aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken2
diff options
context:
space:
mode:
Diffstat (limited to 'sources/shiboken2')
-rw-r--r--sources/shiboken2/.gitattributes2
-rw-r--r--sources/shiboken2/.gitignore8
-rw-r--r--sources/shiboken2/AUTHORS12
-rw-r--r--sources/shiboken2/ApiExtractor/AUTHORS8
-rw-r--r--sources/shiboken2/ApiExtractor/CMakeLists.txt94
-rw-r--r--sources/shiboken2/ApiExtractor/COPYING342
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp3217
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetabuilder.h123
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetabuilder_p.h206
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetalang.cpp2707
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetalang.h1811
-rw-r--r--sources/shiboken2/ApiExtractor/abstractmetalang_typedefs.h51
-rw-r--r--sources/shiboken2/ApiExtractor/apiextractor.cpp264
-rw-r--r--sources/shiboken2/ApiExtractor/apiextractor.h111
-rw-r--r--sources/shiboken2/ApiExtractor/apiextractormacros.h41
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/clangbuilder.cpp1150
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/clangbuilder.h62
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/clangdebugutils.cpp150
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/clangdebugutils.h48
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/clangparser.cpp266
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/clangparser.h93
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/clangutils.cpp276
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/clangutils.h116
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/compilersupport.cpp404
-rw-r--r--sources/shiboken2/ApiExtractor/clangparser/compilersupport.h55
-rw-r--r--sources/shiboken2/ApiExtractor/cmake_uninstall.cmake21
-rw-r--r--sources/shiboken2/ApiExtractor/dependency.h47
-rw-r--r--sources/shiboken2/ApiExtractor/docparser.cpp150
-rw-r--r--sources/shiboken2/ApiExtractor/docparser.h134
-rw-r--r--sources/shiboken2/ApiExtractor/doxygenparser.cpp209
-rw-r--r--sources/shiboken2/ApiExtractor/doxygenparser.h43
-rw-r--r--sources/shiboken2/ApiExtractor/fileout.cpp249
-rw-r--r--sources/shiboken2/ApiExtractor/fileout.h69
-rw-r--r--sources/shiboken2/ApiExtractor/graph.cpp134
-rw-r--r--sources/shiboken2/ApiExtractor/graph.h77
-rw-r--r--sources/shiboken2/ApiExtractor/header_paths.h72
-rw-r--r--sources/shiboken2/ApiExtractor/icecc.cmake11
-rw-r--r--sources/shiboken2/ApiExtractor/include.cpp70
-rw-r--r--sources/shiboken2/ApiExtractor/include.h95
-rw-r--r--sources/shiboken2/ApiExtractor/merge.xsl82
-rw-r--r--sources/shiboken2/ApiExtractor/messages.cpp575
-rw-r--r--sources/shiboken2/ApiExtractor/messages.h176
-rw-r--r--sources/shiboken2/ApiExtractor/parser/codemodel.cpp1551
-rw-r--r--sources/shiboken2/ApiExtractor/parser/codemodel.h804
-rw-r--r--sources/shiboken2/ApiExtractor/parser/codemodel_enums.h64
-rw-r--r--sources/shiboken2/ApiExtractor/parser/codemodel_fwd.h85
-rw-r--r--sources/shiboken2/ApiExtractor/parser/enumvalue.cpp76
-rw-r--r--sources/shiboken2/ApiExtractor/parser/enumvalue.h71
-rw-r--r--sources/shiboken2/ApiExtractor/qtcompat.h40
-rw-r--r--sources/shiboken2/ApiExtractor/qtdocparser.cpp358
-rw-r--r--sources/shiboken2/ApiExtractor/qtdocparser.h53
-rw-r--r--sources/shiboken2/ApiExtractor/reporthandler.cpp188
-rw-r--r--sources/shiboken2/ApiExtractor/reporthandler.h71
-rw-r--r--sources/shiboken2/ApiExtractor/symbols.filter7
-rw-r--r--sources/shiboken2/ApiExtractor/tests/CMakeLists.txt63
-rw-r--r--sources/shiboken2/ApiExtractor/tests/a.xml14
-rw-r--r--sources/shiboken2/ApiExtractor/tests/injectedcode.txt5
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testabstractmetaclass.cpp591
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testabstractmetaclass.h56
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testabstractmetatype.cpp247
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testabstractmetatype.h49
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testaddfunction.cpp467
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testaddfunction.h54
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testarrayargument.cpp171
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testarrayargument.h43
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testcodeinjection.cpp131
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testcodeinjection.h46
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testcodeinjection.qrc6
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testcontainer.cpp107
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testcontainer.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testconversionoperator.cpp188
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testconversionoperator.h44
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testconversionruletag.cpp250
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testconversionruletag.h43
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testctorinformation.cpp76
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testctorinformation.h44
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testdroptypeentries.cpp147
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testdroptypeentries.h44
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testdtorinformation.cpp119
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testdtorinformation.h47
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testenum.cpp435
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testenum.h47
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testextrainclude.cpp86
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testextrainclude.h42
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testfunctiontag.cpp97
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testfunctiontag.h42
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testimplicitconversions.cpp163
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testimplicitconversions.h46
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testinserttemplate.cpp86
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testinserttemplate.h42
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.cpp107
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.qrc5
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testmodifyfunction.cpp466
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testmodifyfunction.h49
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testmultipleinheritance.cpp75
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testmultipleinheritance.h43
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testnamespace.cpp96
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testnamespace.h44
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testnestedtypes.cpp128
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testnestedtypes.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testnumericaltypedef.cpp119
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testnumericaltypedef.h42
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testprimitivetypetag.cpp60
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testprimitivetypetag.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testrefcounttag.cpp101
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testrefcounttag.h42
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testreferencetopointer.cpp59
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testreferencetopointer.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testremovefield.cpp62
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testremovefield.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testremoveimplconv.cpp69
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testremoveimplconv.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testremoveoperatormethod.cpp117
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testremoveoperatormethod.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testresolvetype.cpp66
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testresolvetype.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testreverseoperators.cpp139
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testreverseoperators.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testtemplates.cpp644
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testtemplates.h55
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testtoposort.cpp68
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testtoposort.h42
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testtyperevision.cpp107
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testtyperevision.h44
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testutil.h82
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testvaluetypedefaultctortag.cpp64
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testvaluetypedefaultctortag.h41
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testvoidarg.cpp87
-rw-r--r--sources/shiboken2/ApiExtractor/tests/testvoidarg.h42
-rw-r--r--sources/shiboken2/ApiExtractor/tests/utf8code.txt1
-rw-r--r--sources/shiboken2/ApiExtractor/typedatabase.cpp1039
-rw-r--r--sources/shiboken2/ApiExtractor/typedatabase.h222
-rw-r--r--sources/shiboken2/ApiExtractor/typedatabase_typedefs.h69
-rw-r--r--sources/shiboken2/ApiExtractor/typeparser.cpp305
-rw-r--r--sources/shiboken2/ApiExtractor/typeparser.h45
-rw-r--r--sources/shiboken2/ApiExtractor/typesystem.cpp1186
-rw-r--r--sources/shiboken2/ApiExtractor/typesystem.h1662
-rw-r--r--sources/shiboken2/ApiExtractor/typesystem_enums.h110
-rw-r--r--sources/shiboken2/ApiExtractor/typesystem_typedefs.h53
-rw-r--r--sources/shiboken2/ApiExtractor/typesystemparser.cpp3076
-rw-r--r--sources/shiboken2/ApiExtractor/typesystemparser.h279
-rw-r--r--sources/shiboken2/ApiExtractor/xmlutils.cpp68
-rw-r--r--sources/shiboken2/ApiExtractor/xmlutils.h53
-rw-r--r--sources/shiboken2/ApiExtractor/xmlutils_libxslt.cpp231
-rw-r--r--sources/shiboken2/ApiExtractor/xmlutils_libxslt.h40
-rw-r--r--sources/shiboken2/ApiExtractor/xmlutils_qt.cpp102
-rw-r--r--sources/shiboken2/ApiExtractor/xmlutils_qt.h40
-rw-r--r--sources/shiboken2/CMakeLists.txt229
-rw-r--r--sources/shiboken2/COPYING342
-rw-r--r--sources/shiboken2/COPYING.libsample501
-rw-r--r--sources/shiboken2/COPYING.libshiboken501
-rw-r--r--sources/shiboken2/Doxyfile311
-rw-r--r--sources/shiboken2/cmake_uninstall.cmake21
-rw-r--r--sources/shiboken2/data/CMakeLists.txt61
-rw-r--r--sources/shiboken2/data/GeneratorRunnerConfig.cmake.in17
-rw-r--r--sources/shiboken2/data/GeneratorRunnerConfigVersion.cmake.in10
-rw-r--r--sources/shiboken2/data/Shiboken2Config-spec.cmake.in41
-rw-r--r--sources/shiboken2/data/Shiboken2Config.cmake.in5
-rw-r--r--sources/shiboken2/data/Shiboken2ConfigVersion.cmake.in10
l---------sources/shiboken2/data/docgenerator.11
-rw-r--r--sources/shiboken2/data/generatorrunner.176
-rw-r--r--sources/shiboken2/data/generatorrunner.pc.in13
-rw-r--r--sources/shiboken2/data/shiboken2.pc.in13
-rw-r--r--sources/shiboken2/data/shiboken_helpers.cmake476
-rw-r--r--sources/shiboken2/doc/CMakeLists.txt23
-rw-r--r--sources/shiboken2/doc/README.md12
-rw-r--r--sources/shiboken2/doc/_templates/index.html35
-rw-r--r--sources/shiboken2/doc/_templates/layout.html29
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/searchbox.html12
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/static/bg_header.pngbin36012 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/static/bg_topo.jpgbin14237 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/static/fakebar.pngbin101 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/static/logo_python.jpgbin2660 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/static/logo_qt.pngbin1032 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/static/pyside.css2071
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/static/pysidelogo.pngbin4936 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/static/relbar_bg.pngbin130 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/_themes/pysidedocs/theme.conf7
-rw-r--r--sources/shiboken2/doc/conf.py.in160
-rw-r--r--sources/shiboken2/doc/considerations.rst183
-rw-r--r--sources/shiboken2/doc/dependency-pyside.svg527
-rw-r--r--sources/shiboken2/doc/examples/index.rst9
-rw-r--r--sources/shiboken2/doc/examples/samplebinding.rst246
-rw-r--r--sources/shiboken2/doc/gettingstarted.rst61
-rw-r--r--sources/shiboken2/doc/images/.directory3
-rw-r--r--sources/shiboken2/doc/images/bindinggen-development.pngbin32698 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/images/bindinggen-development.svg542
-rw-r--r--sources/shiboken2/doc/images/boostgen.pngbin153473 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/images/converter.pngbin22467 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/images/converter.svg349
-rw-r--r--sources/shiboken2/doc/images/genrunnerarch.pngbin68761 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/images/genrunnerarch.svg654
-rw-r--r--sources/shiboken2/doc/images/icecream.pngbin4272 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/images/qtforpython-underthehood.pngbin19144 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/images/shibokenqtarch.pngbin17602 -> 0 bytes
-rw-r--r--sources/shiboken2/doc/images/shibokenqtarch.svg188
-rw-r--r--sources/shiboken2/doc/index.rst52
-rw-r--r--sources/shiboken2/doc/shibokengenerator.rst315
-rw-r--r--sources/shiboken2/doc/shibokenmodule.rst79
-rw-r--r--sources/shiboken2/doc/typesystem.rst57
-rw-r--r--sources/shiboken2/doc/typesystem_arguments.rst206
-rw-r--r--sources/shiboken2/doc/typesystem_codeinjection.rst399
-rw-r--r--sources/shiboken2/doc/typesystem_conversionrule.rst116
-rw-r--r--sources/shiboken2/doc/typesystem_converters.rst291
-rw-r--r--sources/shiboken2/doc/typesystem_documentation.rst43
-rw-r--r--sources/shiboken2/doc/typesystem_manipulating_objects.rst190
-rw-r--r--sources/shiboken2/doc/typesystem_modify_function.rst78
-rw-r--r--sources/shiboken2/doc/typesystem_ownership.rst229
-rw-r--r--sources/shiboken2/doc/typesystem_sequenceprotocol.rst29
-rw-r--r--sources/shiboken2/doc/typesystem_solving_compilation.rst70
-rw-r--r--sources/shiboken2/doc/typesystem_specifying_types.rst481
-rw-r--r--sources/shiboken2/doc/typesystem_templates.rst55
-rw-r--r--sources/shiboken2/doc/typesystem_variables.rst359
-rw-r--r--sources/shiboken2/generator/CMakeLists.txt63
-rw-r--r--sources/shiboken2/generator/__init__.py.in2
-rw-r--r--sources/shiboken2/generator/_config.py.in9
-rw-r--r--sources/shiboken2/generator/generator.cpp989
-rw-r--r--sources/shiboken2/generator/generator.h433
-rw-r--r--sources/shiboken2/generator/indentor.h85
-rw-r--r--sources/shiboken2/generator/main.cpp643
-rw-r--r--sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp2408
-rw-r--r--sources/shiboken2/generator/qtdoc/qtdocgenerator.h284
-rw-r--r--sources/shiboken2/generator/shiboken2/cppgenerator.cpp6181
-rw-r--r--sources/shiboken2/generator/shiboken2/cppgenerator.h396
-rw-r--r--sources/shiboken2/generator/shiboken2/headergenerator.cpp652
-rw-r--r--sources/shiboken2/generator/shiboken2/headergenerator.h70
-rw-r--r--sources/shiboken2/generator/shiboken2/overloaddata.cpp1091
-rw-r--r--sources/shiboken2/generator/shiboken2/overloaddata.h163
-rw-r--r--sources/shiboken2/generator/shiboken2/shibokengenerator.cpp2855
-rw-r--r--sources/shiboken2/generator/shiboken2/shibokengenerator.h573
-rw-r--r--sources/shiboken2/generator/shibokenconfig.h.in6
-rw-r--r--sources/shiboken2/generatorrunnerconfig.h.in13
-rw-r--r--sources/shiboken2/generatorrunnermacros.h48
-rw-r--r--sources/shiboken2/generators/shiboken/shiboken.cpp32
-rw-r--r--sources/shiboken2/icecc.cmake11
-rw-r--r--sources/shiboken2/libshiboken/CMakeLists.txt152
-rw-r--r--sources/shiboken2/libshiboken/autodecref.h111
-rw-r--r--sources/shiboken2/libshiboken/basewrapper.cpp1755
-rw-r--r--sources/shiboken2/libshiboken/basewrapper.h464
-rw-r--r--sources/shiboken2/libshiboken/basewrapper_p.h289
-rw-r--r--sources/shiboken2/libshiboken/bindingmanager.cpp348
-rw-r--r--sources/shiboken2/libshiboken/bindingmanager.h110
-rw-r--r--sources/shiboken2/libshiboken/bufferprocs_py37.cpp396
-rw-r--r--sources/shiboken2/libshiboken/bufferprocs_py37.h145
-rw-r--r--sources/shiboken2/libshiboken/debugfreehook.cpp194
-rw-r--r--sources/shiboken2/libshiboken/debugfreehook.h61
-rw-r--r--sources/shiboken2/libshiboken/embed/embedding_generator.py242
-rw-r--r--sources/shiboken2/libshiboken/embed/module_collector.py105
-rw-r--r--sources/shiboken2/libshiboken/embed/qt_python_license.txt87
-rw-r--r--sources/shiboken2/libshiboken/embed/signature_bootstrap.py180
-rw-r--r--sources/shiboken2/libshiboken/gilstate.cpp67
-rw-r--r--sources/shiboken2/libshiboken/gilstate.h68
-rw-r--r--sources/shiboken2/libshiboken/helper.cpp281
-rw-r--r--sources/shiboken2/libshiboken/helper.h124
-rw-r--r--sources/shiboken2/libshiboken/pep384_issue33738.cpp121
-rw-r--r--sources/shiboken2/libshiboken/pep384impl.cpp802
-rw-r--r--sources/shiboken2/libshiboken/pep384impl.h557
-rw-r--r--sources/shiboken2/libshiboken/pep384impl_doc.rst721
-rw-r--r--sources/shiboken2/libshiboken/python25compat.h104
-rw-r--r--sources/shiboken2/libshiboken/qapp_macro.cpp100
-rw-r--r--sources/shiboken2/libshiboken/qapp_macro.h52
-rw-r--r--sources/shiboken2/libshiboken/qt_attribution.json12
-rw-r--r--sources/shiboken2/libshiboken/sbkarrayconverter.cpp289
-rw-r--r--sources/shiboken2/libshiboken/sbkarrayconverter.h174
-rw-r--r--sources/shiboken2/libshiboken/sbkarrayconverter_p.h62
-rw-r--r--sources/shiboken2/libshiboken/sbkconverter.cpp597
-rw-r--r--sources/shiboken2/libshiboken/sbkconverter.h405
-rw-r--r--sources/shiboken2/libshiboken/sbkconverter_p.h575
-rw-r--r--sources/shiboken2/libshiboken/sbkdbg.h129
-rw-r--r--sources/shiboken2/libshiboken/sbkenum.cpp802
-rw-r--r--sources/shiboken2/libshiboken/sbkenum.h123
-rw-r--r--sources/shiboken2/libshiboken/sbkmodule.cpp111
-rw-r--r--sources/shiboken2/libshiboken/sbkmodule.h115
-rw-r--r--sources/shiboken2/libshiboken/sbknumpyarrayconverter.cpp308
-rw-r--r--sources/shiboken2/libshiboken/sbkpython.h144
-rw-r--r--sources/shiboken2/libshiboken/sbkstaticstrings.cpp96
-rw-r--r--sources/shiboken2/libshiboken/sbkstaticstrings.h68
-rw-r--r--sources/shiboken2/libshiboken/sbkstaticstrings_p.h74
-rw-r--r--sources/shiboken2/libshiboken/sbkstring.cpp272
-rw-r--r--sources/shiboken2/libshiboken/sbkstring.h71
-rw-r--r--sources/shiboken2/libshiboken/sbkversion.h.in53
-rw-r--r--sources/shiboken2/libshiboken/shiboken.h60
-rw-r--r--sources/shiboken2/libshiboken/shibokenbuffer.cpp103
-rw-r--r--sources/shiboken2/libshiboken/shibokenbuffer.h85
-rw-r--r--sources/shiboken2/libshiboken/shibokenmacros.h63
-rw-r--r--sources/shiboken2/libshiboken/signature.cpp1262
-rw-r--r--sources/shiboken2/libshiboken/signature.h56
-rw-r--r--sources/shiboken2/libshiboken/signature_doc.rst357
-rw-r--r--sources/shiboken2/libshiboken/threadstatesaver.cpp67
-rw-r--r--sources/shiboken2/libshiboken/threadstatesaver.h68
-rw-r--r--sources/shiboken2/libshiboken/tmp-referencetopython/sbkconverter.cpp216
-rw-r--r--sources/shiboken2/libshiboken/tmp-referencetopython/sbkconverter.h191
-rw-r--r--sources/shiboken2/libshiboken/typespec.cpp777
-rw-r--r--sources/shiboken2/libshiboken/typespec.h153
-rw-r--r--sources/shiboken2/libshiboken/voidptr.cpp480
-rw-r--r--sources/shiboken2/libshiboken/voidptr.h65
-rwxr-xr-xsources/shiboken2/shiboken_tool.py53
-rw-r--r--sources/shiboken2/shiboken_version.py55
-rw-r--r--sources/shiboken2/shibokenmodule/CMakeLists.txt88
-rw-r--r--sources/shiboken2/shibokenmodule/__init__.py.in30
-rw-r--r--sources/shiboken2/shibokenmodule/_config.py.in11
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/__init__.py40
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/backport_inspect.py900
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/fix-complaints.py98
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/PSF-3.7.0.txt43
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/__init__.py42
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/errorhandler.py148
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/importhandler.py103
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/layout.py282
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/__init__.py40
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/enum_sig.py219
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py154
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/loader.py221
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/mapping.py645
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/parser.py458
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/qt_attribution.json13
-rw-r--r--sources/shiboken2/shibokenmodule/files.dir/shibokensupport/typing27.py2636
-rw-r--r--sources/shiboken2/shibokenmodule/nothing.h0
-rw-r--r--sources/shiboken2/shibokenmodule/shibokenmodule.txt.in16
-rw-r--r--sources/shiboken2/shibokenmodule/typesystem_shiboken.xml129
-rw-r--r--sources/shiboken2/tests/CMakeLists.txt93
-rw-r--r--sources/shiboken2/tests/dumpcodemodel/CMakeLists.txt6
-rw-r--r--sources/shiboken2/tests/dumpcodemodel/main.cpp227
-rw-r--r--sources/shiboken2/tests/libminimal/CMakeLists.txt13
-rw-r--r--sources/shiboken2/tests/libminimal/libminimalmacros.h46
-rw-r--r--sources/shiboken2/tests/libminimal/listuser.cpp124
-rw-r--r--sources/shiboken2/tests/libminimal/listuser.h75
-rw-r--r--sources/shiboken2/tests/libminimal/minbool.h68
-rw-r--r--sources/shiboken2/tests/libminimal/obj.cpp44
-rw-r--r--sources/shiboken2/tests/libminimal/obj.h59
-rw-r--r--sources/shiboken2/tests/libminimal/typedef.cpp75
-rw-r--r--sources/shiboken2/tests/libminimal/typedef.h54
-rw-r--r--sources/shiboken2/tests/libminimal/val.h59
-rw-r--r--sources/shiboken2/tests/libother/CMakeLists.txt17
-rw-r--r--sources/shiboken2/tests/libother/extendsnoimplicitconversion.h45
-rw-r--r--sources/shiboken2/tests/libother/libothermacros.h46
-rw-r--r--sources/shiboken2/tests/libother/number.cpp59
-rw-r--r--sources/shiboken2/tests/libother/number.h57
-rw-r--r--sources/shiboken2/tests/libother/otherderived.cpp64
-rw-r--r--sources/shiboken2/tests/libother/otherderived.h68
-rw-r--r--sources/shiboken2/tests/libother/othermultiplederived.cpp50
-rw-r--r--sources/shiboken2/tests/libother/othermultiplederived.h46
-rw-r--r--sources/shiboken2/tests/libother/otherobjecttype.cpp46
-rw-r--r--sources/shiboken2/tests/libother/otherobjecttype.h52
-rw-r--r--sources/shiboken2/tests/libother/smartptrtester.cpp55
-rw-r--r--sources/shiboken2/tests/libother/smartptrtester.h49
-rw-r--r--sources/shiboken2/tests/libsample/CMakeLists.txt59
-rw-r--r--sources/shiboken2/tests/libsample/abstract.cpp97
-rw-r--r--sources/shiboken2/tests/libsample/abstract.h108
-rw-r--r--sources/shiboken2/tests/libsample/blackbox.cpp131
-rw-r--r--sources/shiboken2/tests/libsample/blackbox.h67
-rw-r--r--sources/shiboken2/tests/libsample/bucket.cpp86
-rw-r--r--sources/shiboken2/tests/libsample/bucket.h59
-rw-r--r--sources/shiboken2/tests/libsample/bytearray.cpp214
-rw-r--r--sources/shiboken2/tests/libsample/bytearray.h89
-rw-r--r--sources/shiboken2/tests/libsample/collector.cpp62
-rw-r--r--sources/shiboken2/tests/libsample/collector.h71
-rw-r--r--sources/shiboken2/tests/libsample/complex.cpp54
-rw-r--r--sources/shiboken2/tests/libsample/complex.h55
-rw-r--r--sources/shiboken2/tests/libsample/ctorconvrule.h45
-rw-r--r--sources/shiboken2/tests/libsample/cvlist.h53
-rw-r--r--sources/shiboken2/tests/libsample/derived.cpp125
-rw-r--r--sources/shiboken2/tests/libsample/derived.h95
-rw-r--r--sources/shiboken2/tests/libsample/echo.cpp29
-rw-r--r--sources/shiboken2/tests/libsample/echo.h55
-rw-r--r--sources/shiboken2/tests/libsample/exceptiontest.cpp64
-rw-r--r--sources/shiboken2/tests/libsample/exceptiontest.h48
-rw-r--r--sources/shiboken2/tests/libsample/expression.cpp137
-rw-r--r--sources/shiboken2/tests/libsample/expression.h64
-rw-r--r--sources/shiboken2/tests/libsample/filter.cpp73
-rw-r--r--sources/shiboken2/tests/libsample/filter.h99
-rw-r--r--sources/shiboken2/tests/libsample/functions.cpp255
-rw-r--r--sources/shiboken2/tests/libsample/functions.h104
-rw-r--r--sources/shiboken2/tests/libsample/handle.cpp44
-rw-r--r--sources/shiboken2/tests/libsample/handle.h72
-rw-r--r--sources/shiboken2/tests/libsample/implicitconv.cpp66
-rw-r--r--sources/shiboken2/tests/libsample/implicitconv.h83
-rw-r--r--sources/shiboken2/tests/libsample/injectcode.cpp108
-rw-r--r--sources/shiboken2/tests/libsample/injectcode.h65
-rw-r--r--sources/shiboken2/tests/libsample/libsamplemacros.h46
-rw-r--r--sources/shiboken2/tests/libsample/list.h106
-rw-r--r--sources/shiboken2/tests/libsample/listuser.cpp91
-rw-r--r--sources/shiboken2/tests/libsample/listuser.h74
-rw-r--r--sources/shiboken2/tests/libsample/main.cpp244
-rw-r--r--sources/shiboken2/tests/libsample/mapuser.cpp74
-rw-r--r--sources/shiboken2/tests/libsample/mapuser.h67
-rw-r--r--sources/shiboken2/tests/libsample/modelindex.h72
-rw-r--r--sources/shiboken2/tests/libsample/modifications.cpp186
-rw-r--r--sources/shiboken2/tests/libsample/modifications.h160
-rw-r--r--sources/shiboken2/tests/libsample/modified_constructor.cpp42
-rw-r--r--sources/shiboken2/tests/libsample/modified_constructor.h46
-rw-r--r--sources/shiboken2/tests/libsample/multiple_derived.cpp64
-rw-r--r--sources/shiboken2/tests/libsample/multiple_derived.h195
-rw-r--r--sources/shiboken2/tests/libsample/noimplicitconversion.h49
-rw-r--r--sources/shiboken2/tests/libsample/nondefaultctor.h75
-rw-r--r--sources/shiboken2/tests/libsample/nontypetemplate.h52
-rw-r--r--sources/shiboken2/tests/libsample/null.h44
-rw-r--r--sources/shiboken2/tests/libsample/objectmodel.cpp42
-rw-r--r--sources/shiboken2/tests/libsample/objectmodel.h58
-rw-r--r--sources/shiboken2/tests/libsample/objecttype.cpp312
-rw-r--r--sources/shiboken2/tests/libsample/objecttype.h185
-rw-r--r--sources/shiboken2/tests/libsample/objecttypebyvalue.h46
-rw-r--r--sources/shiboken2/tests/libsample/objecttypeholder.cpp52
-rw-r--r--sources/shiboken2/tests/libsample/objecttypeholder.h51
-rw-r--r--sources/shiboken2/tests/libsample/objecttypelayout.cpp68
-rw-r--r--sources/shiboken2/tests/libsample/objecttypelayout.h56
-rw-r--r--sources/shiboken2/tests/libsample/objecttypeoperators.cpp63
-rw-r--r--sources/shiboken2/tests/libsample/objecttypeoperators.h61
-rw-r--r--sources/shiboken2/tests/libsample/objectview.cpp54
-rw-r--r--sources/shiboken2/tests/libsample/objectview.h58
-rw-r--r--sources/shiboken2/tests/libsample/oddbool.h83
-rw-r--r--sources/shiboken2/tests/libsample/onlycopy.cpp83
-rw-r--r--sources/shiboken2/tests/libsample/onlycopy.h63
-rw-r--r--sources/shiboken2/tests/libsample/overload.cpp50
-rw-r--r--sources/shiboken2/tests/libsample/overload.h143
-rw-r--r--sources/shiboken2/tests/libsample/overloadsort.cpp30
-rw-r--r--sources/shiboken2/tests/libsample/overloadsort.h88
-rw-r--r--sources/shiboken2/tests/libsample/pairuser.cpp57
-rw-r--r--sources/shiboken2/tests/libsample/pairuser.h55
-rw-r--r--sources/shiboken2/tests/libsample/pen.cpp67
-rw-r--r--sources/shiboken2/tests/libsample/pen.h62
-rw-r--r--sources/shiboken2/tests/libsample/photon.cpp50
-rw-r--r--sources/shiboken2/tests/libsample/photon.h140
-rw-r--r--sources/shiboken2/tests/libsample/point.cpp155
-rw-r--r--sources/shiboken2/tests/libsample/point.h99
-rw-r--r--sources/shiboken2/tests/libsample/pointerholder.h45
-rw-r--r--sources/shiboken2/tests/libsample/pointf.cpp126
-rw-r--r--sources/shiboken2/tests/libsample/pointf.h88
-rw-r--r--sources/shiboken2/tests/libsample/polygon.cpp75
-rw-r--r--sources/shiboken2/tests/libsample/polygon.h66
-rw-r--r--sources/shiboken2/tests/libsample/privatector.h55
-rw-r--r--sources/shiboken2/tests/libsample/privatedtor.h60
-rw-r--r--sources/shiboken2/tests/libsample/protected.cpp32
-rw-r--r--sources/shiboken2/tests/libsample/protected.h151
-rw-r--r--sources/shiboken2/tests/libsample/rect.h86
-rw-r--r--sources/shiboken2/tests/libsample/reference.cpp78
-rw-r--r--sources/shiboken2/tests/libsample/reference.h81
-rw-r--r--sources/shiboken2/tests/libsample/removednamespaces.h68
-rw-r--r--sources/shiboken2/tests/libsample/renaming.cpp46
-rw-r--r--sources/shiboken2/tests/libsample/renaming.h50
-rw-r--r--sources/shiboken2/tests/libsample/sample.cpp47
-rw-r--r--sources/shiboken2/tests/libsample/sample.h51
-rw-r--r--sources/shiboken2/tests/libsample/samplenamespace.cpp135
-rw-r--r--sources/shiboken2/tests/libsample/samplenamespace.h179
-rw-r--r--sources/shiboken2/tests/libsample/sbkdate.cpp48
-rw-r--r--sources/shiboken2/tests/libsample/sbkdate.h50
-rw-r--r--sources/shiboken2/tests/libsample/simplefile.cpp108
-rw-r--r--sources/shiboken2/tests/libsample/simplefile.h56
-rw-r--r--sources/shiboken2/tests/libsample/size.cpp39
-rw-r--r--sources/shiboken2/tests/libsample/size.h206
-rw-r--r--sources/shiboken2/tests/libsample/sometime.cpp99
-rw-r--r--sources/shiboken2/tests/libsample/sometime.h92
-rw-r--r--sources/shiboken2/tests/libsample/str.cpp185
-rw-r--r--sources/shiboken2/tests/libsample/str.h78
-rw-r--r--sources/shiboken2/tests/libsample/strlist.cpp57
-rw-r--r--sources/shiboken2/tests/libsample/strlist.h65
-rw-r--r--sources/shiboken2/tests/libsample/templateptr.cpp33
-rw-r--r--sources/shiboken2/tests/libsample/templateptr.h43
-rw-r--r--sources/shiboken2/tests/libsample/transform.cpp65
-rw-r--r--sources/shiboken2/tests/libsample/transform.h45
-rw-r--r--sources/shiboken2/tests/libsample/valueandvirtual.h47
-rw-r--r--sources/shiboken2/tests/libsample/virtualmethods.cpp78
-rw-r--r--sources/shiboken2/tests/libsample/virtualmethods.h157
-rw-r--r--sources/shiboken2/tests/libsample/voidholder.h54
-rw-r--r--sources/shiboken2/tests/libsmart/CMakeLists.txt11
-rw-r--r--sources/shiboken2/tests/libsmart/libsmartmacros.h46
-rw-r--r--sources/shiboken2/tests/libsmart/smart.cpp261
-rw-r--r--sources/shiboken2/tests/libsmart/smart.h37
-rw-r--r--sources/shiboken2/tests/libsmart/smart_integer.h56
-rw-r--r--sources/shiboken2/tests/libsmart/smart_obj.h62
-rw-r--r--sources/shiboken2/tests/libsmart/smart_registry.h68
-rw-r--r--sources/shiboken2/tests/libsmart/smart_sharedptr.h140
-rw-r--r--sources/shiboken2/tests/minimalbinding/CMakeLists.txt36
-rw-r--r--sources/shiboken2/tests/minimalbinding/brace_pattern_test.py125
-rw-r--r--sources/shiboken2/tests/minimalbinding/global.h33
-rw-r--r--sources/shiboken2/tests/minimalbinding/listuser_test.py330
-rw-r--r--sources/shiboken2/tests/minimalbinding/minbool_test.py70
-rw-r--r--sources/shiboken2/tests/minimalbinding/minimal-binding.txt.in15
-rw-r--r--sources/shiboken2/tests/minimalbinding/obj_test.py120
-rw-r--r--sources/shiboken2/tests/minimalbinding/typedef_test.py122
-rw-r--r--sources/shiboken2/tests/minimalbinding/typesystem_minimal.xml93
-rw-r--r--sources/shiboken2/tests/minimalbinding/val_test.py121
-rw-r--r--sources/shiboken2/tests/otherbinding/CMakeLists.txt46
-rw-r--r--sources/shiboken2/tests/otherbinding/collector_external_operator_test.py64
-rw-r--r--sources/shiboken2/tests/otherbinding/conversion_operator_for_class_without_implicit_conversions_test.py79
-rw-r--r--sources/shiboken2/tests/otherbinding/extended_multiply_operator_test.py70
-rw-r--r--sources/shiboken2/tests/otherbinding/global.h36
-rw-r--r--sources/shiboken2/tests/otherbinding/module_reload_test.py65
-rw-r--r--sources/shiboken2/tests/otherbinding/new_ctor_operator_test.py62
-rw-r--r--sources/shiboken2/tests/otherbinding/objtypehashes_test.py59
-rw-r--r--sources/shiboken2/tests/otherbinding/other-binding.txt.in20
-rw-r--r--sources/shiboken2/tests/otherbinding/otherderived_test.py125
-rw-r--r--sources/shiboken2/tests/otherbinding/signature_test.py54
-rw-r--r--sources/shiboken2/tests/otherbinding/smartptr_test.py61
-rw-r--r--sources/shiboken2/tests/otherbinding/test_module_template.py40
-rw-r--r--sources/shiboken2/tests/otherbinding/typediscovery_test.py72
-rw-r--r--sources/shiboken2/tests/otherbinding/typesystem_other.xml20
-rw-r--r--sources/shiboken2/tests/otherbinding/usersprimitivefromothermodule_test.py58
-rw-r--r--sources/shiboken2/tests/otherbinding/wrongctor_test.py59
-rw-r--r--sources/shiboken2/tests/py3k.py2
-rw-r--r--sources/shiboken2/tests/py3kcompat.py82
-rw-r--r--sources/shiboken2/tests/samplebinding/CMakeLists.txt153
-rw-r--r--sources/shiboken2/tests/samplebinding/__del___test.py57
-rw-r--r--sources/shiboken2/tests/samplebinding/abstract_test.py116
-rw-r--r--sources/shiboken2/tests/samplebinding/addedfunction_test.py68
-rw-r--r--sources/shiboken2/tests/samplebinding/addedfunction_with_container_args_test.py57
-rw-r--r--sources/shiboken2/tests/samplebinding/argumentmodifications_test.py116
-rw-r--r--sources/shiboken2/tests/samplebinding/array_numpy_test.py70
-rw-r--r--sources/shiboken2/tests/samplebinding/array_sequence_test.py59
-rw-r--r--sources/shiboken2/tests/samplebinding/bug_554_test.py51
-rw-r--r--sources/shiboken2/tests/samplebinding/bug_704_test.py74
-rw-r--r--sources/shiboken2/tests/samplebinding/bytearray_bufferprotocol.cpp55
-rw-r--r--sources/shiboken2/tests/samplebinding/bytearray_test.py157
-rw-r--r--sources/shiboken2/tests/samplebinding/child_return_test.py63
-rw-r--r--sources/shiboken2/tests/samplebinding/class_fields_test.py174
-rw-r--r--sources/shiboken2/tests/samplebinding/collector_test.py86
-rw-r--r--sources/shiboken2/tests/samplebinding/complex_test.py89
-rw-r--r--sources/shiboken2/tests/samplebinding/conversion_operator_test.py61
-rw-r--r--sources/shiboken2/tests/samplebinding/copy_test.py92
-rw-r--r--sources/shiboken2/tests/samplebinding/ctorconvrule_test.py55
-rw-r--r--sources/shiboken2/tests/samplebinding/cyclic_test.py115
-rw-r--r--sources/shiboken2/tests/samplebinding/date_test.py63
-rw-r--r--sources/shiboken2/tests/samplebinding/decisor_test.py73
-rw-r--r--sources/shiboken2/tests/samplebinding/delete_test.py53
-rw-r--r--sources/shiboken2/tests/samplebinding/deprecated_test.py50
-rw-r--r--sources/shiboken2/tests/samplebinding/derived_test.py158
-rw-r--r--sources/shiboken2/tests/samplebinding/duck_punching_test.py182
-rw-r--r--sources/shiboken2/tests/samplebinding/echo_test.py58
-rw-r--r--sources/shiboken2/tests/samplebinding/enum_test.py188
-rw-r--r--sources/shiboken2/tests/samplebinding/enumfromremovednamespace_test.py59
-rw-r--r--sources/shiboken2/tests/samplebinding/event_loop_call_virtual_test.py76
-rw-r--r--sources/shiboken2/tests/samplebinding/event_loop_thread_test.py102
-rw-r--r--sources/shiboken2/tests/samplebinding/exception_test.py84
-rw-r--r--sources/shiboken2/tests/samplebinding/filter_test.py51
-rw-r--r--sources/shiboken2/tests/samplebinding/global.h93
-rw-r--r--sources/shiboken2/tests/samplebinding/handleholder_test.py63
-rw-r--r--sources/shiboken2/tests/samplebinding/hashabletype_test.py60
-rw-r--r--sources/shiboken2/tests/samplebinding/ignorederefop_test.py44
-rw-r--r--sources/shiboken2/tests/samplebinding/implicitconv_numerical_test.py157
-rw-r--r--sources/shiboken2/tests/samplebinding/implicitconv_test.py72
-rw-r--r--sources/shiboken2/tests/samplebinding/inheritanceandscope_test.py54
-rw-r--r--sources/shiboken2/tests/samplebinding/injectcode_test.py138
-rw-r--r--sources/shiboken2/tests/samplebinding/innerclass_test.py48
-rw-r--r--sources/shiboken2/tests/samplebinding/intlist_test.py104
-rw-r--r--sources/shiboken2/tests/samplebinding/invalid_virtual_return_test.py71
-rw-r--r--sources/shiboken2/tests/samplebinding/keep_reference_test.py87
-rw-r--r--sources/shiboken2/tests/samplebinding/list_test.py127
-rw-r--r--sources/shiboken2/tests/samplebinding/lock_test.py101
-rw-r--r--sources/shiboken2/tests/samplebinding/map_test.py86
-rw-r--r--sources/shiboken2/tests/samplebinding/metaclass_test.py68
-rw-r--r--sources/shiboken2/tests/samplebinding/mi_virtual_methods_test.py94
-rw-r--r--sources/shiboken2/tests/samplebinding/mixed_mi_test.py82
-rw-r--r--sources/shiboken2/tests/samplebinding/modelindex_test.py59
-rw-r--r--sources/shiboken2/tests/samplebinding/modelview_test.py84
-rw-r--r--sources/shiboken2/tests/samplebinding/modifications_test.py248
-rw-r--r--sources/shiboken2/tests/samplebinding/modified_constructor_test.py55
-rw-r--r--sources/shiboken2/tests/samplebinding/modifiedvirtualmethods_test.py254
-rw-r--r--sources/shiboken2/tests/samplebinding/multi_cpp_inheritance_test.py110
-rw-r--r--sources/shiboken2/tests/samplebinding/multiple_derived_test.py226
-rw-r--r--sources/shiboken2/tests/samplebinding/namespace_test.py95
-rw-r--r--sources/shiboken2/tests/samplebinding/newdivision_test.py50
-rw-r--r--sources/shiboken2/tests/samplebinding/nondefaultctor_test.py76
-rw-r--r--sources/shiboken2/tests/samplebinding/nontypetemplate_test.py65
-rw-r--r--sources/shiboken2/tests/samplebinding/nonzero_test.py50
-rw-r--r--sources/shiboken2/tests/samplebinding/numericaltypedef_test.py62
-rw-r--r--sources/shiboken2/tests/samplebinding/numpy_test.py64
-rw-r--r--sources/shiboken2/tests/samplebinding/objecttype_test.py136
-rw-r--r--sources/shiboken2/tests/samplebinding/objecttype_with_named_args_test.py78
-rw-r--r--sources/shiboken2/tests/samplebinding/objecttypebyvalue_test.py50
-rw-r--r--sources/shiboken2/tests/samplebinding/objecttypelayout_test.py307
-rw-r--r--sources/shiboken2/tests/samplebinding/objecttypeoperators_test.py66
-rw-r--r--sources/shiboken2/tests/samplebinding/objecttypereferenceasvirtualmethodargument_test.py55
-rw-r--r--sources/shiboken2/tests/samplebinding/oddbool_test.py84
-rw-r--r--sources/shiboken2/tests/samplebinding/oldstyleclass_as_number_test.py89
-rw-r--r--sources/shiboken2/tests/samplebinding/onlycopyclass_test.py64
-rw-r--r--sources/shiboken2/tests/samplebinding/overflow_test.py92
-rw-r--r--sources/shiboken2/tests/samplebinding/overload_sorting_test.py98
-rw-r--r--sources/shiboken2/tests/samplebinding/overload_test.py215
-rw-r--r--sources/shiboken2/tests/samplebinding/overloadwithdefault_test.py70
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_argument_invalidation_test.py67
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_delete_child_in_cpp_test.py60
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_delete_child_in_python_test.py66
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_delete_parent_test.py87
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_invalidate_after_use_test.py115
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_invalidate_child_test.py75
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_invalidate_nonpolymorphic_test.py58
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_invalidate_parent_test.py74
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_reparenting_test.py136
-rw-r--r--sources/shiboken2/tests/samplebinding/ownership_transference_test.py90
-rw-r--r--sources/shiboken2/tests/samplebinding/pair_test.py110
-rw-r--r--sources/shiboken2/tests/samplebinding/pen_test.py69
-rw-r--r--sources/shiboken2/tests/samplebinding/point_test.py114
-rw-r--r--sources/shiboken2/tests/samplebinding/pointerholder_test.py64
-rw-r--r--sources/shiboken2/tests/samplebinding/pointerprimitivetype_test.py85
-rw-r--r--sources/shiboken2/tests/samplebinding/pointf_test.py75
-rw-r--r--sources/shiboken2/tests/samplebinding/primitivereferenceargument_test.py55
-rw-r--r--sources/shiboken2/tests/samplebinding/privatector_test.py89
-rw-r--r--sources/shiboken2/tests/samplebinding/privatedtor_test.py104
-rw-r--r--sources/shiboken2/tests/samplebinding/protected_test.py363
-rw-r--r--sources/shiboken2/tests/samplebinding/pstrlist_test.py56
-rw-r--r--sources/shiboken2/tests/samplebinding/pystr_test.py54
-rw-r--r--sources/shiboken2/tests/samplebinding/python_thread_test.py122
-rw-r--r--sources/shiboken2/tests/samplebinding/receive_null_cstring_test.py60
-rw-r--r--sources/shiboken2/tests/samplebinding/reference_test.py127
-rw-r--r--sources/shiboken2/tests/samplebinding/referencetopointer_test.py103
-rw-r--r--sources/shiboken2/tests/samplebinding/renaming_test.py63
-rw-r--r--sources/shiboken2/tests/samplebinding/return_null_test.py64
-rw-r--r--sources/shiboken2/tests/samplebinding/richcompare_test.py52
-rw-r--r--sources/shiboken2/tests/samplebinding/sample-binding.txt.in15
-rw-r--r--sources/shiboken2/tests/samplebinding/sample_test.py84
-rw-r--r--sources/shiboken2/tests/samplebinding/simplefile_glue.cpp34
-rw-r--r--sources/shiboken2/tests/samplebinding/simplefile_test.py86
-rw-r--r--sources/shiboken2/tests/samplebinding/size_test.py125
-rw-r--r--sources/shiboken2/tests/samplebinding/static_nonstatic_methods_test.py114
-rw-r--r--sources/shiboken2/tests/samplebinding/str_test.py121
-rw-r--r--sources/shiboken2/tests/samplebinding/strlist_test.py118
-rw-r--r--sources/shiboken2/tests/samplebinding/templateinheritingclass_test.py87
-rw-r--r--sources/shiboken2/tests/samplebinding/time_test.py145
-rw-r--r--sources/shiboken2/tests/samplebinding/transform_test.py62
-rw-r--r--sources/shiboken2/tests/samplebinding/typeconverters_test.py196
-rw-r--r--sources/shiboken2/tests/samplebinding/typedealloc_test.py81
-rw-r--r--sources/shiboken2/tests/samplebinding/typedtordoublefree_test.py60
-rw-r--r--sources/shiboken2/tests/samplebinding/typesystem_sample.xml2465
-rw-r--r--sources/shiboken2/tests/samplebinding/unsafe_parent_test.py59
-rw-r--r--sources/shiboken2/tests/samplebinding/useraddedctor_test.py51
-rw-r--r--sources/shiboken2/tests/samplebinding/virtualdtor_test.py81
-rw-r--r--sources/shiboken2/tests/samplebinding/virtualmethods_test.py143
-rw-r--r--sources/shiboken2/tests/samplebinding/visibilitychange_test.py53
-rw-r--r--sources/shiboken2/tests/samplebinding/voidholder_test.py75
-rw-r--r--sources/shiboken2/tests/samplebinding/weakref_test.py71
-rw-r--r--sources/shiboken2/tests/samplebinding/writableclassdict_test.py59
-rw-r--r--sources/shiboken2/tests/shiboken_paths.py106
-rw-r--r--sources/shiboken2/tests/shiboken_test_helper.py40
-rw-r--r--sources/shiboken2/tests/shibokenmodule/module_test.py123
-rw-r--r--sources/shiboken2/tests/smartbinding/CMakeLists.txt40
-rw-r--r--sources/shiboken2/tests/smartbinding/global.h29
-rw-r--r--sources/shiboken2/tests/smartbinding/smart-binding.txt.in15
-rw-r--r--sources/shiboken2/tests/smartbinding/smart_pointer_test.py219
-rw-r--r--sources/shiboken2/tests/smartbinding/typesystem_smart.xml56
-rw-r--r--sources/shiboken2/tests/sphinxtabletest.cpp332
-rw-r--r--sources/shiboken2/tests/sphinxtabletest.h54
-rw-r--r--sources/shiboken2/tests/test_generator/CMakeLists.txt68
-rw-r--r--sources/shiboken2/tests/test_generator/dummygenerator.cpp70
-rw-r--r--sources/shiboken2/tests/test_generator/dummygenerator.h49
-rw-r--r--sources/shiboken2/tests/test_generator/dummygentest-project.txt.in20
-rw-r--r--sources/shiboken2/tests/test_generator/dummygentest.cpp138
-rw-r--r--sources/shiboken2/tests/test_generator/dummygentest.h56
-rw-r--r--sources/shiboken2/tests/test_generator/dummygentestconfig.h.in15
-rw-r--r--sources/shiboken2/tests/test_generator/main.cpp39
-rw-r--r--sources/shiboken2/tests/test_generator/run_test.cmake11
-rw-r--r--sources/shiboken2/tests/test_generator/test_global.h1
-rw-r--r--sources/shiboken2/tests/test_generator/test_typesystem.xml3
653 files changed, 0 insertions, 114168 deletions
diff --git a/sources/shiboken2/.gitattributes b/sources/shiboken2/.gitattributes
deleted file mode 100644
index adbe833c1..000000000
--- a/sources/shiboken2/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-.gitignore export-ignore
-.gitattributes export-ignore
diff --git a/sources/shiboken2/.gitignore b/sources/shiboken2/.gitignore
deleted file mode 100644
index adb1e4594..000000000
--- a/sources/shiboken2/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-build
-.kdev4
-*.log
-*.pyc
-*.o
-*.so
-.*.swp
-*.kdev4
diff --git a/sources/shiboken2/AUTHORS b/sources/shiboken2/AUTHORS
deleted file mode 100644
index 4bb16b2dd..000000000
--- a/sources/shiboken2/AUTHORS
+++ /dev/null
@@ -1,12 +0,0 @@
-John Cummings <jcummings2@users.sf.net>
-John Ehresman <jpe@wingware.com>
-Roman Lacko <backup.rlacko@gmail.com>
-Matthew Woehlke <matthew.woehlke@kitware.com>
-Anderson Lizardo <anderson.lizardo@openbossa.org>
-Bruno Araujo <bruno.araujo@openbossa.org>
-Hugo Parente Lima <hugo.lima@openbossa.org>
-Lauro Moura <lauro.neto@openbossa.org>
-Luciano Wolf <luciano.wolf@openbossa.org>
-Marcelo Lira <marcelo.lira@openbossa.org>
-Renato Araujo Oliveira Filho <renato.filho@openbossa.org>
-
diff --git a/sources/shiboken2/ApiExtractor/AUTHORS b/sources/shiboken2/ApiExtractor/AUTHORS
deleted file mode 100644
index 6e802fb53..000000000
--- a/sources/shiboken2/ApiExtractor/AUTHORS
+++ /dev/null
@@ -1,8 +0,0 @@
-Anderson Lizardo <anderson.lizardo@openbossa.org>
-Bruno Araujo <bruno.araujo@openbossa.org>
-Hugo Parente Lima <hugo.lima@openbossa.org>
-Lauro Moura <lauro.neto@openbossa.org>
-Luciano Wolf <luciano.wolf@openbossa.org>
-Marcelo Lira <marcelo.lira@openbossa.org>
-Renato Araujo Oliveira Filho <renato.filho@openbossa.org>
-
diff --git a/sources/shiboken2/ApiExtractor/CMakeLists.txt b/sources/shiboken2/ApiExtractor/CMakeLists.txt
deleted file mode 100644
index f8e504583..000000000
--- a/sources/shiboken2/ApiExtractor/CMakeLists.txt
+++ /dev/null
@@ -1,94 +0,0 @@
-project(apiextractor)
-
-cmake_minimum_required(VERSION 3.1)
-cmake_policy(VERSION 3.1)
-
-set(CMAKE_AUTOMOC ON)
-
-set(apiextractor_SRC
-apiextractor.cpp
-abstractmetabuilder.cpp
-abstractmetalang.cpp
-fileout.cpp
-graph.cpp
-messages.cpp
-reporthandler.cpp
-typeparser.cpp
-typesystem.cpp
-typesystemparser.cpp
-include.cpp
-typedatabase.cpp
-# Clang
-clangparser/compilersupport.cpp
-clangparser/clangparser.cpp
-clangparser/clangbuilder.cpp
-clangparser/clangdebugutils.cpp
-clangparser/clangutils.cpp
-# Old parser
-parser/codemodel.cpp
-parser/enumvalue.cpp
-xmlutils.cpp
-)
-
-find_package(Qt${QT_MAJOR_VERSION}XmlPatterns 5.12)
-find_package(Qt${QT_MAJOR_VERSION}Xml 5.12)
-find_package(LibXml2 2.6.32)
-find_package(LibXslt 1.1.19)
-
-set(HAS_LIBXSLT 0)
-if (LIBXSLT_FOUND AND LIBXML2_FOUND)
- set(HAS_LIBXSLT 1)
-endif()
-
-if(NOT Qt${QT_MAJOR_VERSION}XmlPatterns_FOUND AND NOT HAS_LIBXSLT)
- set(DISABLE_DOCSTRINGS TRUE)
- message(WARNING
- "Documentation will not be built due to missing dependency (no Qt5XmlPatterns found).")
-endif()
-
-# Export to parent scope so that generator/CMakeLists.txt gets it
-set(DISABLE_DOCSTRINGS ${DISABLE_DOCSTRINGS} PARENT_SCOPE)
-
-add_library(apiextractor STATIC ${apiextractor_SRC})
-target_include_directories(apiextractor PRIVATE ${CLANG_EXTRA_INCLUDES}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}/parser)
-target_link_libraries(apiextractor PUBLIC Qt${QT_MAJOR_VERSION}::Core)
-target_link_libraries(apiextractor PRIVATE ${CLANG_EXTRA_LIBRARIES})
-
-if (HAS_LIBXSLT)
- target_compile_definitions(apiextractor PUBLIC HAVE_LIBXSLT)
- target_sources(apiextractor PRIVATE xmlutils_libxslt.cpp)
- target_include_directories(apiextractor
- PRIVATE ${LIBXSLT_INCLUDE_DIR} ${LIBXML2_INCLUDE_DIR})
- target_link_libraries(apiextractor
- PRIVATE ${LIBXSLT_LIBRARIES} ${LIBXML2_LIBRARIES})
-endif()
-
-if (Qt${QT_MAJOR_VERSION}XmlPatterns_FOUND)
- target_compile_definitions(apiextractor PUBLIC HAVE_QTXMLPATTERNS)
- target_sources(apiextractor PRIVATE xmlutils_qt.cpp)
- target_link_libraries(apiextractor PUBLIC Qt${QT_MAJOR_VERSION}::Xml Qt${QT_MAJOR_VERSION}::XmlPatterns)
-endif()
-
-if (NOT DISABLE_DOCSTRINGS)
- target_sources(apiextractor PRIVATE docparser.cpp
- doxygenparser.cpp
- qtdocparser.cpp)
- if (NOT HAS_LIBXSLT)
- message(WARNING
- "libxslt and/or libxml not found, falling back to QtXmlPatterns (QTBUG-66925)")
- endif()
-endif()
-
-target_compile_definitions(apiextractor PRIVATE CMAKE_CXX_COMPILER="${CMAKE_CXX_COMPILER}")
-
-set(LIB_INSTALL_DIR "lib${LIB_SUFFIX}" CACHE PATH "The subdirectory relative to the install prefix where libraries will be installed (default is /lib${LIB_SUFFIX})" FORCE)
-
-if (BUILD_TESTS)
- find_package(Qt${QT_MAJOR_VERSION}Test 5.12 REQUIRED)
- set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/tests)
- enable_testing()
- add_subdirectory(tests)
-endif()
diff --git a/sources/shiboken2/ApiExtractor/COPYING b/sources/shiboken2/ApiExtractor/COPYING
deleted file mode 100644
index 4ccd71466..000000000
--- a/sources/shiboken2/ApiExtractor/COPYING
+++ /dev/null
@@ -1,342 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- <signature of Ty Coon>, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Library General
-Public License instead of this License.
-
--------------------------------------------------------------------------
diff --git a/sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp b/sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp
deleted file mode 100644
index b54dc70ef..000000000
--- a/sources/shiboken2/ApiExtractor/abstractmetabuilder.cpp
+++ /dev/null
@@ -1,3217 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "abstractmetabuilder_p.h"
-#include "messages.h"
-#include "reporthandler.h"
-#include "typedatabase.h"
-
-#include <clangparser/clangbuilder.h>
-#include <clangparser/clangutils.h>
-#include <clangparser/compilersupport.h>
-
-#include "parser/codemodel.h"
-
-#include <QDebug>
-#include <QDir>
-#include <QFile>
-#include <QFileInfo>
-#include <QRegularExpression>
-#include <QTextCodec>
-#include <QTextStream>
-#include <QVariant>
-#include <QTime>
-#include <QQueue>
-#include <QDir>
-
-#include <cstdio>
-#include <algorithm>
-#include "graph.h"
-#include <QTemporaryFile>
-
-static inline QString colonColon() { return QStringLiteral("::"); }
-
-static QString stripTemplateArgs(const QString &name)
-{
- int pos = name.indexOf(QLatin1Char('<'));
- return pos < 0 ? name : name.left(pos);
-}
-
-static QStringList parseTemplateType(const QString &name) {
- int n = name.indexOf(QLatin1Char('<'));
- if (n <= 0) {
- // If name starts with '<' or contains an unmatched (i.e. any) '>', we
- // reject it
- if (n == 0 || name.count(QLatin1Char('>')))
- return QStringList();
- // Doesn't look like a template instantiation; just return the name
- return QStringList() << name;
- }
-
- // Split the type name into the template name and template arguments; the
- // part before the opening '<' is the template name
- //
- // Example:
- // "foo<A, bar<B, C>, D>" -> ( "foo", "A", "bar<B, C>", "D" )
- QStringList result;
- result << name.left(n).trimmed();
-
- // Extract template arguments
- int i, depth = 1;
- const int l = name.length();
- for (i = n + 1; i < l; ++i) {
- // Consume balanced '<'/'>' within a single argument so that we won't
- // split on ',' as part of a single argument which is itself a
- // multi-argument template type
- if (name[i] == QLatin1Char('<')) {
- ++depth;
- } else if (name[i] == QLatin1Char('>')) {
- if (--depth == 0)
- break;
- } else if (name[i] == QLatin1Char(',') && depth == 1) {
- // Encountered ',' in template argument list that is not within
- // another template name; add current argument to result and start
- // working on the next argument
- result << name.mid(n + 1, i - n - 1).trimmed();
- n = i;
- }
- }
- if (i >= l) // arg list not closed
- return QStringList();
- if (i + 1 < l) // arg list closed before end of name
- return QStringList();
-
- // Add final argument and return result
- result << name.mid(n + 1, i - n - 1).trimmed();
- return result;
-}
-
-AbstractMetaBuilderPrivate::AbstractMetaBuilderPrivate() :
- m_logDirectory(QLatin1String(".") + QDir::separator())
-{
-}
-
-AbstractMetaBuilderPrivate::~AbstractMetaBuilderPrivate()
-{
- qDeleteAll(m_globalEnums);
- qDeleteAll(m_globalFunctions);
- qDeleteAll(m_templates);
- qDeleteAll(m_smartPointers);
- qDeleteAll(m_metaClasses);
-}
-
-AbstractMetaBuilder::AbstractMetaBuilder() : d(new AbstractMetaBuilderPrivate)
-{
- d->q = this;
-}
-
-AbstractMetaBuilder::~AbstractMetaBuilder()
-{
- delete d;
-}
-
-AbstractMetaClassList AbstractMetaBuilder::classes() const
-{
- return d->m_metaClasses;
-}
-
-AbstractMetaClassList AbstractMetaBuilder::templates() const
-{
- return d->m_templates;
-}
-
-AbstractMetaClassList AbstractMetaBuilder::smartPointers() const
-{
- return d->m_smartPointers;
-}
-
-AbstractMetaFunctionList AbstractMetaBuilder::globalFunctions() const
-{
- return d->m_globalFunctions;
-}
-
-AbstractMetaEnumList AbstractMetaBuilder::globalEnums() const
-{
- return d->m_globalEnums;
-}
-
-AbstractMetaEnum *AbstractMetaBuilder::findEnum(const TypeEntry *typeEntry) const
-{
- if (typeEntry && typeEntry->isFlags())
- typeEntry = static_cast<const FlagsTypeEntry *>(typeEntry)->originator();
- return d->m_enums.value(typeEntry);
-}
-
-void AbstractMetaBuilderPrivate::checkFunctionModifications()
-{
- const auto &entries = TypeDatabase::instance()->entries();
-
- for (auto it = entries.cbegin(), end = entries.cend(); it != end; ++it) {
- const TypeEntry *entry = it.value();
- if (!entry)
- continue;
- if (!entry->isComplex() || entry->codeGeneration() == TypeEntry::GenerateNothing)
- continue;
-
- auto centry = static_cast<const ComplexTypeEntry *>(entry);
-
- if (!(centry->codeGeneration() & TypeEntry::GenerateTargetLang))
- continue;
-
- FunctionModificationList modifications = centry->functionModifications();
-
- for (const FunctionModification &modification : qAsConst(modifications)) {
- QString signature = modification.signature();
-
- QString name = signature.trimmed();
- name.truncate(name.indexOf(QLatin1Char('(')));
-
- AbstractMetaClass *clazz = AbstractMetaClass::findClass(m_metaClasses, centry);
- if (!clazz)
- continue;
-
- const AbstractMetaFunctionList functions = clazz->functions();
- bool found = false;
- QStringList possibleSignatures;
- for (AbstractMetaFunction *function : functions) {
- if (function->implementingClass() == clazz
- && modification.matches(function->minimalSignature())) {
- found = true;
- break;
- }
-
- if (function->originalName() == name) {
- possibleSignatures.append(function->minimalSignature() + QLatin1String(" in ")
- + function->implementingClass()->name());
- }
- }
-
- if (!found) {
- qCWarning(lcShiboken).noquote().nospace()
- << msgNoFunctionForModification(signature,
- modification.originalSignature(),
- clazz->qualifiedCppName(),
- possibleSignatures, functions);
- }
- }
- }
-}
-
-AbstractMetaClass *AbstractMetaBuilderPrivate::argumentToClass(const ArgumentModelItem &argument,
- AbstractMetaClass *currentClass)
-{
- AbstractMetaClass *returned = nullptr;
- AbstractMetaType *type = translateType(argument->type(), currentClass);
- if (type && type->typeEntry() && type->typeEntry()->isComplex()) {
- const TypeEntry *entry = type->typeEntry();
- returned = AbstractMetaClass::findClass(m_metaClasses, entry);
- }
- delete type;
- return returned;
-}
-
-/**
- * Checks the argument of a hash function and flags the type if it is a complex type
- */
-void AbstractMetaBuilderPrivate::registerHashFunction(const FunctionModelItem &function_item,
- AbstractMetaClass *currentClass)
-{
- ArgumentList arguments = function_item->arguments();
- if (arguments.size() == 1) {
- if (AbstractMetaClass *cls = argumentToClass(arguments.at(0), currentClass))
- cls->setHasHashFunction(true);
- }
-}
-
-void AbstractMetaBuilderPrivate::registerToStringCapabilityIn(const NamespaceModelItem &nsItem)
-{
- const FunctionList &streamOps = nsItem->findFunctions(QLatin1String("operator<<"));
- for (const FunctionModelItem &item : streamOps)
- registerToStringCapability(item, nullptr);
- for (const NamespaceModelItem &ni : nsItem->namespaces())
- registerToStringCapabilityIn(ni);
-}
-
-/**
- * Check if a class has a debug stream operator that can be used as toString
- */
-
-void AbstractMetaBuilderPrivate::registerToStringCapability(const FunctionModelItem &function_item,
- AbstractMetaClass *currentClass)
-{
- ArgumentList arguments = function_item->arguments();
- if (arguments.size() == 2) {
- if (arguments.at(0)->type().toString() == QLatin1String("QDebug")) {
- const ArgumentModelItem &arg = arguments.at(1);
- if (AbstractMetaClass *cls = argumentToClass(arg, currentClass)) {
- if (arg->type().indirections() < 2)
- cls->setToStringCapability(true, int(arg->type().indirections()));
- }
- }
- }
-}
-
-void AbstractMetaBuilderPrivate::traverseOperatorFunction(const FunctionModelItem &item,
- AbstractMetaClass *currentClass)
-{
- if (item->accessPolicy() != CodeModel::Public)
- return;
-
- ArgumentList arguments = item->arguments();
- bool firstArgumentIsSelf = true;
- bool unaryOperator = false;
-
- auto baseoperandClass = argumentToClass(arguments.at(0), currentClass);
-
- if (arguments.size() == 1) {
- unaryOperator = true;
- } else if (!baseoperandClass
- || !(baseoperandClass->typeEntry()->codeGeneration() & TypeEntry::GenerateTargetLang)) {
- baseoperandClass = argumentToClass(arguments.at(1), currentClass);
- firstArgumentIsSelf = false;
- } else {
- AbstractMetaType *type = translateType(item->type(), currentClass);
- const TypeEntry *retType = type ? type->typeEntry() : nullptr;
- AbstractMetaClass *otherArgClass = argumentToClass(arguments.at(1), currentClass);
- if (otherArgClass && retType
- && (retType->isValue() || retType->isObject())
- && retType != baseoperandClass->typeEntry()
- && retType == otherArgClass->typeEntry()) {
- baseoperandClass = AbstractMetaClass::findClass(m_metaClasses, retType);
- firstArgumentIsSelf = false;
- }
- delete type;
- }
-
- if (baseoperandClass) {
- AbstractMetaFunction *metaFunction = traverseFunction(item, baseoperandClass);
- if (metaFunction) {
- // Strip away first argument, since that is the containing object
- AbstractMetaArgumentList arguments = metaFunction->arguments();
- if (firstArgumentIsSelf || unaryOperator) {
- AbstractMetaArgument *first = arguments.takeFirst();
- if (!unaryOperator && first->type()->indirections())
- metaFunction->setPointerOperator(true);
- delete first;
- metaFunction->setArguments(arguments);
- } else {
- // If the operator method is not unary and the first operator is
- // not of the same type of its owning class we suppose that it
- // must be an reverse operator (e.g. CLASS::operator(TYPE, CLASS)).
- // All operator overloads that operate over a class are already
- // being added as member functions of that class by the API Extractor.
- AbstractMetaArgument *last = arguments.takeLast();
- if (last->type()->indirections())
- metaFunction->setPointerOperator(true);
- delete last;
-
- metaFunction->setArguments(arguments);
- metaFunction->setReverseOperator(true);
- }
- metaFunction->setFunctionType(AbstractMetaFunction::NormalFunction);
- metaFunction->setVisibility(AbstractMetaFunction::Public);
- metaFunction->setOriginalAttributes(metaFunction->attributes());
- setupFunctionDefaults(metaFunction, baseoperandClass);
- baseoperandClass->addFunction(metaFunction);
- Q_ASSERT(!metaFunction->wasPrivate());
- } else {
- delete metaFunction;
- }
- }
-}
-
-void AbstractMetaBuilderPrivate::traverseStreamOperator(const FunctionModelItem &item,
- AbstractMetaClass *currentClass)
-{
- ArgumentList arguments = item->arguments();
- if (arguments.size() == 2 && item->accessPolicy() == CodeModel::Public) {
- AbstractMetaClass *streamClass = argumentToClass(arguments.at(0), currentClass);
- AbstractMetaClass *streamedClass = argumentToClass(arguments.at(1), currentClass);
-
- if (streamClass && streamedClass && (streamClass->isStream())) {
- AbstractMetaFunction *streamFunction = traverseFunction(item, streamedClass);
-
- if (streamFunction) {
- streamFunction->setFunctionType(AbstractMetaFunction::GlobalScopeFunction);
- // Strip first argument, since that is the containing object
- AbstractMetaArgumentList arguments = streamFunction->arguments();
- if (!streamClass->typeEntry()->generateCode())
- delete arguments.takeLast();
- else
- delete arguments.takeFirst();
-
- streamFunction->setArguments(arguments);
-
- *streamFunction += AbstractMetaAttributes::FinalInTargetLang;
- *streamFunction += AbstractMetaAttributes::Public;
- streamFunction->setOriginalAttributes(streamFunction->attributes());
-
-// streamFunction->setType(0);
-
- AbstractMetaClass *funcClass;
-
- if (!streamClass->typeEntry()->generateCode()) {
- AbstractMetaArgumentList reverseArgs = reverseList(streamFunction->arguments());
- streamFunction->setArguments(reverseArgs);
- streamFunction->setReverseOperator(true);
- funcClass = streamedClass;
- } else {
- funcClass = streamClass;
- }
-
- setupFunctionDefaults(streamFunction, funcClass);
- funcClass->addFunction(streamFunction);
- if (funcClass == streamClass)
- funcClass->typeEntry()->addExtraInclude(streamedClass->typeEntry()->include());
- else
- funcClass->typeEntry()->addExtraInclude(streamClass->typeEntry()->include());
-
- } else {
- delete streamFunction;
- }
-
- }
- }
-}
-
-void AbstractMetaBuilderPrivate::sortLists()
-{
- for (AbstractMetaClass *cls : qAsConst(m_metaClasses))
- cls->sortFunctions();
-}
-
-FileModelItem AbstractMetaBuilderPrivate::buildDom(QByteArrayList arguments,
- LanguageLevel level,
- unsigned clangFlags)
-{
- clang::Builder builder;
- builder.setSystemIncludes(TypeDatabase::instance()->systemIncludes());
- if (level == LanguageLevel::Default)
- level = clang::emulatedCompilerLanguageLevel();
- arguments.prepend(QByteArrayLiteral("-std=")
- + clang::languageLevelOption(level));
- FileModelItem result = clang::parse(arguments, clangFlags, builder)
- ? builder.dom() : FileModelItem();
- const clang::BaseVisitor::Diagnostics &diagnostics = builder.diagnostics();
- if (const int diagnosticsCount = diagnostics.size()) {
- QDebug d = qWarning();
- d.nospace();
- d.noquote();
- d << "Clang: " << diagnosticsCount << " diagnostic messages:\n";
- for (int i = 0; i < diagnosticsCount; ++i)
- d << " " << diagnostics.at(i) << '\n';
- }
- return result;
-}
-
-void AbstractMetaBuilderPrivate::traverseDom(const FileModelItem &dom)
-{
- const TypeDatabase *types = TypeDatabase::instance();
-
- pushScope(dom);
-
- // Start the generation...
- const ClassList &typeValues = dom->classes();
-
- ReportHandler::startProgress("Generating class model ("
- + QByteArray::number(typeValues.size()) + ")...");
- for (const ClassModelItem &item : typeValues) {
- if (AbstractMetaClass *cls = traverseClass(dom, item, nullptr))
- addAbstractMetaClass(cls, item.data());
- }
-
- // We need to know all global enums
- const EnumList &enums = dom->enums();
-
- ReportHandler::startProgress("Generating enum model ("
- + QByteArray::number(enums.size()) + ")...");
- for (const EnumModelItem &item : enums) {
- AbstractMetaEnum *metaEnum = traverseEnum(item, nullptr, QSet<QString>());
- if (metaEnum) {
- if (metaEnum->typeEntry()->generateCode())
- m_globalEnums << metaEnum;
- }
- }
-
- const auto &namespaceTypeValues = dom->namespaces();
- ReportHandler::startProgress("Generating namespace model ("
- + QByteArray::number(namespaceTypeValues.size()) + ")...");
- for (const NamespaceModelItem &item : namespaceTypeValues)
- traverseNamespace(dom, item);
-
- // Go through all typedefs to see if we have defined any
- // specific typedefs to be used as classes.
- const TypeDefList typeDefs = dom->typeDefs();
- ReportHandler::startProgress("Resolving typedefs ("
- + QByteArray::number(typeDefs.size()) + ")...");
- for (const TypeDefModelItem &typeDef : typeDefs) {
- if (AbstractMetaClass *cls = traverseTypeDef(dom, typeDef, nullptr))
- addAbstractMetaClass(cls, typeDef.data());
- }
-
- traverseTypesystemTypedefs();
-
- for (const ClassModelItem &item : typeValues)
- traverseClassMembers(item);
-
- for (const NamespaceModelItem &item : namespaceTypeValues)
- traverseNamespaceMembers(item);
-
- // Global functions
- const FunctionList &functions = dom->functions();
- for (const FunctionModelItem &func : functions) {
- if (func->accessPolicy() != CodeModel::Public || func->name().startsWith(QLatin1String("operator")))
- continue;
-
- FunctionTypeEntry *funcEntry = types->findFunctionType(func->name());
- if (!funcEntry || !funcEntry->generateCode())
- continue;
-
- AbstractMetaFunction *metaFunc = traverseFunction(func, nullptr);
- if (!metaFunc)
- continue;
-
- if (!funcEntry->hasSignature(metaFunc->minimalSignature())) {
- delete metaFunc;
- continue;
- }
-
- applyFunctionModifications(metaFunc);
-
- setInclude(funcEntry, func->fileName());
- if (metaFunc->typeEntry())
- delete metaFunc->typeEntry();
-
- metaFunc->setTypeEntry(funcEntry);
- m_globalFunctions << metaFunc;
- }
-
- ReportHandler::startProgress("Fixing class inheritance...");
- for (AbstractMetaClass *cls : qAsConst(m_metaClasses)) {
- if (!cls->isNamespace()) {
- setupInheritance(cls);
- if (!cls->hasVirtualDestructor() && cls->baseClass()
- && cls->baseClass()->hasVirtualDestructor())
- cls->setHasVirtualDestructor(true);
- }
- }
-
- ReportHandler::startProgress("Detecting inconsistencies in class model...");
- for (AbstractMetaClass *cls : qAsConst(m_metaClasses)) {
- cls->fixFunctions();
-
- if (!cls->typeEntry()) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("class '%1' does not have an entry in the type system")
- .arg(cls->name());
- } else {
- const bool couldAddDefaultCtors = cls->isConstructible()
- && !cls->isNamespace()
- && (cls->attributes() & AbstractMetaAttributes::HasRejectedConstructor) == 0;
- if (couldAddDefaultCtors) {
- if (!cls->hasConstructors())
- cls->addDefaultConstructor();
- if (cls->typeEntry()->isValue() && !cls->isAbstract() && !cls->hasCopyConstructor())
- cls->addDefaultCopyConstructor(ancestorHasPrivateCopyConstructor(cls));
- }
- }
- }
- const auto &allEntries = types->entries();
-
- ReportHandler::startProgress("Detecting inconsistencies in typesystem ("
- + QByteArray::number(allEntries.size()) + ")...");
- for (auto it = allEntries.cbegin(), end = allEntries.cend(); it != end; ++it) {
- TypeEntry *entry = it.value();
- if (!entry->isPrimitive()) {
- if ((entry->isValue() || entry->isObject())
- && !types->shouldDropTypeEntry(entry->qualifiedCppName())
- && !entry->isContainer()
- && !entry->isCustom()
- && (entry->generateCode() & TypeEntry::GenerateTargetLang)
- && !AbstractMetaClass::findClass(m_metaClasses, entry)) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("type '%1' is specified in typesystem, but not defined. This could potentially lead to compilation errors.")
- .arg(entry->qualifiedCppName());
- } else if (entry->generateCode() && entry->type() == TypeEntry::FunctionType) {
- auto fte = static_cast<const FunctionTypeEntry *>(entry);
- const QStringList &signatures = fte->signatures();
- for (const QString &signature : signatures) {
- bool ok = false;
- for (AbstractMetaFunction *func : qAsConst(m_globalFunctions)) {
- if (signature == func->minimalSignature()) {
- ok = true;
- break;
- }
- }
- if (!ok) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("Global function '%1' is specified in typesystem, but not defined. This could potentially lead to compilation errors.")
- .arg(signature);
- }
- }
- } else if (entry->isEnum() && (entry->generateCode() & TypeEntry::GenerateTargetLang)) {
- const QString name = static_cast<const EnumTypeEntry *>(entry)->targetLangQualifier();
- AbstractMetaClass *cls = AbstractMetaClass::findClass(m_metaClasses, name);
-
- const bool enumFound = cls
- ? cls->findEnum(entry->targetLangEntryName()) != nullptr
- : m_enums.contains(entry);
-
- if (!enumFound) {
- entry->setCodeGeneration(TypeEntry::GenerateNothing);
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("enum '%1' is specified in typesystem, but not declared")
- .arg(entry->qualifiedCppName());
- }
-
- }
- }
- }
-
- {
- const FunctionList &hashFunctions = dom->findFunctions(QLatin1String("qHash"));
- for (const FunctionModelItem &item : hashFunctions)
- registerHashFunction(item, nullptr);
- }
-
- registerToStringCapabilityIn(dom);
-
- {
- FunctionList binaryOperators = dom->findFunctions(QStringLiteral("operator=="));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator!=")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator<=")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator>=")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator<")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator+")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator/")));
- // Filter binary operators, skipping for example
- // class Iterator { ... Value *operator*() ... };
- const FunctionList potentiallyBinaryOperators =
- dom->findFunctions(QStringLiteral("operator*"))
- + dom->findFunctions(QStringLiteral("operator&"));
- for (const FunctionModelItem &item : potentiallyBinaryOperators) {
- if (!item->arguments().isEmpty())
- binaryOperators.append(item);
- }
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator-")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator&")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator|")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator^")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator~")));
- binaryOperators.append(dom->findFunctions(QStringLiteral("operator>")));
-
- for (const FunctionModelItem &item : qAsConst(binaryOperators))
- traverseOperatorFunction(item, nullptr);
- }
-
- {
- const FunctionList streamOperators = dom->findFunctions(QLatin1String("operator<<"))
- + dom->findFunctions(QLatin1String("operator>>"));
- for (const FunctionModelItem &item : streamOperators)
- traverseStreamOperator(item, nullptr);
- }
-
- ReportHandler::startProgress("Checking inconsistencies in function modifications...");
-
- checkFunctionModifications();
-
- ReportHandler::startProgress("Writing log files...");
-
- // sort all classes topologically
- m_metaClasses = classesTopologicalSorted(m_metaClasses);
-
- for (AbstractMetaClass *cls : qAsConst(m_metaClasses)) {
-// setupEquals(cls);
-// setupComparable(cls);
- setupClonable(cls);
- setupExternalConversion(cls);
-
- // sort all inner classes topologically
- if (!cls->typeEntry()->codeGeneration() || cls->innerClasses().size() < 2)
- continue;
-
- cls->setInnerClasses(classesTopologicalSorted(cls->innerClasses()));
- }
-
- dumpLog();
-
- sortLists();
-
- // Functions added to the module on the type system.
- const AddedFunctionList &globalUserFunctions = types->globalUserFunctions();
- for (const AddedFunctionPtr &addedFunc : globalUserFunctions) {
- AbstractMetaFunction *metaFunc = traverseFunction(addedFunc);
- if (Q_UNLIKELY(!metaFunc)) {
- qFatal("Unable to traverse added global function \"%s\".",
- qPrintable(addedFunc->name()));
- }
- metaFunc->setFunctionType(AbstractMetaFunction::NormalFunction);
- m_globalFunctions << metaFunc;
- }
-
- m_itemToClass.clear();
-
- ReportHandler::endProgress();
-}
-
-static bool metaEnumLessThan(const AbstractMetaEnum *e1, const AbstractMetaEnum *e2)
-{ return e1->fullName() < e2->fullName(); }
-
-static bool metaClassLessThan(const AbstractMetaClass *c1, const AbstractMetaClass *c2)
-{ return c1->fullName() < c2->fullName(); }
-
-static bool metaFunctionLessThan(const AbstractMetaFunction *f1, const AbstractMetaFunction *f2)
-{ return f1->name() < f2->name(); }
-
-bool AbstractMetaBuilder::build(const QByteArrayList &arguments,
- LanguageLevel level,
- unsigned clangFlags)
-{
- const FileModelItem dom = d->buildDom(arguments, level, clangFlags);
- if (dom.isNull())
- return false;
- if (ReportHandler::isDebug(ReportHandler::MediumDebug))
- qCDebug(lcShiboken) << dom.data();
- d->traverseDom(dom);
-
- // Ensure that indexes are in alphabetical order, roughly
- std::sort(d->m_globalEnums.begin(), d->m_globalEnums.end(), metaEnumLessThan);
- std::sort(d->m_metaClasses.begin(), d->m_metaClasses.end(), metaClassLessThan);
- std::sort(d->m_templates.begin(), d->m_templates.end(), metaClassLessThan);
- std::sort(d->m_smartPointers.begin(), d->m_smartPointers.end(), metaClassLessThan);
- std::sort(d->m_globalFunctions.begin(), d->m_globalFunctions.end(), metaFunctionLessThan);
-
- return true;
-}
-
-void AbstractMetaBuilder::setLogDirectory(const QString &logDir)
-{
- d->m_logDirectory = logDir;
- if (!d->m_logDirectory.endsWith(QDir::separator()))
- d->m_logDirectory.append(QDir::separator());
-}
-
-void AbstractMetaBuilderPrivate::addAbstractMetaClass(AbstractMetaClass *cls,
- const _CodeModelItem *item)
-{
- cls->setOriginalAttributes(cls->attributes());
- m_itemToClass.insert(item, cls);
- if (cls->typeEntry()->isContainer()) {
- m_templates << cls;
- } else if (cls->typeEntry()->isSmartPointer()) {
- m_smartPointers << cls;
- } else {
- m_metaClasses << cls;
- }
-}
-
-AbstractMetaClass *AbstractMetaBuilderPrivate::traverseNamespace(const FileModelItem &dom,
- const NamespaceModelItem &namespaceItem)
-{
- QString namespaceName = currentScope()->qualifiedName().join(colonColon());
- if (!namespaceName.isEmpty())
- namespaceName.append(colonColon());
- namespaceName.append(namespaceItem->name());
-
- if (TypeDatabase::instance()->isClassRejected(namespaceName)) {
- m_rejectedClasses.insert(namespaceName, AbstractMetaBuilder::GenerationDisabled);
- return nullptr;
- }
-
- auto type = TypeDatabase::instance()->findNamespaceType(namespaceName, namespaceItem->fileName());
- if (!type) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("namespace '%1' does not have a type entry").arg(namespaceName);
- return nullptr;
- }
-
- if (namespaceItem->type() == NamespaceType::Inline) {
- type->setInlineNamespace(true);
- TypeDatabase::instance()->addInlineNamespaceLookups(type);
- }
-
- // Continue populating namespace?
- AbstractMetaClass *metaClass = AbstractMetaClass::findClass(m_metaClasses, type);
- if (!metaClass) {
- metaClass = new AbstractMetaClass;
- metaClass->setTypeEntry(type);
- *metaClass += AbstractMetaAttributes::Public;
- addAbstractMetaClass(metaClass, namespaceItem.data());
- if (auto extendsType = type->extends()) {
- AbstractMetaClass *extended = AbstractMetaClass::findClass(m_metaClasses, extendsType);
- if (!extended) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgNamespaceToBeExtendedNotFound(extendsType->name(), extendsType->targetLangPackage())));
- return nullptr;
- }
- metaClass->setExtendedNamespace(extended);
- }
- } else {
- m_itemToClass.insert(namespaceItem.data(), metaClass);
- }
-
- traverseEnums(namespaceItem, metaClass, namespaceItem->enumsDeclarations());
-
- pushScope(namespaceItem);
-
- const ClassList &classes = namespaceItem->classes();
- for (const ClassModelItem &cls : classes) {
- AbstractMetaClass *mjc = traverseClass(dom, cls, metaClass);
- if (mjc) {
- metaClass->addInnerClass(mjc);
- mjc->setEnclosingClass(metaClass);
- addAbstractMetaClass(mjc, cls.data());
- }
- }
-
- // Go through all typedefs to see if we have defined any
- // specific typedefs to be used as classes.
- const TypeDefList typeDefs = namespaceItem->typeDefs();
- for (const TypeDefModelItem &typeDef : typeDefs) {
- AbstractMetaClass *cls = traverseTypeDef(dom, typeDef, metaClass);
- if (cls) {
- metaClass->addInnerClass(cls);
- cls->setEnclosingClass(metaClass);
- addAbstractMetaClass(cls, typeDef.data());
- }
- }
-
- // Traverse namespaces recursively
- for (const NamespaceModelItem &ni : namespaceItem->namespaces()) {
- AbstractMetaClass *mjc = traverseNamespace(dom, ni);
- if (mjc) {
- metaClass->addInnerClass(mjc);
- mjc->setEnclosingClass(metaClass);
- }
- }
-
- popScope();
-
- if (!type->include().isValid())
- setInclude(type, namespaceItem->fileName());
-
- return metaClass;
-}
-
-AbstractMetaEnum *AbstractMetaBuilderPrivate::traverseEnum(const EnumModelItem &enumItem,
- AbstractMetaClass *enclosing,
- const QSet<QString> &enumsDeclarations)
-{
- QString qualifiedName = enumItem->qualifiedName().join(colonColon());
-
- TypeEntry *typeEntry = nullptr;
- const TypeEntry *enclosingTypeEntry = enclosing ? enclosing->typeEntry() : nullptr;
- if (enumItem->accessPolicy() == CodeModel::Private) {
- typeEntry = new EnumTypeEntry(enumItem->qualifiedName().constLast(),
- QVersionNumber(0, 0), enclosingTypeEntry);
- TypeDatabase::instance()->addType(typeEntry);
- } else if (enumItem->enumKind() != AnonymousEnum) {
- typeEntry = TypeDatabase::instance()->findType(qualifiedName);
- } else {
- QStringList tmpQualifiedName = enumItem->qualifiedName();
- const EnumeratorList &enums = enumItem->enumerators();
- for (const EnumeratorModelItem &enumValue : enums) {
- tmpQualifiedName.removeLast();
- tmpQualifiedName << enumValue->name();
- qualifiedName = tmpQualifiedName.join(colonColon());
- typeEntry = TypeDatabase::instance()->findType(qualifiedName);
- if (typeEntry)
- break;
- }
- }
-
- QString enumName = enumItem->name();
-
- QString className;
- if (enclosingTypeEntry)
- className = enclosingTypeEntry->qualifiedCppName();
-
- QString rejectReason;
- if (TypeDatabase::instance()->isEnumRejected(className, enumName, &rejectReason)) {
- if (typeEntry)
- typeEntry->setCodeGeneration(TypeEntry::GenerateNothing);
- m_rejectedEnums.insert(qualifiedName + rejectReason, AbstractMetaBuilder::GenerationDisabled);
- return nullptr;
- }
-
- const bool rejectionWarning = !enclosing
- || (enclosing->typeEntry()->codeGeneration() & TypeEntry::GenerateTargetLang);
-
- if (!typeEntry) {
- if (rejectionWarning)
- qCWarning(lcShiboken, "%s", qPrintable(msgNoEnumTypeEntry(enumItem, className)));
- m_rejectedEnums.insert(qualifiedName, AbstractMetaBuilder::NotInTypeSystem);
- return nullptr;
- }
-
- if (!typeEntry->isEnum()) {
- if (rejectionWarning) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgNoEnumTypeConflict(enumItem, className, typeEntry)));
- }
- m_rejectedEnums.insert(qualifiedName, AbstractMetaBuilder::NotInTypeSystem);
- return nullptr;
- }
-
- auto *metaEnum = new AbstractMetaEnum;
- metaEnum->setEnumKind(enumItem->enumKind());
- metaEnum->setSigned(enumItem->isSigned());
- if (enumsDeclarations.contains(qualifiedName)
- || enumsDeclarations.contains(enumName)) {
- metaEnum->setHasQEnumsDeclaration(true);
- }
-
- auto *enumTypeEntry = static_cast<EnumTypeEntry *>(typeEntry);
- metaEnum->setTypeEntry(enumTypeEntry);
- switch (enumItem->accessPolicy()) {
- case CodeModel::Public:
- *metaEnum += AbstractMetaAttributes::Public;
- break;
- case CodeModel::Protected:
- *metaEnum += AbstractMetaAttributes::Protected;
- break;
- case CodeModel::Private:
- *metaEnum += AbstractMetaAttributes::Private;
- typeEntry->setCodeGeneration(TypeEntry::GenerateNothing);
- break;
- default:
- break;
- }
-
- const EnumeratorList &enums = enumItem->enumerators();
- for (const EnumeratorModelItem &value : enums) {
-
- auto *metaEnumValue = new AbstractMetaEnumValue;
- metaEnumValue->setName(value->name());
- // Deciding the enum value...
-
- metaEnumValue->setStringValue(value->stringValue());
- metaEnumValue->setValue(value->value());
- metaEnum->addEnumValue(metaEnumValue);
- }
-
- m_enums.insert(typeEntry, metaEnum);
-
- if (!metaEnum->typeEntry()->include().isValid())
- setInclude(metaEnum->typeEntry(), enumItem->fileName());
-
- metaEnum->setOriginalAttributes(metaEnum->attributes());
-
- // Register all enum values on Type database
- const bool isScopedEnum = enumItem->enumKind() == EnumClass;
- const EnumeratorList &enumerators = enumItem->enumerators();
- for (const EnumeratorModelItem &e : enumerators) {
- auto enumValue =
- new EnumValueTypeEntry(e->name(), e->stringValue(),
- enumTypeEntry, isScopedEnum,
- enumTypeEntry->version());
- TypeDatabase::instance()->addType(enumValue);
- if (e->value().isNullValue())
- enumTypeEntry->setNullValue(enumValue);
- }
-
- return metaEnum;
-}
-
-AbstractMetaClass *AbstractMetaBuilderPrivate::traverseTypeDef(const FileModelItem &,
- const TypeDefModelItem &typeDef,
- AbstractMetaClass *currentClass)
-{
- TypeDatabase *types = TypeDatabase::instance();
- QString className = stripTemplateArgs(typeDef->name());
-
- QString fullClassName = className;
- // we have an inner class
- if (currentClass) {
- fullClassName = stripTemplateArgs(currentClass->typeEntry()->qualifiedCppName())
- + colonColon() + fullClassName;
- }
-
- // If this is the alias for a primitive type
- // we store the aliased type on the alias
- // TypeEntry
- PrimitiveTypeEntry *ptype = types->findPrimitiveType(className);
- if (ptype) {
- QString typeDefName = typeDef->type().qualifiedName()[0];
- ptype->setReferencedTypeEntry(types->findPrimitiveType(typeDefName));
- return nullptr;
- }
-
-
- // If we haven't specified anything for the typedef, then we don't care
- ComplexTypeEntry *type = types->findComplexType(fullClassName);
- if (!type)
- return nullptr;
-
- auto *metaClass = new AbstractMetaClass;
- metaClass->setTypeDef(true);
- metaClass->setTypeEntry(type);
- metaClass->setBaseClassNames(QStringList(typeDef->type().toString()));
- *metaClass += AbstractMetaAttributes::Public;
-
- // Set the default include file name
- if (!type->include().isValid())
- setInclude(type, typeDef->fileName());
-
- fillAddedFunctions(metaClass);
-
- return metaClass;
-}
-
-// Add the typedef'ed classes
-void AbstractMetaBuilderPrivate::traverseTypesystemTypedefs()
-{
- const auto &entries = TypeDatabase::instance()->typedefEntries();
- for (auto it = entries.begin(), end = entries.end(); it != end; ++it) {
- TypedefEntry *te = it.value();
- auto *metaClass = new AbstractMetaClass;
- metaClass->setTypeDef(true);
- metaClass->setTypeEntry(te->target());
- metaClass->setBaseClassNames(QStringList(te->sourceType()));
- *metaClass += AbstractMetaAttributes::Public;
- fillAddedFunctions(metaClass);
- addAbstractMetaClass(metaClass, nullptr);
- }
-}
-
-AbstractMetaClass *AbstractMetaBuilderPrivate::traverseClass(const FileModelItem &dom,
- const ClassModelItem &classItem,
- AbstractMetaClass *currentClass)
-{
- QString className = stripTemplateArgs(classItem->name());
- QString fullClassName = className;
-
- // we have inner an class
- if (currentClass) {
- fullClassName = stripTemplateArgs(currentClass->typeEntry()->qualifiedCppName())
- + colonColon() + fullClassName;
- }
-
- ComplexTypeEntry *type = TypeDatabase::instance()->findComplexType(fullClassName);
- AbstractMetaBuilder::RejectReason reason = AbstractMetaBuilder::NoReason;
-
- if (TypeDatabase::instance()->isClassRejected(fullClassName)) {
- reason = AbstractMetaBuilder::GenerationDisabled;
- } else if (!type) {
- TypeEntry *te = TypeDatabase::instance()->findType(fullClassName);
- if (te && !te->isComplex())
- reason = AbstractMetaBuilder::RedefinedToNotClass;
- else
- reason = AbstractMetaBuilder::NotInTypeSystem;
- } else if (type->codeGeneration() == TypeEntry::GenerateNothing) {
- reason = AbstractMetaBuilder::GenerationDisabled;
- }
- if (reason != AbstractMetaBuilder::NoReason) {
- if (fullClassName.isEmpty()) {
- QTextStream(&fullClassName) << "anonymous struct at " << classItem->fileName()
- << ':' << classItem->startLine();
- }
- m_rejectedClasses.insert(fullClassName, reason);
- return nullptr;
- }
-
- auto *metaClass = new AbstractMetaClass;
- metaClass->setTypeEntry(type);
-
- if (classItem->isFinal())
- *metaClass += AbstractMetaAttributes::FinalCppClass;
-
- QStringList baseClassNames;
- const QVector<_ClassModelItem::BaseClass> &baseClasses = classItem->baseClasses();
- for (const _ClassModelItem::BaseClass &baseClass : baseClasses) {
- if (baseClass.accessPolicy == CodeModel::Public)
- baseClassNames.append(baseClass.name);
- }
-
- metaClass->setBaseClassNames(baseClassNames);
- *metaClass += AbstractMetaAttributes::Public;
- if (type->stream())
- metaClass->setStream(true);
-
- if (ReportHandler::isDebug(ReportHandler::MediumDebug)) {
- const QString message = type->isContainer()
- ? QStringLiteral("container: '%1'").arg(fullClassName)
- : QStringLiteral("class: '%1'").arg(metaClass->fullName());
- qCInfo(lcShiboken, "%s", qPrintable(message));
- }
-
- TemplateParameterList template_parameters = classItem->templateParameters();
- QVector<TypeEntry *> template_args;
- template_args.clear();
- auto argumentParent = metaClass->typeEntry()->typeSystemTypeEntry();
- for (int i = 0; i < template_parameters.size(); ++i) {
- const TemplateParameterModelItem &param = template_parameters.at(i);
- auto param_type = new TemplateArgumentEntry(param->name(), type->version(),
- argumentParent);
- param_type->setOrdinal(i);
- template_args.append(param_type);
- }
- metaClass->setTemplateArguments(template_args);
-
- parseQ_Property(metaClass, classItem->propertyDeclarations());
-
- traverseEnums(classItem, metaClass, classItem->enumsDeclarations());
-
- // Inner classes
- {
- const ClassList &innerClasses = classItem->classes();
- for (const ClassModelItem &ci : innerClasses) {
- AbstractMetaClass *cl = traverseClass(dom, ci, metaClass);
- if (cl) {
- cl->setEnclosingClass(metaClass);
- metaClass->addInnerClass(cl);
- addAbstractMetaClass(cl, ci.data());
- }
- }
-
- }
-
- // Go through all typedefs to see if we have defined any
- // specific typedefs to be used as classes.
- const TypeDefList typeDefs = classItem->typeDefs();
- for (const TypeDefModelItem &typeDef : typeDefs) {
- AbstractMetaClass *cls = traverseTypeDef(dom, typeDef, metaClass);
- if (cls) {
- cls->setEnclosingClass(metaClass);
- addAbstractMetaClass(cls, typeDef.data());
- }
- }
-
- // Set the default include file name
- if (!type->include().isValid())
- setInclude(type, classItem->fileName());
-
- return metaClass;
-}
-
-void AbstractMetaBuilderPrivate::traverseScopeMembers(const ScopeModelItem &item,
- AbstractMetaClass *metaClass)
-{
- // Classes/Namespace members
- traverseFields(item, metaClass);
- traverseFunctions(item, metaClass);
-
- // Inner classes
- const ClassList &innerClasses = item->classes();
- for (const ClassModelItem &ci : innerClasses)
- traverseClassMembers(ci);
-}
-
-void AbstractMetaBuilderPrivate::traverseClassMembers(const ClassModelItem &item)
-{
- AbstractMetaClass *metaClass = m_itemToClass.value(item.data());
- if (!metaClass)
- return;
-
- // Class members
- traverseScopeMembers(item, metaClass);
-}
-
-void AbstractMetaBuilderPrivate::traverseNamespaceMembers(const NamespaceModelItem &item)
-{
- AbstractMetaClass *metaClass = m_itemToClass.value(item.data());
- if (!metaClass)
- return;
-
- // Namespace members
- traverseScopeMembers(item, metaClass);
-
- // Inner namespaces
- for (const NamespaceModelItem &ni : item->namespaces())
- traverseNamespaceMembers(ni);
-
-}
-
-static inline QString fieldSignatureWithType(const VariableModelItem &field)
-{
- return field->name() + QStringLiteral(" -> ") + field->type().toString();
-}
-
-static inline QString qualifiedFieldSignatureWithType(const QString &className,
- const VariableModelItem &field)
-{
- return className + colonColon() + fieldSignatureWithType(field);
-}
-
-AbstractMetaField *AbstractMetaBuilderPrivate::traverseField(const VariableModelItem &field,
- AbstractMetaClass *cls)
-{
- QString fieldName = field->name();
- QString className = cls->typeEntry()->qualifiedCppName();
-
- // Ignore friend decl.
- if (field->isFriend())
- return nullptr;
-
- if (field->accessPolicy() == CodeModel::Private)
- return nullptr;
-
- QString rejectReason;
- if (TypeDatabase::instance()->isFieldRejected(className, fieldName, &rejectReason)) {
- m_rejectedFields.insert(qualifiedFieldSignatureWithType(className, field) + rejectReason,
- AbstractMetaBuilder::GenerationDisabled);
- return nullptr;
- }
-
-
- auto *metaField = new AbstractMetaField;
- metaField->setName(fieldName);
- metaField->setEnclosingClass(cls);
-
- TypeInfo fieldType = field->type();
- AbstractMetaType *metaType = translateType(fieldType, cls);
-
- if (!metaType) {
- const QString type = TypeInfo::resolveType(fieldType, currentScope()).qualifiedName().join(colonColon());
- if (cls->typeEntry()->codeGeneration() & TypeEntry::GenerateTargetLang) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("skipping field '%1::%2' with unmatched type '%3'")
- .arg(cls->name(), fieldName, type);
- }
- delete metaField;
- return nullptr;
- }
-
- metaField->setType(metaType);
-
- AbstractMetaAttributes::Attributes attr;
- if (field->isStatic())
- attr |= AbstractMetaAttributes::Static;
-
- CodeModel::AccessPolicy policy = field->accessPolicy();
- if (policy == CodeModel::Public)
- attr |= AbstractMetaAttributes::Public;
- else if (policy == CodeModel::Protected)
- attr |= AbstractMetaAttributes::Protected;
- else
- attr |= AbstractMetaAttributes::Private;
- metaField->setAttributes(attr);
-
- return metaField;
-}
-
-void AbstractMetaBuilderPrivate::traverseFields(const ScopeModelItem &scope_item,
- AbstractMetaClass *metaClass)
-{
- const VariableList &variables = scope_item->variables();
- for (const VariableModelItem &field : variables) {
- AbstractMetaField *metaField = traverseField(field, metaClass);
-
- if (metaField && !metaField->isModifiedRemoved()) {
- metaField->setOriginalAttributes(metaField->attributes());
- metaClass->addField(metaField);
- }
- }
-}
-
-void AbstractMetaBuilderPrivate::setupFunctionDefaults(AbstractMetaFunction *metaFunction,
- AbstractMetaClass *metaClass)
-{
- // Set the default value of the declaring class. This may be changed
- // in fixFunctions later on
- metaFunction->setDeclaringClass(metaClass);
-
- // Some of the queries below depend on the implementing class being set
- // to function properly. Such as function modifications
- metaFunction->setImplementingClass(metaClass);
-
- if (metaFunction->name() == QLatin1String("operator_equal"))
- metaClass->setHasEqualsOperator(true);
-}
-
-void AbstractMetaBuilderPrivate::fixReturnTypeOfConversionOperator(AbstractMetaFunction *metaFunction)
-{
- if (!metaFunction->isConversionOperator())
- return;
-
- TypeDatabase *types = TypeDatabase::instance();
- static const QRegularExpression operatorRegExp(QStringLiteral("^operator "));
- Q_ASSERT(operatorRegExp.isValid());
- QString castTo = metaFunction->name().remove(operatorRegExp).trimmed();
-
- if (castTo.endsWith(QLatin1Char('&')))
- castTo.chop(1);
- if (castTo.startsWith(QLatin1String("const ")))
- castTo.remove(0, 6);
-
- TypeEntry *retType = types->findType(castTo);
- if (!retType)
- return;
-
- auto *metaType = new AbstractMetaType;
- metaType->setTypeEntry(retType);
- metaFunction->replaceType(metaType);
-}
-
-AbstractMetaFunctionList AbstractMetaBuilderPrivate::classFunctionList(const ScopeModelItem &scopeItem,
- AbstractMetaClass::Attributes *constructorAttributes,
- AbstractMetaClass *currentClass)
-{
- *constructorAttributes = {};
- AbstractMetaFunctionList result;
- const FunctionList &scopeFunctionList = scopeItem->functions();
- result.reserve(scopeFunctionList.size());
- for (const FunctionModelItem &function : scopeFunctionList) {
- if (AbstractMetaFunction *metaFunction = traverseFunction(function, currentClass)) {
- result.append(metaFunction);
- } else if (function->functionType() == CodeModel::Constructor) {
- auto arguments = function->arguments();
- *constructorAttributes |= AbstractMetaAttributes::HasRejectedConstructor;
- if (arguments.isEmpty() || arguments.constFirst()->defaultValue())
- *constructorAttributes |= AbstractMetaAttributes::HasRejectedDefaultConstructor;
- }
- }
- return result;
-}
-
-void AbstractMetaBuilderPrivate::traverseFunctions(ScopeModelItem scopeItem,
- AbstractMetaClass *metaClass)
-{
- AbstractMetaAttributes::Attributes constructorAttributes;
- const AbstractMetaFunctionList functions =
- classFunctionList(scopeItem, &constructorAttributes, metaClass);
- metaClass->setAttributes(metaClass->attributes() | constructorAttributes);
-
- for (AbstractMetaFunction *metaFunction : functions){
- metaFunction->setOriginalAttributes(metaFunction->attributes());
- if (metaClass->isNamespace())
- *metaFunction += AbstractMetaAttributes::Static;
-
- QPropertySpec *read = nullptr;
- if (!metaFunction->isSignal() && (read = metaClass->propertySpecForRead(metaFunction->name()))) {
- // Property reader must be in the form "<type> name()"
- if (metaFunction->type() && (read->type() == metaFunction->type()->typeEntry())
- && metaFunction->arguments().isEmpty()) {
- *metaFunction += AbstractMetaAttributes::PropertyReader;
- metaFunction->setPropertySpec(read);
- }
- } else if (QPropertySpec *write = metaClass->propertySpecForWrite(metaFunction->name())) {
- // Property setter must be in the form "void name(<type>)"
- // make sure the function was created with all aguments, some argument can be missing during the pareser because of errors on typesystem
- if ((!metaFunction->type()) && (metaFunction->arguments().size() == 1) && (write->type() == metaFunction->arguments().at(0)->type()->typeEntry())) {
- *metaFunction += AbstractMetaAttributes::PropertyWriter;
- metaFunction->setPropertySpec(write);
- }
- } else if (QPropertySpec *reset = metaClass->propertySpecForReset(metaFunction->name())) {
- // Property resetter must be in the form "void name()"
- if ((!metaFunction->type()) && metaFunction->arguments().isEmpty()) {
- *metaFunction += AbstractMetaAttributes::PropertyResetter;
- metaFunction->setPropertySpec(reset);
- }
- }
-
- const bool isInvalidDestructor = metaFunction->isDestructor() && metaFunction->isPrivate();
- const bool isInvalidConstructor = metaFunction->functionType() == AbstractMetaFunction::ConstructorFunction
- && metaFunction->isPrivate();
- if (isInvalidConstructor)
- metaClass->setHasPrivateConstructor(true);
- if ((isInvalidDestructor || isInvalidConstructor)
- && !metaClass->hasNonPrivateConstructor()) {
- *metaClass += AbstractMetaAttributes::FinalInTargetLang;
- } else if (metaFunction->isConstructor() && !metaFunction->isPrivate()) {
- *metaClass -= AbstractMetaAttributes::FinalInTargetLang;
- metaClass->setHasNonPrivateConstructor(true);
- }
-
- if (!metaFunction->isDestructor()
- && !(metaFunction->isPrivate() && metaFunction->functionType() == AbstractMetaFunction::ConstructorFunction)) {
-
- setupFunctionDefaults(metaFunction, metaClass);
-
- if (metaFunction->isSignal() && metaClass->hasSignal(metaFunction)) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("signal '%1' in class '%2' is overloaded.")
- .arg(metaFunction->name(), metaClass->name());
- }
-
- if (metaFunction->isConversionOperator())
- fixReturnTypeOfConversionOperator(metaFunction);
-
- metaClass->addFunction(metaFunction);
- applyFunctionModifications(metaFunction);
- } else if (metaFunction->isDestructor()) {
- metaClass->setHasPrivateDestructor(metaFunction->isPrivate());
- metaClass->setHasProtectedDestructor(metaFunction->isProtected());
- metaClass->setHasVirtualDestructor(metaFunction->isVirtual());
- }
- if (!metaFunction->ownerClass()) {
- delete metaFunction;
- metaFunction = nullptr;
- }
- }
-
- fillAddedFunctions(metaClass);
-}
-
-void AbstractMetaBuilderPrivate::fillAddedFunctions(AbstractMetaClass *metaClass)
-{
- // Add the functions added by the typesystem
- const AddedFunctionList &addedFunctions = metaClass->typeEntry()->addedFunctions();
- for (const AddedFunctionPtr &addedFunc : addedFunctions) {
- if (!traverseFunction(addedFunc, metaClass)) {
- qFatal("Unable to traverse function \"%s\" added to \"%s\".",
- qPrintable(addedFunc->name()), qPrintable(metaClass->name()));
- }
- }
-}
-
-void AbstractMetaBuilderPrivate::applyFunctionModifications(AbstractMetaFunction *func)
-{
- const FunctionModificationList &mods = func->modifications(func->implementingClass());
- AbstractMetaFunction& funcRef = *func;
- for (const FunctionModification &mod : mods) {
- if (mod.isRenameModifier()) {
- func->setOriginalName(func->name());
- func->setName(mod.renamedTo());
- } else if (mod.isAccessModifier()) {
- funcRef -= AbstractMetaAttributes::Public;
- funcRef -= AbstractMetaAttributes::Protected;
- funcRef -= AbstractMetaAttributes::Private;
- funcRef -= AbstractMetaAttributes::Friendly;
-
- if (mod.isPublic())
- funcRef += AbstractMetaAttributes::Public;
- else if (mod.isProtected())
- funcRef += AbstractMetaAttributes::Protected;
- else if (mod.isPrivate())
- funcRef += AbstractMetaAttributes::Private;
- else if (mod.isFriendly())
- funcRef += AbstractMetaAttributes::Friendly;
- }
-
- if (mod.isFinal())
- funcRef += AbstractMetaAttributes::FinalInTargetLang;
- else if (mod.isNonFinal())
- funcRef -= AbstractMetaAttributes::FinalInTargetLang;
- }
-}
-
-bool AbstractMetaBuilderPrivate::setupInheritance(AbstractMetaClass *metaClass)
-{
- if (m_setupInheritanceDone.contains(metaClass))
- return true;
-
- m_setupInheritanceDone.insert(metaClass);
-
- QStringList baseClasses = metaClass->baseClassNames();
-
- // we only support our own containers and ONLY if there is only one baseclass
- if (baseClasses.size() == 1 && baseClasses.constFirst().contains(QLatin1Char('<'))) {
- TypeInfo info;
- ComplexTypeEntry* baseContainerType;
- AbstractMetaClass* templ = findTemplateClass(baseClasses.constFirst(), metaClass, &info, &baseContainerType);
- if (templ) {
- setupInheritance(templ);
- inheritTemplate(metaClass, templ, info);
- metaClass->typeEntry()->setBaseContainerType(templ->typeEntry());
- return true;
- }
-
- if (baseContainerType) {
- // Container types are not necessarily wrapped as 'real' classes,
- // but there may still be classes derived from them. In such case,
- // we still need to set the base container type in order to
- // generate correct code for type conversion checking.
- //
- // Additionally, we consider this case as successfully setting up
- // inheritance.
- metaClass->typeEntry()->setBaseContainerType(baseContainerType);
- return true;
- }
-
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("template baseclass '%1' of '%2' is not known")
- .arg(baseClasses.constFirst(), metaClass->name());
- return false;
- }
-
- TypeDatabase* types = TypeDatabase::instance();
-
- for (const auto &baseClassName : baseClasses) {
- if (!types->isClassRejected(baseClassName)) {
- if (!types->findType(baseClassName)) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("class '%1' inherits from unknown base class '%2'")
- .arg(metaClass->name(), baseClassName);
- return false;
- }
- auto baseClass = AbstractMetaClass::findClass(m_metaClasses, baseClassName);
- if (!baseClass) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("class not found for setup inheritance '%1'").arg(baseClassName);
- return false;
- }
- metaClass->addBaseClass(baseClass);
-
- setupInheritance(baseClass);
- }
- }
-
- return true;
-}
-
-void AbstractMetaBuilderPrivate::traverseEnums(const ScopeModelItem &scopeItem,
- AbstractMetaClass *metaClass,
- const QStringList &enumsDeclarations)
-{
- const EnumList &enums = scopeItem->enums();
-#if QT_VERSION >= 0x050E00
- const QSet<QString> enumsDeclarationSet(enumsDeclarations.cbegin(), enumsDeclarations.cend());
-#else
- const QSet<QString> enumsDeclarationSet = QSet<QString>::fromList(enumsDeclarations);
-#endif
- for (const EnumModelItem &enumItem : enums) {
- AbstractMetaEnum* metaEnum = traverseEnum(enumItem, metaClass, enumsDeclarationSet);
- if (metaEnum) {
- metaClass->addEnum(metaEnum);
- metaEnum->setEnclosingClass(metaClass);
- }
- }
-}
-
-static void applyDefaultExpressionModifications(const FunctionModificationList &functionMods,
- int i, AbstractMetaArgument *metaArg)
-{
- // use replace/remove-default-expression for set default value
- for (const auto &modification : functionMods) {
- for (const auto &argumentModification : modification.argument_mods) {
- if (argumentModification.index == i + 1) {
- if (argumentModification.removedDefaultExpression) {
- metaArg->setDefaultValueExpression(QString());
- break;
- }
- if (!argumentModification.replacedDefaultExpression.isEmpty()) {
- metaArg->setDefaultValueExpression(argumentModification.replacedDefaultExpression);
- break;
- }
- }
- }
- }
-}
-
-AbstractMetaFunction* AbstractMetaBuilderPrivate::traverseFunction(const AddedFunctionPtr &addedFunc)
-{
- return traverseFunction(addedFunc, nullptr);
-}
-
-AbstractMetaFunction* AbstractMetaBuilderPrivate::traverseFunction(const AddedFunctionPtr &addedFunc,
- AbstractMetaClass *metaClass)
-{
- QString errorMessage;
-
- AbstractMetaType *returnType = nullptr;
- if (addedFunc->returnType().name != QLatin1String("void")) {
- returnType = translateType(addedFunc->returnType(), &errorMessage);
- if (!returnType) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgAddedFunctionInvalidReturnType(addedFunc->name(),
- addedFunc->returnType().name,
- errorMessage)));
- return nullptr;
- }
- }
-
- auto metaFunction = new AbstractMetaFunction(addedFunc);
- metaFunction->setType(returnType);
-
- const auto &args = addedFunc->arguments();
- AbstractMetaArgumentList metaArguments;
-
- for (int i = 0; i < args.count(); ++i) {
- const AddedFunction::TypeInfo& typeInfo = args.at(i).typeInfo;
- auto *metaArg = new AbstractMetaArgument;
- AbstractMetaType *type = translateType(typeInfo, &errorMessage);
- if (Q_UNLIKELY(!type)) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgAddedFunctionInvalidArgType(addedFunc->name(),
- typeInfo.name, i + 1,
- errorMessage)));
- delete metaFunction;
- return nullptr;
- }
- type->decideUsagePattern();
- if (!args.at(i).name.isEmpty())
- metaArg->setName(args.at(i).name);
- metaArg->setType(type);
- metaArg->setArgumentIndex(i);
- metaArg->setDefaultValueExpression(typeInfo.defaultValue);
- metaArg->setOriginalDefaultValueExpression(typeInfo.defaultValue);
- metaArguments.append(metaArg);
- }
-
- metaFunction->setArguments(metaArguments);
- if (metaFunction->isOperatorOverload() && !metaFunction->isCallOperator()) {
- if (metaArguments.size() > 2) {
- qCWarning(lcShiboken) << "An operator overload need to have 0, 1 or 2 arguments if it's reverse.";
- } else if (metaArguments.size() == 2) {
- // Check if it's a reverse operator
- if (metaArguments[1]->type()->typeEntry() == metaClass->typeEntry()) {
- metaFunction->setReverseOperator(true);
- // we need to call these two function to cache the old signature (with two args)
- // we do this buggy behaviour to comply with the original apiextractor buggy behaviour.
- metaFunction->signature();
- metaFunction->minimalSignature();
- metaArguments.removeLast();
- metaFunction->setArguments(metaArguments);
- } else {
- qCWarning(lcShiboken) << "Operator overload can have two arguments only if it's a reverse operator!";
- }
- }
- }
-
-
- // Find the correct default values
- const FunctionModificationList functionMods = metaFunction->modifications(metaClass);
- for (int i = 0; i < metaArguments.size(); ++i) {
- AbstractMetaArgument* metaArg = metaArguments.at(i);
-
- // use replace-default-expression for set default value
- applyDefaultExpressionModifications(functionMods, i, metaArg);
- metaArg->setOriginalDefaultValueExpression(metaArg->defaultValueExpression()); // appear unmodified
- }
-
- metaFunction->setOriginalAttributes(metaFunction->attributes());
- if (!metaArguments.isEmpty())
- fixArgumentNames(metaFunction, metaFunction->modifications(metaClass));
-
- if (metaClass) {
- const AbstractMetaArgumentList fargs = metaFunction->arguments();
- if (metaClass->isNamespace())
- *metaFunction += AbstractMetaFunction::Static;
- if (metaFunction->name() == metaClass->name()) {
- metaFunction->setFunctionType(AbstractMetaFunction::ConstructorFunction);
- if (fargs.size() == 1) {
- const TypeEntry *te = fargs.constFirst()->type()->typeEntry();
- if (te->isCustom())
- metaFunction->setExplicit(true);
- if (te->name() == metaFunction->name())
- metaFunction->setFunctionType(AbstractMetaFunction::CopyConstructorFunction);
- }
- } else {
- auto type = AbstractMetaFunction::NormalFunction;
- if (metaFunction->name() == QLatin1String("__getattro__"))
- type = AbstractMetaFunction::GetAttroFunction;
- else if (metaFunction->name() == QLatin1String("__setattro__"))
- type = AbstractMetaFunction::SetAttroFunction;
- metaFunction->setFunctionType(type);
- }
-
- metaFunction->setDeclaringClass(metaClass);
- metaFunction->setImplementingClass(metaClass);
- metaClass->addFunction(metaFunction);
- metaClass->setHasNonPrivateConstructor(true);
- }
-
- return metaFunction;
-}
-
-void AbstractMetaBuilderPrivate::fixArgumentNames(AbstractMetaFunction *func, const FunctionModificationList &mods)
-{
- for (const FunctionModification &mod : mods) {
- for (const ArgumentModification &argMod : mod.argument_mods) {
- if (!argMod.renamed_to.isEmpty()) {
- AbstractMetaArgument* arg = func->arguments().at(argMod.index - 1);
- arg->setOriginalName(arg->name());
- arg->setName(argMod.renamed_to, false);
- }
- }
- }
-
- AbstractMetaArgumentList arguments = func->arguments();
- for (int i = 0, size = arguments.size(); i < size; ++i) {
- if (arguments.at(i)->name().isEmpty())
- arguments[i]->setName(QLatin1String("arg__") + QString::number(i + 1), false);
- }
-}
-
-static QString functionSignature(const FunctionModelItem &functionItem)
-{
- QStringList args;
- const ArgumentList &arguments = functionItem->arguments();
- for (const ArgumentModelItem &arg : arguments)
- args << arg->type().toString();
- return functionItem->name() + QLatin1Char('(') + args.join(QLatin1Char(',')) + QLatin1Char(')');
-}
-
-static inline QString qualifiedFunctionSignatureWithType(const FunctionModelItem &functionItem,
- const QString &className = QString())
-{
- QString result = functionItem->type().toString() + QLatin1Char(' ');
- if (!className.isEmpty())
- result += className + colonColon();
- result += functionSignature(functionItem);
- return result;
-}
-static inline AbstractMetaFunction::FunctionType functionTypeFromCodeModel(CodeModel::FunctionType ft)
-{
- AbstractMetaFunction::FunctionType result = AbstractMetaFunction::NormalFunction;
- switch (ft) {
- case CodeModel::Constructor:
- result = AbstractMetaFunction::ConstructorFunction;
- break;
- case CodeModel::CopyConstructor:
- result = AbstractMetaFunction::CopyConstructorFunction;
- break;
- case CodeModel::MoveConstructor:
- result = AbstractMetaFunction::MoveConstructorFunction;
- break;
- case CodeModel::Destructor:
- result = AbstractMetaFunction::DestructorFunction;
- break;
- case CodeModel::Normal:
- break;
- case CodeModel::Signal:
- result = AbstractMetaFunction::SignalFunction;
- break;
- case CodeModel::Slot:
- result = AbstractMetaFunction::SlotFunction;
- break;
- }
- return result;
-}
-
-// Apply the <array> modifications of the arguments
-static bool applyArrayArgumentModifications(const FunctionModificationList &functionMods,
- AbstractMetaFunction *func,
- QString *errorMessage)
-{
- for (const FunctionModification &mod : functionMods) {
- for (const ArgumentModification &argMod : mod.argument_mods) {
- if (argMod.array) {
- const int i = argMod.index - 1;
- if (i < 0 || i >= func->arguments().size()) {
- *errorMessage = msgCannotSetArrayUsage(func->minimalSignature(), i,
- QLatin1String("Index out of range."));
- return false;
- }
- if (!func->arguments().at(i)->type()->applyArrayModification(errorMessage)) {
- *errorMessage = msgCannotSetArrayUsage(func->minimalSignature(), i, *errorMessage);
- return false;
- }
- }
- }
- }
- return true;
-}
-
-AbstractMetaFunction *AbstractMetaBuilderPrivate::traverseFunction(const FunctionModelItem &functionItem,
- AbstractMetaClass *currentClass)
-{
- if (functionItem->isDeleted() || !functionItem->templateParameters().isEmpty())
- return nullptr;
- QString functionName = functionItem->name();
- QString className;
- if (currentClass) {
- // Clang: Skip qt_metacast(), qt_metacall(), expanded from Q_OBJECT
- // and overridden metaObject(), QGADGET helpers
- if (functionName == QLatin1String("qt_check_for_QGADGET_macro")
- || functionName.startsWith(QLatin1String("qt_meta"))) {
- return nullptr;
- }
- className = currentClass->typeEntry()->qualifiedCppName();
- if (functionName == QLatin1String("metaObject") && className != QLatin1String("QObject"))
- return nullptr;
- }
-
- // Store original signature with unresolved typedefs for message/log purposes
- const QString originalQualifiedSignatureWithReturn =
- qualifiedFunctionSignatureWithType(functionItem, className);
-
- QString rejectReason;
- if (TypeDatabase::instance()->isFunctionRejected(className, functionName, &rejectReason)) {
- m_rejectedFunctions.insert(originalQualifiedSignatureWithReturn + rejectReason, AbstractMetaBuilder::GenerationDisabled);
- return nullptr;
- }
- const QString &signature = functionSignature(functionItem);
- const bool rejected =
- TypeDatabase::instance()->isFunctionRejected(className, signature, &rejectReason);
-
- if (rejected) {
- if (ReportHandler::isDebug(ReportHandler::MediumDebug)) {
- qCInfo(lcShiboken, "%s::%s was rejected by the type database (%s).",
- qPrintable(className), qPrintable(signature), qPrintable(rejectReason));
- }
- return nullptr;
- }
-
- if (functionItem->isFriend())
- return nullptr;
-
- const bool deprecated = functionItem->isDeprecated();
- if (deprecated && m_skipDeprecated) {
- m_rejectedFunctions.insert(originalQualifiedSignatureWithReturn + QLatin1String(" is deprecated."),
- AbstractMetaBuilder::GenerationDisabled);
- return nullptr;
- }
-
- auto *metaFunction = new AbstractMetaFunction;
- if (deprecated)
- *metaFunction += AbstractMetaAttributes::Deprecated;
-
- // Additional check for assignment/move assignment down below
- metaFunction->setFunctionType(functionTypeFromCodeModel(functionItem->functionType()));
- metaFunction->setConstant(functionItem->isConstant());
- metaFunction->setExceptionSpecification(functionItem->exceptionSpecification());
-
- metaFunction->setName(functionName);
- metaFunction->setOriginalName(functionItem->name());
-
- if (functionItem->isAbstract())
- *metaFunction += AbstractMetaAttributes::Abstract;
-
- if (functionItem->isVirtual()) {
- *metaFunction += AbstractMetaAttributes::VirtualCppMethod;
- if (functionItem->isOverride())
- *metaFunction += AbstractMetaAttributes::OverriddenCppMethod;
- if (functionItem->isFinal())
- *metaFunction += AbstractMetaAttributes::FinalCppMethod;
- } else {
- *metaFunction += AbstractMetaAttributes::FinalInTargetLang;
- }
-
- if (functionItem->isInvokable())
- *metaFunction += AbstractMetaAttributes::Invokable;
-
- if (functionItem->isStatic()) {
- *metaFunction += AbstractMetaAttributes::Static;
- *metaFunction += AbstractMetaAttributes::FinalInTargetLang;
- }
-
- // Access rights
- if (functionItem->accessPolicy() == CodeModel::Public)
- *metaFunction += AbstractMetaAttributes::Public;
- else if (functionItem->accessPolicy() == CodeModel::Private)
- *metaFunction += AbstractMetaAttributes::Private;
- else
- *metaFunction += AbstractMetaAttributes::Protected;
-
- QString errorMessage;
- switch (metaFunction->functionType()) {
- case AbstractMetaFunction::DestructorFunction:
- break;
- case AbstractMetaFunction::ConstructorFunction:
- metaFunction->setExplicit(functionItem->isExplicit());
- metaFunction->setName(currentClass->name());
- break;
- default: {
- TypeInfo returnType = functionItem->type();
-
- if (TypeDatabase::instance()->isReturnTypeRejected(className, returnType.toString(), &rejectReason)) {
- m_rejectedFunctions.insert(originalQualifiedSignatureWithReturn + rejectReason, AbstractMetaBuilder::GenerationDisabled);
- delete metaFunction;
- return nullptr;
- }
-
- AbstractMetaType *type = nullptr;
- if (!returnType.isVoid()) {
- type = translateType(returnType, currentClass, {}, &errorMessage);
- if (!type) {
- const QString reason = msgUnmatchedReturnType(functionItem, errorMessage);
- qCWarning(lcShiboken, "%s",
- qPrintable(msgSkippingFunction(functionItem, originalQualifiedSignatureWithReturn, reason)));
- m_rejectedFunctions.insert(originalQualifiedSignatureWithReturn, AbstractMetaBuilder::UnmatchedReturnType);
- delete metaFunction;
- return nullptr;
- }
- }
-
- metaFunction->setType(type);
- }
- break;
- }
-
- ArgumentList arguments = functionItem->arguments();
-
- if (arguments.size() == 1) {
- ArgumentModelItem arg = arguments.at(0);
- TypeInfo type = arg->type();
- if (type.qualifiedName().constFirst() == QLatin1String("void") && type.indirections() == 0)
- arguments.pop_front();
- }
-
- AbstractMetaArgumentList metaArguments;
-
- for (int i = 0; i < arguments.size(); ++i) {
- const ArgumentModelItem &arg = arguments.at(i);
-
- if (TypeDatabase::instance()->isArgumentTypeRejected(className, arg->type().toString(), &rejectReason)) {
- m_rejectedFunctions.insert(originalQualifiedSignatureWithReturn + rejectReason, AbstractMetaBuilder::GenerationDisabled);
- delete metaFunction;
- return nullptr;
- }
-
- AbstractMetaType *metaType = translateType(arg->type(), currentClass, {}, &errorMessage);
- if (!metaType) {
- // If an invalid argument has a default value, simply remove it
- if (arg->defaultValue()) {
- if (!currentClass
- || (currentClass->typeEntry()->codeGeneration()
- & TypeEntry::GenerateTargetLang)) {
- qCWarning(lcShiboken).noquote().nospace()
- << "Stripping argument #" << (i + 1) << " of "
- << originalQualifiedSignatureWithReturn
- << " due to unmatched type \"" << arg->type().toString()
- << "\" with default expression \""
- << arg->defaultValueExpression() << "\".";
- }
- break;
- }
- Q_ASSERT(metaType == nullptr);
- const QString reason = msgUnmatchedParameterType(arg, i, errorMessage);
- qCWarning(lcShiboken, "%s",
- qPrintable(msgSkippingFunction(functionItem, originalQualifiedSignatureWithReturn, reason)));
- const QString rejectedFunctionSignature = originalQualifiedSignatureWithReturn
- + QLatin1String(": ") + reason;
- m_rejectedFunctions.insert(rejectedFunctionSignature, AbstractMetaBuilder::UnmatchedArgumentType);
- delete metaFunction;
- return nullptr;
- }
-
- auto *metaArgument = new AbstractMetaArgument;
-
- metaArgument->setType(metaType);
- metaArgument->setName(arg->name());
- metaArgument->setArgumentIndex(i);
- metaArguments << metaArgument;
- }
-
- metaFunction->setArguments(metaArguments);
-
- const FunctionModificationList functionMods = metaFunction->modifications(currentClass);
-
- for (const FunctionModification &mod : functionMods) {
- if (mod.exceptionHandling() != TypeSystem::ExceptionHandling::Unspecified)
- metaFunction->setExceptionHandlingModification(mod.exceptionHandling());
- else if (mod.allowThread() != TypeSystem::AllowThread::Unspecified)
- metaFunction->setAllowThreadModification(mod.allowThread());
- }
-
- // Find the correct default values
- for (int i = 0, size = metaArguments.size(); i < size; ++i) {
- const ArgumentModelItem &arg = arguments.at(i);
- AbstractMetaArgument* metaArg = metaArguments.at(i);
-
- const QString originalDefaultExpression =
- fixDefaultValue(arg, metaArg->type(), metaFunction, currentClass, i);
-
- metaArg->setOriginalDefaultValueExpression(originalDefaultExpression);
- metaArg->setDefaultValueExpression(originalDefaultExpression);
-
- applyDefaultExpressionModifications(functionMods, i, metaArg);
-
- //Check for missing argument name
- if (!metaArg->defaultValueExpression().isEmpty()
- && !metaArg->hasName()
- && !metaFunction->isOperatorOverload()
- && !metaFunction->isSignal()
- && metaFunction->argumentName(i + 1, false, currentClass).isEmpty()) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("Argument %1 on function '%2::%3' has default expression but does not have name.")
- .arg(i+1).arg(className, metaFunction->minimalSignature());
- }
-
- }
-
- if (!metaArguments.isEmpty()) {
- fixArgumentNames(metaFunction, functionMods);
- QString errorMessage;
- if (!applyArrayArgumentModifications(functionMods, metaFunction, &errorMessage)) {
- qCWarning(lcShiboken, "While traversing %s: %s",
- qPrintable(className), qPrintable(errorMessage));
- }
- }
-
- // Determine class special functions
- if (currentClass && metaFunction->arguments().size() == 1) {
- const AbstractMetaType *argType = metaFunction->arguments().constFirst()->type();
- if (argType->typeEntry() == currentClass->typeEntry() && argType->indirections() == 0) {
- if (metaFunction->name() == QLatin1String("operator=")) {
- switch (argType->referenceType()) {
- case NoReference:
- metaFunction->setFunctionType(AbstractMetaFunction::AssignmentOperatorFunction);
- break;
- case LValueReference:
- if (argType->isConstant())
- metaFunction->setFunctionType(AbstractMetaFunction::AssignmentOperatorFunction);
- break;
- case RValueReference:
- metaFunction->setFunctionType(AbstractMetaFunction::MoveAssignmentOperatorFunction);
- break;
- }
- }
- }
- }
- return metaFunction;
-}
-
-AbstractMetaType *AbstractMetaBuilderPrivate::translateType(const AddedFunction::TypeInfo &typeInfo,
- QString *errorMessage)
-{
- Q_ASSERT(!typeInfo.name.isEmpty());
- TypeDatabase* typeDb = TypeDatabase::instance();
- TypeEntry* type;
-
- QString typeName = typeInfo.name;
-
- if (typeName == QLatin1String("void"))
- return nullptr;
-
- type = typeDb->findType(typeName);
- if (!type)
- type = typeDb->findFlagsType(typeName);
-
- // test if the type is a template, like a container
- bool isTemplate = false;
- QStringList templateArgs;
- if (!type && typeInfo.name.contains(QLatin1Char('<'))) {
- const QStringList& parsedType = parseTemplateType(typeInfo.name);
- if (parsedType.isEmpty()) {
- *errorMessage = QStringLiteral("Template type parsing failed for '%1'").arg(typeInfo.name);
- return nullptr;
- }
- templateArgs = parsedType.mid(1);
- isTemplate = (type = typeDb->findContainerType(parsedType[0]));
- }
-
- if (!type) {
- QStringList candidates;
- const auto &entries = typeDb->entries();
- for (auto it = entries.cbegin(), end = entries.cend(); it != end; ++it) {
- // Let's try to find the type in different scopes.
- if (it.key().endsWith(colonColon() + typeName))
- candidates.append(it.key());
- }
- QTextStream str(errorMessage);
- str << "Type '" << typeName << "' wasn't found in the type database.\n";
-
- if (candidates.isEmpty()) {
- str << "Declare it in the type system using the proper <*-type> tag.";
- } else {
- str << "Remember to inform the full qualified name for the type you want to use.\nCandidates are:\n";
- candidates.sort();
- for (const QString& candidate : qAsConst(candidates))
- str << " " << candidate << '\n';
- }
- return nullptr;
- }
-
- // These are only implicit and should not appear in code...
- auto *metaType = new AbstractMetaType;
- metaType->setTypeEntry(type);
- metaType->setIndirections(typeInfo.indirections);
- if (typeInfo.isReference)
- metaType->setReferenceType(LValueReference);
- metaType->setConstant(typeInfo.isConstant);
- if (isTemplate) {
- for (const QString& templateArg : qAsConst(templateArgs)) {
- AbstractMetaType *metaArgType = nullptr;
- if (templateArg != QLatin1String("void")) {
- metaArgType = translateType(AddedFunction::TypeInfo::fromSignature(templateArg), errorMessage);
- if (!metaArgType)
- return nullptr;
- }
- metaType->addInstantiation(metaArgType);
- }
- metaType->setTypeUsagePattern(AbstractMetaType::ContainerPattern);
- }
-
- return metaType;
-}
-
-static const TypeEntry* findTypeEntryUsingContext(const AbstractMetaClass* metaClass, const QString& qualifiedName)
-{
- const TypeEntry* type = nullptr;
- QStringList context = metaClass->qualifiedCppName().split(colonColon());
- while (!type && !context.isEmpty()) {
- type = TypeDatabase::instance()->findType(context.join(colonColon()) + colonColon() + qualifiedName);
- context.removeLast();
- }
- return type;
-}
-
-// Helper for translateTypeStatic()
-TypeEntries AbstractMetaBuilderPrivate::findTypeEntries(const QString &qualifiedName,
- const QString &name,
- AbstractMetaClass *currentClass,
- AbstractMetaBuilderPrivate *d)
-{
- // 5.1 - Try first using the current scope
- if (currentClass) {
- if (auto type = findTypeEntryUsingContext(currentClass, qualifiedName))
- return {type};
-
- // 5.1.1 - Try using the class parents' scopes
- if (d && !currentClass->baseClassNames().isEmpty()) {
- const AbstractMetaClassList &baseClasses = d->getBaseClasses(currentClass);
- for (const AbstractMetaClass *cls : baseClasses) {
- if (auto type = findTypeEntryUsingContext(cls, qualifiedName))
- return {type};
- }
- }
- }
-
- // 5.2 - Try without scope
- auto types = TypeDatabase::instance()->findCppTypes(qualifiedName);
- if (!types.isEmpty())
- return types;
-
- // 6. No? Try looking it up as a flags type
- if (auto type = TypeDatabase::instance()->findFlagsType(qualifiedName))
- return {type};
-
- // 7. No? Try looking it up as a container type
- if (auto type = TypeDatabase::instance()->findContainerType(name))
- return {type};
-
- // 8. No? Check if the current class is a template and this type is one
- // of the parameters.
- if (currentClass) {
- const QVector<TypeEntry *> &template_args = currentClass->templateArguments();
- for (TypeEntry *te : template_args) {
- if (te->name() == qualifiedName)
- return {te};
- }
- }
- return {};
-}
-
-AbstractMetaType *AbstractMetaBuilderPrivate::translateType(const TypeInfo &_typei,
- AbstractMetaClass *currentClass,
- TranslateTypeFlags flags,
- QString *errorMessage)
-{
- return translateTypeStatic(_typei, currentClass, this, flags, errorMessage);
-}
-
-static bool isNumber(const QString &s)
-{
- return std::all_of(s.cbegin(), s.cend(),
- [](QChar c) { return c.isDigit(); });
-}
-
-AbstractMetaType *AbstractMetaBuilderPrivate::translateTypeStatic(const TypeInfo &_typei,
- AbstractMetaClass *currentClass,
- AbstractMetaBuilderPrivate *d,
- TranslateTypeFlags flags,
- QString *errorMessageIn)
-{
- // 1. Test the type info without resolving typedefs in case this is present in the
- // type system
- const bool resolveType = !flags.testFlag(AbstractMetaBuilder::DontResolveType);
- if (resolveType) {
- AbstractMetaType *resolved =
- translateTypeStatic(_typei, currentClass, d,
- flags | AbstractMetaBuilder::DontResolveType,
- errorMessageIn);
- if (resolved)
- return resolved;
- }
-
- TypeInfo typeInfo = _typei;
- if (resolveType) {
- // Go through all parts of the current scope (including global namespace)
- // to resolve typedefs. The parser does not properly resolve typedefs in
- // the global scope when they are referenced from inside a namespace.
- // This is a work around to fix this bug since fixing it in resolveType
- // seemed non-trivial
- int i = d ? d->m_scopes.size() - 1 : -1;
- while (i >= 0) {
- typeInfo = TypeInfo::resolveType(_typei, d->m_scopes.at(i--));
- if (typeInfo.qualifiedName().join(colonColon()) != _typei.qualifiedName().join(colonColon()))
- break;
- }
-
- }
-
- if (typeInfo.isFunctionPointer()) {
- if (errorMessageIn)
- *errorMessageIn = msgUnableToTranslateType(_typei, QLatin1String("Unsupported function pointer."));
- return nullptr;
- }
-
- QString errorMessage;
-
- // 2. Handle arrays.
- // 2.1 Handle char arrays with unspecified size (aka "const char[]") as "const char*" with
- // NativePointerPattern usage.
- bool oneDimensionalArrayOfUnspecifiedSize =
- typeInfo.arrayElements().size() == 1
- && typeInfo.arrayElements().at(0).isEmpty();
-
- bool isConstCharStarCase =
- oneDimensionalArrayOfUnspecifiedSize
- && typeInfo.qualifiedName().size() == 1
- && typeInfo.qualifiedName().at(0) == QStringLiteral("char")
- && typeInfo.indirections() == 0
- && typeInfo.isConstant()
- && typeInfo.referenceType() == NoReference
- && typeInfo.arguments().isEmpty();
-
- if (isConstCharStarCase)
- typeInfo.setIndirections(typeInfo.indirections() + typeInfo.arrayElements().size());
-
- // 2.2 Handle regular arrays.
- if (!typeInfo.arrayElements().isEmpty() && !isConstCharStarCase) {
- TypeInfo newInfo;
- //newInfo.setArguments(typeInfo.arguments());
- newInfo.setIndirectionsV(typeInfo.indirectionsV());
- newInfo.setConstant(typeInfo.isConstant());
- newInfo.setVolatile(typeInfo.isVolatile());
- newInfo.setFunctionPointer(typeInfo.isFunctionPointer());
- newInfo.setQualifiedName(typeInfo.qualifiedName());
- newInfo.setReferenceType(typeInfo.referenceType());
- newInfo.setVolatile(typeInfo.isVolatile());
-
- AbstractMetaType *elementType = translateTypeStatic(newInfo, currentClass, d, flags, &errorMessage);
- if (!elementType) {
- if (errorMessageIn) {
- errorMessage.prepend(QLatin1String("Unable to translate array element: "));
- *errorMessageIn = msgUnableToTranslateType(_typei, errorMessage);
- }
- return nullptr;
- }
-
- for (int i = typeInfo.arrayElements().size() - 1; i >= 0; --i) {
- auto *arrayType = new AbstractMetaType;
- arrayType->setArrayElementType(elementType);
- const QString &arrayElement = typeInfo.arrayElements().at(i);
- if (!arrayElement.isEmpty()) {
- bool _ok;
- const qint64 elems = d
- ? d->findOutValueFromString(arrayElement, _ok)
- : arrayElement.toLongLong(&_ok, 0);
- if (_ok)
- arrayType->setArrayElementCount(int(elems));
- }
- auto elementTypeEntry = elementType->typeEntry();
- arrayType->setTypeEntry(new ArrayTypeEntry(elementTypeEntry, elementTypeEntry->version(),
- elementTypeEntry->parent()));
- arrayType->decideUsagePattern();
-
- elementType = arrayType;
- }
-
- return elementType;
- }
-
- QStringList qualifierList = typeInfo.qualifiedName();
- if (qualifierList.isEmpty()) {
- errorMessage = msgUnableToTranslateType(_typei, QLatin1String("horribly broken type"));
- if (errorMessageIn)
- *errorMessageIn = errorMessage;
- else
- qCWarning(lcShiboken,"%s", qPrintable(errorMessage));
- return nullptr;
- }
-
- QString qualifiedName = qualifierList.join(colonColon());
- QString name = qualifierList.takeLast();
-
- // 4. Special case QFlags (include instantiation in name)
- if (qualifiedName == QLatin1String("QFlags")) {
- qualifiedName = typeInfo.toString();
- typeInfo.clearInstantiations();
- }
-
- const TypeEntries types = findTypeEntries(qualifiedName, name, currentClass, d);
- if (types.isEmpty()) {
- if (errorMessageIn) {
- *errorMessageIn =
- msgUnableToTranslateType(_typei, msgCannotFindTypeEntry(qualifiedName));
- }
- return nullptr;
- }
-
- const TypeEntry *type = types.constFirst();
- const TypeEntry::Type typeEntryType = type->type();
-
- QScopedPointer<AbstractMetaType> metaType(new AbstractMetaType);
- metaType->setIndirectionsV(typeInfo.indirectionsV());
- metaType->setReferenceType(typeInfo.referenceType());
- metaType->setConstant(typeInfo.isConstant());
- metaType->setVolatile(typeInfo.isVolatile());
- metaType->setOriginalTypeDescription(_typei.toString());
-
- const auto &templateArguments = typeInfo.instantiations();
- for (int t = 0, size = templateArguments.size(); t < size; ++t) {
- const TypeInfo &ti = templateArguments.at(t);
- AbstractMetaType *targType = translateTypeStatic(ti, currentClass, d, flags, &errorMessage);
- // For non-type template parameters, create a dummy type entry on the fly
- // as is done for classes.
- if (!targType) {
- const QString value = ti.qualifiedName().join(colonColon());
- if (isNumber(value)) {
- TypeDatabase::instance()->addConstantValueTypeEntry(value, type->typeSystemTypeEntry());
- targType = translateTypeStatic(ti, currentClass, d, flags, &errorMessage);
- }
- }
- if (!targType) {
- if (errorMessageIn)
- *errorMessageIn = msgCannotTranslateTemplateArgument(t, ti, errorMessage);
- return nullptr;
- }
-
- metaType->addInstantiation(targType, true);
- }
-
- if (types.size() > 1) {
- const bool sameType = std::all_of(types.cbegin() + 1, types.cend(),
- [typeEntryType](const TypeEntry *e) {
- return e->type() == typeEntryType; });
- if (!sameType) {
- if (errorMessageIn)
- *errorMessageIn = msgAmbiguousVaryingTypesFound(qualifiedName, types);
- return nullptr;
- }
- // Ambiguous primitive/smart pointer types are possible (when
- // including type systems).
- if (typeEntryType != TypeEntry::PrimitiveType
- && typeEntryType != TypeEntry::SmartPointerType) {
- if (errorMessageIn)
- *errorMessageIn = msgAmbiguousTypesFound(qualifiedName, types);
- return nullptr;
- }
- }
-
- if (typeEntryType == TypeEntry::SmartPointerType) {
- // Find a matching instantiation
- if (metaType->instantiations().size() != 1) {
- if (errorMessageIn)
- *errorMessageIn = msgInvalidSmartPointerType(_typei);
- return nullptr;
- }
- auto instantiationType = metaType->instantiations().constFirst()->typeEntry();
- if (instantiationType->type() == TypeEntry::TemplateArgumentType) {
- // Member functions of the template itself, SharedPtr(const SharedPtr &)
- type = instantiationType;
- } else {
- auto it = std::find_if(types.cbegin(), types.cend(),
- [instantiationType](const TypeEntry *e) {
- auto smartPtr = static_cast<const SmartPointerTypeEntry *>(e);
- return smartPtr->matchesInstantiation(instantiationType);
- });
- if (it == types.cend()) {
- if (errorMessageIn)
- *errorMessageIn = msgCannotFindSmartPointerInstantion(_typei);
- return nullptr;
- }
- type =*it;
- }
- }
-
- metaType->setTypeEntry(type);
-
- // The usage pattern *must* be decided *after* the possible template
- // instantiations have been determined, or else the absence of
- // such instantiations will break the caching scheme of
- // AbstractMetaType::cppSignature().
- metaType->decideUsagePattern();
-
- return metaType.take();
-}
-
-AbstractMetaType *AbstractMetaBuilder::translateType(const TypeInfo &_typei,
- AbstractMetaClass *currentClass,
- TranslateTypeFlags flags,
- QString *errorMessage)
-{
- return AbstractMetaBuilderPrivate::translateTypeStatic(_typei, currentClass,
- nullptr, flags,
- errorMessage);
-}
-
-AbstractMetaType *AbstractMetaBuilder::translateType(const QString &t,
- AbstractMetaClass *currentClass,
- TranslateTypeFlags flags,
- QString *errorMessageIn)
-{
- QString errorMessage;
- TypeInfo typeInfo = TypeParser::parse(t, &errorMessage);
- if (typeInfo.qualifiedName().isEmpty()) {
- errorMessage = msgUnableToTranslateType(t, errorMessage);
- if (errorMessageIn)
- *errorMessageIn = errorMessage;
- else
- qCWarning(lcShiboken, "%s", qPrintable(errorMessage));
- return nullptr;
- }
- return translateType(typeInfo, currentClass, flags, errorMessageIn);
-}
-
-qint64 AbstractMetaBuilderPrivate::findOutValueFromString(const QString &stringValue, bool &ok)
-{
- qint64 value = stringValue.toLongLong(&ok);
- if (ok)
- return value;
-
- if (stringValue == QLatin1String("true") || stringValue == QLatin1String("false")) {
- ok = true;
- return (stringValue == QLatin1String("true"));
- }
-
- // This is a very lame way to handle expression evaluation,
- // but it is not critical and will do for the time being.
- static const QRegularExpression variableNameRegExp(QStringLiteral("^[a-zA-Z_][a-zA-Z0-9_]*$"));
- Q_ASSERT(variableNameRegExp.isValid());
- if (!variableNameRegExp.match(stringValue).hasMatch()) {
- ok = true;
- return 0;
- }
-
- AbstractMetaEnumValue *enumValue = AbstractMetaClass::findEnumValue(m_metaClasses, stringValue);
- if (enumValue) {
- ok = true;
- return enumValue->value().value();
- }
-
- for (AbstractMetaEnum *metaEnum : qAsConst(m_globalEnums)) {
- if (const AbstractMetaEnumValue *ev = metaEnum->findEnumValue(stringValue)) {
- ok = true;
- return ev->value().value();
- }
- }
-
- ok = false;
- return 0;
-}
-
-QString AbstractMetaBuilderPrivate::fixDefaultValue(const ArgumentModelItem &item,
- AbstractMetaType *type,
- AbstractMetaFunction *fnc,
- AbstractMetaClass *implementingClass,
- int /* argumentIndex */)
-{
- QString expr = item->defaultValueExpression();
- if (expr.isEmpty())
- return expr;
-
- if (type) {
- if (type->isPrimitive()) {
- if (type->name() == QLatin1String("boolean")) {
- if (expr != QLatin1String("false") && expr != QLatin1String("true")) {
- bool ok = false;
- int number = expr.toInt(&ok);
- if (ok && number)
- expr = QLatin1String("true");
- else
- expr = QLatin1String("false");
- }
- } else {
- // This can be an enum or flag so I need to delay the
- // translation untill all namespaces are completly
- // processed. This is done in figureOutEnumValues()
- }
- } else if (type->isFlags() || type->isEnum()) {
- bool isNumber;
- expr.toInt(&isNumber);
- if (!isNumber && expr.indexOf(colonColon()) < 0) {
- // Add the enum/flag scope to default value, making it usable
- // from other contexts beside its owner class hierarchy
- static const QRegularExpression typeRegEx(QStringLiteral("[^<]*[<]([^:]*::).*"));
- Q_ASSERT(typeRegEx.isValid());
- const QRegularExpressionMatch match = typeRegEx.match(type->minimalSignature());
- if (match.hasMatch())
- expr.prepend(match.captured(1));
- }
- } else if (type->isContainer() && expr.contains(QLatin1Char('<'))) {
- static const QRegularExpression typeRegEx(QStringLiteral("[^<]*<(.*)>"));
- Q_ASSERT(typeRegEx.isValid());
- const QRegularExpressionMatch typeMatch = typeRegEx.match(type->minimalSignature());
- static const QRegularExpression defaultRegEx(QLatin1String("([^<]*<).*(>[^>]*)"));
- Q_ASSERT(defaultRegEx.isValid());
- const QRegularExpressionMatch defaultMatch = defaultRegEx.match(expr);
- if (typeMatch.hasMatch() && defaultMatch.hasMatch())
- expr = defaultMatch.captured(1) + typeMatch.captured(1) + defaultMatch.captured(2);
- } else {
- // Here the default value is supposed to be a constructor,
- // a class field, or a constructor receiving a class field
- static const QRegularExpression defaultRegEx(QStringLiteral("([^\\(]*\\(|)([^\\)]*)(\\)|)"));
- Q_ASSERT(defaultRegEx.isValid());
- const QRegularExpressionMatch defaultMatch = defaultRegEx.match(expr);
- QString defaultValueCtorName = defaultMatch.hasMatch() ? defaultMatch.captured(1) : QString();
- if (defaultValueCtorName.endsWith(QLatin1Char('(')))
- defaultValueCtorName.chop(1);
-
- // Fix the scope for constructor using the already
- // resolved argument type as a reference.
- // The following regular expression extracts any
- // use of namespaces/scopes from the type string.
- static const QRegularExpression typeRegEx(QLatin1String("^(?:const[\\s]+|)([\\w:]*::|)([A-Za-z_]\\w*)\\s*[&\\*]?$"));
- Q_ASSERT(typeRegEx.isValid());
- const QRegularExpressionMatch typeMatch = typeRegEx.match(type->minimalSignature());
-
- QString typeNamespace = typeMatch.hasMatch() ? typeMatch.captured(1) : QString();
- QString typeCtorName = typeMatch.hasMatch() ? typeMatch.captured(2) : QString();
- if (!typeNamespace.isEmpty() && defaultValueCtorName == typeCtorName)
- expr.prepend(typeNamespace);
-
- // Fix scope if the parameter is a field of the current class
- if (implementingClass) {
- const AbstractMetaFieldList &fields = implementingClass->fields();
- for (const AbstractMetaField *field : fields) {
- if (defaultMatch.hasMatch() && defaultMatch.captured(2) == field->name()) {
- expr = defaultMatch.captured(1) + implementingClass->name()
- + colonColon() + defaultMatch.captured(2) + defaultMatch.captured(3);
- break;
- }
- }
- }
- }
- } else {
- const QString className = implementingClass ? implementingClass->qualifiedCppName() : QString();
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("undefined type for default value '%3' of argument in function '%1', class '%2'")
- .arg(fnc->name(), className, item->defaultValueExpression());
-
- expr.clear();
- }
-
- return expr;
-}
-
-bool AbstractMetaBuilderPrivate::isEnum(const FileModelItem &dom, const QStringList& qualified_name)
-{
- CodeModelItem item = dom->model()->findItem(qualified_name, dom);
- return item && item->kind() == _EnumModelItem::__node_kind;
-}
-
-AbstractMetaClass* AbstractMetaBuilderPrivate::findTemplateClass(const QString &name,
- const AbstractMetaClass *context,
- TypeInfo *info,
- ComplexTypeEntry **baseContainerType) const
-{
- TypeDatabase* types = TypeDatabase::instance();
-
- QStringList scope = context->typeEntry()->qualifiedCppName().split(colonColon());
- QString errorMessage;
- scope.removeLast();
- for (int i = scope.size(); i >= 0; --i) {
- QString prefix = i > 0 ? QStringList(scope.mid(0, i)).join(colonColon()) + colonColon() : QString();
- QString completeName = prefix + name;
- const TypeInfo parsed = TypeParser::parse(completeName, &errorMessage);
- QString qualifiedName = parsed.qualifiedName().join(colonColon());
- if (qualifiedName.isEmpty()) {
- qWarning().noquote().nospace() << "Unable to parse type \"" << completeName
- << "\" while looking for template \"" << name << "\": " << errorMessage;
- continue;
- }
- if (info)
- *info = parsed;
-
- AbstractMetaClass *templ = nullptr;
- for (AbstractMetaClass *c : qAsConst(m_templates)) {
- if (c->typeEntry()->name() == qualifiedName) {
- templ = c;
- break;
- }
- }
-
- if (!templ)
- templ = AbstractMetaClass::findClass(m_metaClasses, qualifiedName);
-
- if (templ)
- return templ;
-
- if (baseContainerType)
- *baseContainerType = types->findContainerType(qualifiedName);
- }
-
- return nullptr;
-}
-
-AbstractMetaClassList AbstractMetaBuilderPrivate::getBaseClasses(const AbstractMetaClass *metaClass) const
-{
- AbstractMetaClassList baseClasses;
- const QStringList &baseClassNames = metaClass->baseClassNames();
- for (const QString& parent : baseClassNames) {
- AbstractMetaClass *cls = nullptr;
- if (parent.contains(QLatin1Char('<')))
- cls = findTemplateClass(parent, metaClass);
- else
- cls = AbstractMetaClass::findClass(m_metaClasses, parent);
-
- if (cls)
- baseClasses << cls;
- }
- return baseClasses;
-}
-
-bool AbstractMetaBuilderPrivate::ancestorHasPrivateCopyConstructor(const AbstractMetaClass *metaClass) const
-{
- if (metaClass->hasPrivateCopyConstructor())
- return true;
- const AbstractMetaClassList &baseClasses = getBaseClasses(metaClass);
- for (const AbstractMetaClass *cls : baseClasses) {
- if (ancestorHasPrivateCopyConstructor(cls))
- return true;
- }
- return false;
-}
-
-AbstractMetaType *
- AbstractMetaBuilderPrivate::inheritTemplateType(const AbstractMetaTypeList &templateTypes,
- const AbstractMetaType *metaType)
-{
- Q_ASSERT(metaType);
-
- QScopedPointer<AbstractMetaType> returned(metaType->copy());
-
- if (!metaType->typeEntry()->isTemplateArgument() && !metaType->hasInstantiations())
- return returned.take();
-
- returned->setOriginalTemplateType(metaType);
-
- if (returned->typeEntry()->isTemplateArgument()) {
- const auto *tae = static_cast<const TemplateArgumentEntry*>(returned->typeEntry());
-
- // If the template is intantiated with void we special case this as rejecting the functions that use this
- // parameter from the instantiation.
- const AbstractMetaType *templateType = templateTypes.value(tae->ordinal());
- if (!templateType || templateType->typeEntry()->isVoid())
- return nullptr;
-
- AbstractMetaType* t = returned->copy();
- t->setTypeEntry(templateType->typeEntry());
- t->setIndirections(templateType->indirections() + t->indirections() ? 1 : 0);
- t->decideUsagePattern();
-
- return inheritTemplateType(templateTypes, t);
- }
-
- if (returned->hasInstantiations()) {
- AbstractMetaTypeList instantiations = returned->instantiations();
- for (int i = 0; i < instantiations.count(); ++i) {
- instantiations[i] =
- inheritTemplateType(templateTypes, instantiations.at(i));
- if (!instantiations.at(i))
- return nullptr;
- }
- returned->setInstantiations(instantiations, true);
- }
-
- return returned.take();
-}
-
-bool AbstractMetaBuilderPrivate::inheritTemplate(AbstractMetaClass *subclass,
- const AbstractMetaClass *templateClass,
- const TypeInfo &info)
-{
- QVector<TypeInfo> targs = info.instantiations();
- QVector<AbstractMetaType *> templateTypes;
- QString errorMessage;
-
- if (subclass->isTypeDef()) {
- subclass->setHasCloneOperator(templateClass->hasCloneOperator());
- subclass->setHasEqualsOperator(templateClass->hasEqualsOperator());
- subclass->setHasHashFunction(templateClass->hasHashFunction());
- subclass->setHasNonPrivateConstructor(templateClass->hasNonPrivateConstructor());
- subclass->setHasPrivateDestructor(templateClass->hasPrivateDestructor());
- subclass->setHasProtectedDestructor(templateClass->hasProtectedDestructor());
- subclass->setHasVirtualDestructor(templateClass->hasVirtualDestructor());
- }
-
- for (const TypeInfo &i : qAsConst(targs)) {
- QString typeName = i.qualifiedName().join(colonColon());
- TypeDatabase *typeDb = TypeDatabase::instance();
- TypeEntry *t = nullptr;
- // Check for a non-type template integer parameter, that is, for a base
- // "template <int R, int C> Matrix<R, C>" and subclass
- // "typedef Matrix<2,3> Matrix2x3;". If so, create dummy entries of
- // EnumValueTypeEntry for the integer values encountered on the fly.
- if (isNumber(typeName)) {
- t = typeDb->findType(typeName);
- if (!t) {
- auto parent = subclass->typeEntry()->typeSystemTypeEntry();
- t = TypeDatabase::instance()->addConstantValueTypeEntry(typeName, parent);
- }
- } else {
- QStringList possibleNames;
- possibleNames << subclass->qualifiedCppName() + colonColon() + typeName;
- possibleNames << templateClass->qualifiedCppName() + colonColon() + typeName;
- if (subclass->enclosingClass())
- possibleNames << subclass->enclosingClass()->qualifiedCppName() + colonColon() + typeName;
- possibleNames << typeName;
-
- for (const QString &possibleName : qAsConst(possibleNames)) {
- t = typeDb->findType(possibleName);
- if (t)
- break;
- }
- }
-
- if (t) {
- auto *temporaryType = new AbstractMetaType;
- temporaryType->setTypeEntry(t);
- temporaryType->setConstant(i.isConstant());
- temporaryType->setReferenceType(i.referenceType());
- temporaryType->setIndirectionsV(i.indirectionsV());
- temporaryType->decideUsagePattern();
- templateTypes << temporaryType;
- } else {
- qCWarning(lcShiboken).noquote().nospace()
- << "Ignoring template parameter " << typeName << " from "
- << info.toString() << ". The corresponding type was not found in the typesystem.";
- }
- }
-
- const AbstractMetaFunctionList &subclassFuncs = subclass->functions();
- const AbstractMetaFunctionList &templateClassFunctions = templateClass->functions();
- for (const AbstractMetaFunction *function : templateClassFunctions) {
- // If the function is modified or the instantiation has an equally named
- // function we have shadowing, so we need to skip it.
- if (function->isModifiedRemoved(TypeSystem::All)
- || AbstractMetaFunction::find(subclassFuncs, function->name()) != nullptr) {
- continue;
- }
-
- QScopedPointer<AbstractMetaFunction> f(function->copy());
- f->setArguments(AbstractMetaArgumentList());
-
- if (function->type()) { // Non-void
- AbstractMetaType *returnType = inheritTemplateType(templateTypes, function->type());
- if (!returnType)
- continue;
- f->replaceType(returnType);
- }
-
- const AbstractMetaArgumentList &arguments = function->arguments();
- for (AbstractMetaArgument *argument : arguments) {
- AbstractMetaType *argType = inheritTemplateType(templateTypes, argument->type());
- if (!argType)
- break;
- AbstractMetaArgument *arg = argument->copy();
- arg->replaceType(argType);
- f->addArgument(arg);
- }
-
- if (f->arguments().size() < function->arguments().size())
- continue;
-
- // There is no base class in the target language to inherit from here, so
- // the template instantiation is the class that implements the function.
- f->setImplementingClass(subclass);
-
- // We also set it as the declaring class, since the superclass is
- // supposed to disappear. This allows us to make certain function modifications
- // on the inherited functions.
- f->setDeclaringClass(subclass);
-
- if (f->isConstructor()) {
- if (!subclass->isTypeDef())
- continue;
- f->setName(subclass->name());
- f->setOriginalName(subclass->name());
- }
-
- ComplexTypeEntry* te = subclass->typeEntry();
- FunctionModificationList mods = function->modifications(templateClass);
- for (int i = 0; i < mods.size(); ++i) {
- FunctionModification mod = mods.at(i);
- mod.setSignature(f->minimalSignature());
-
- // If we ever need it... Below is the code to do
- // substitution of the template instantation type inside
- // injected code..
-#if 0
- if (mod.modifiers & Modification::CodeInjection) {
- for (int j = 0; j < template_types.size(); ++j) {
- CodeSnip &snip = mod.snips.last();
- QString code = snip.code();
- code.replace(QString::fromLatin1("$$QT_TEMPLATE_%1$$").arg(j),
- template_types.at(j)->typeEntry()->qualifiedCppName());
- snip.codeList.clear();
- snip.addCode(code);
- }
- }
-#endif
- te->addFunctionModification(mod);
- }
-
-
- if (!applyArrayArgumentModifications(f->modifications(subclass), f.data(),
- &errorMessage)) {
- qCWarning(lcShiboken, "While specializing %s (%s): %s",
- qPrintable(subclass->name()), qPrintable(templateClass->name()),
- qPrintable(errorMessage));
- }
- subclass->addFunction(f.take());
- }
-
- const AbstractMetaFieldList &subClassFields = subclass->fields();
- const AbstractMetaFieldList &templateClassFields = templateClass->fields();
- for (const AbstractMetaField *field : templateClassFields) {
- // If the field is modified or the instantiation has a field named
- // the same as an existing field we have shadowing, so we need to skip it.
- if (field->isModifiedRemoved(TypeSystem::All)
- || field->attributes().testFlag(AbstractMetaAttributes::Static)
- || AbstractMetaField::find(subClassFields, field->name()) != nullptr) {
- continue;
- }
-
- QScopedPointer<AbstractMetaField> f(field->copy());
- f->setEnclosingClass(subclass);
- AbstractMetaType *fieldType = inheritTemplateType(templateTypes, field->type());
- if (!fieldType)
- continue;
- f->replaceType(fieldType);
- subclass->addField(f.take());
- }
-
- subclass->setTemplateBaseClass(templateClass);
- subclass->setTemplateBaseClassInstantiations(templateTypes);
- subclass->setBaseClass(templateClass->baseClass());
-
- return true;
-}
-
-void AbstractMetaBuilderPrivate::parseQ_Property(AbstractMetaClass *metaClass,
- const QStringList &declarations)
-{
- const QStringList scopes = currentScope()->qualifiedName();
-
- for (int i = 0; i < declarations.size(); ++i) {
- const auto propertyTokens = declarations.at(i).splitRef(QLatin1Char(' '));
-
- AbstractMetaType *type = nullptr;
- for (int j = scopes.size(); j >= 0; --j) {
- QStringList qualifiedName = scopes.mid(0, j);
- qualifiedName.append(propertyTokens.at(0).toString());
- TypeInfo info;
- info.setQualifiedName(qualifiedName);
-
- type = translateType(info, metaClass);
- if (type)
- break;
- }
-
- if (!type) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("Unable to decide type of property: '%1' in class '%2'")
- .arg(propertyTokens.at(0).toString(), metaClass->name());
- continue;
- }
-
- auto *spec = new QPropertySpec(type->typeEntry());
- spec->setName(propertyTokens.at(1).toString());
- spec->setIndex(i);
-
- for (int pos = 2; pos + 1 < propertyTokens.size(); pos += 2) {
- if (propertyTokens.at(pos) == QLatin1String("READ"))
- spec->setRead(propertyTokens.at(pos + 1).toString());
- else if (propertyTokens.at(pos) == QLatin1String("WRITE"))
- spec->setWrite(propertyTokens.at(pos + 1).toString());
- else if (propertyTokens.at(pos) == QLatin1String("DESIGNABLE"))
- spec->setDesignable(propertyTokens.at(pos + 1).toString());
- else if (propertyTokens.at(pos) == QLatin1String("RESET"))
- spec->setReset(propertyTokens.at(pos + 1).toString());
- }
-
- metaClass->addPropertySpec(spec);
- delete type;
- }
-}
-
-static AbstractMetaFunction* findCopyCtor(AbstractMetaClass* cls)
-{
-
- const auto &functions = cls->functions();
-
- for (AbstractMetaFunction *f : qAsConst(functions)) {
- const AbstractMetaFunction::FunctionType t = f->functionType();
- if (t == AbstractMetaFunction::CopyConstructorFunction || t == AbstractMetaFunction::AssignmentOperatorFunction)
- return f;
- }
- return nullptr;
-}
-
-void AbstractMetaBuilderPrivate::setupClonable(AbstractMetaClass *cls)
-{
- bool result = true;
-
- // find copy ctor for the current class
- AbstractMetaFunction* copyCtor = findCopyCtor(cls);
- if (copyCtor) { // if exists a copy ctor in this class
- result = copyCtor->isPublic();
- } else { // else... lets find one in the parent class
- QQueue<AbstractMetaClass*> baseClasses;
- if (cls->baseClass())
- baseClasses.enqueue(cls->baseClass());
-
- while (!baseClasses.isEmpty()) {
- AbstractMetaClass* currentClass = baseClasses.dequeue();
- if (currentClass->baseClass())
- baseClasses.enqueue(currentClass->baseClass());
-
- copyCtor = findCopyCtor(currentClass);
- if (copyCtor) {
- result = copyCtor->isPublic();
- break;
- }
- }
- }
- cls->setHasCloneOperator(result);
-}
-
-void AbstractMetaBuilderPrivate::setupExternalConversion(AbstractMetaClass *cls)
-{
- const AbstractMetaFunctionList &convOps = cls->operatorOverloads(AbstractMetaClass::ConversionOp);
- for (AbstractMetaFunction *func : convOps) {
- if (func->isModifiedRemoved())
- continue;
- AbstractMetaClass *metaClass = AbstractMetaClass::findClass(m_metaClasses, func->type()->typeEntry());
- if (!metaClass)
- continue;
- metaClass->addExternalConversionOperator(func);
- }
- const AbstractMetaClassList &innerClasses = cls->innerClasses();
- for (AbstractMetaClass *innerClass : innerClasses)
- setupExternalConversion(innerClass);
-}
-
-static void writeRejectLogFile(const QString &name,
- const QMap<QString, AbstractMetaBuilder::RejectReason> &rejects)
-{
- QFile f(name);
- if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("failed to write log file: '%1'")
- .arg(QDir::toNativeSeparators(f.fileName()));
- return;
- }
-
- QTextStream s(&f);
-
-
- for (int reason = 0; reason < AbstractMetaBuilder::NoReason; ++reason) {
- s << QString(72, QLatin1Char('*')) << Qt::endl;
- switch (reason) {
- case AbstractMetaBuilder::NotInTypeSystem:
- s << "Not in type system";
- break;
- case AbstractMetaBuilder::GenerationDisabled:
- s << "Generation disabled by type system";
- break;
- case AbstractMetaBuilder::RedefinedToNotClass:
- s << "Type redefined to not be a class";
- break;
-
- case AbstractMetaBuilder::UnmatchedReturnType:
- s << "Unmatched return type";
- break;
-
- case AbstractMetaBuilder::UnmatchedArgumentType:
- s << "Unmatched argument type";
- break;
-
- case AbstractMetaBuilder::ApiIncompatible:
- s << "Incompatible API";
- break;
-
- case AbstractMetaBuilder::Deprecated:
- s << "Deprecated";
- break;
-
- default:
- s << "unknown reason";
- break;
- }
-
- s << Qt::endl;
-
- for (QMap<QString, AbstractMetaBuilder::RejectReason>::const_iterator it = rejects.constBegin();
- it != rejects.constEnd(); ++it) {
- if (it.value() != reason)
- continue;
- s << " - " << it.key() << Qt::endl;
- }
-
- s << QString(72, QLatin1Char('*')) << Qt::endl << Qt::endl;
- }
-
-}
-
-void AbstractMetaBuilderPrivate::dumpLog() const
-{
- writeRejectLogFile(m_logDirectory + QLatin1String("mjb_rejected_classes.log"), m_rejectedClasses);
- writeRejectLogFile(m_logDirectory + QLatin1String("mjb_rejected_enums.log"), m_rejectedEnums);
- writeRejectLogFile(m_logDirectory + QLatin1String("mjb_rejected_functions.log"), m_rejectedFunctions);
- writeRejectLogFile(m_logDirectory + QLatin1String("mjb_rejected_fields.log"), m_rejectedFields);
-}
-
-using ClassIndexHash = QHash<AbstractMetaClass *, int>;
-
-static ClassIndexHash::ConstIterator findByTypeEntry(const ClassIndexHash &map,
- const TypeEntry *typeEntry)
-{
- auto it = map.cbegin();
- for (auto end = map.cend(); it != end; ++it) {
- if (it.key()->typeEntry() == typeEntry)
- break;
- }
- return it;
-}
-
-AbstractMetaClassList AbstractMetaBuilderPrivate::classesTopologicalSorted(const AbstractMetaClassList &classList,
- const Dependencies &additionalDependencies) const
-{
- ClassIndexHash map;
- QHash<int, AbstractMetaClass *> reverseMap;
-
- int i = 0;
- for (AbstractMetaClass *clazz : classList) {
- if (map.contains(clazz))
- continue;
- map.insert(clazz, i);
- reverseMap.insert(i, clazz);
- i++;
- }
-
- Graph graph(map.count());
-
- for (const auto &dep : additionalDependencies) {
- const int parentIndex = map.value(dep.parent, -1);
- const int childIndex = map.value(dep.child, -1);
- if (parentIndex >= 0 && childIndex >= 0) {
- graph.addEdge(parentIndex, childIndex);
- } else {
- qCWarning(lcShiboken).noquote().nospace()
- << "AbstractMetaBuilder::classesTopologicalSorted(): Invalid additional dependency: "
- << dep.child->name() << " -> " << dep.parent->name() << '.';
- }
- }
-
- for (AbstractMetaClass *clazz : classList) {
- const int classIndex = map.value(clazz);
- if (auto enclosing = clazz->enclosingClass()) {
- const auto enclosingIt = map.constFind(const_cast< AbstractMetaClass *>(enclosing));
- if (enclosingIt!= map.cend())
- graph.addEdge(enclosingIt.value(), classIndex);
- }
-
- const AbstractMetaClassList &bases = getBaseClasses(clazz);
- for (AbstractMetaClass *baseClass : bases) {
- const auto baseIt = map.constFind(baseClass);
- if (baseIt!= map.cend())
- graph.addEdge(baseIt.value(), classIndex);
- }
-
- const AbstractMetaFunctionList &functions = clazz->functions();
- for (AbstractMetaFunction *func : functions) {
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (AbstractMetaArgument *arg : arguments) {
- // Check methods with default args: If a class is instantiated by value,
- // ("QString s = QString()"), add a dependency.
- if (!arg->originalDefaultValueExpression().isEmpty()
- && arg->type()->isValue()) {
- auto typeEntry = arg->type()->typeEntry();
- if (typeEntry->isComplex() && typeEntry != clazz->typeEntry()) {
- auto ait = findByTypeEntry(map, typeEntry);
- if (ait != map.cend() && ait.key()->enclosingClass() != clazz)
- graph.addEdge(ait.value(), classIndex);
- }
- }
- }
- }
- }
-
- AbstractMetaClassList result;
- const auto unmappedResult = graph.topologicalSort();
- if (unmappedResult.isEmpty() && graph.nodeCount()) {
- QTemporaryFile tempFile(QDir::tempPath() + QLatin1String("/cyclic_depXXXXXX.dot"));
- tempFile.setAutoRemove(false);
- tempFile.open();
- QHash<int, QString> hash;
- for (auto it = map.cbegin(), end = map.cend(); it != end; ++it)
- hash.insert(it.value(), it.key()->qualifiedCppName());
- graph.dumpDot(hash, tempFile.fileName());
- qCWarning(lcShiboken).noquote().nospace()
- << "Cyclic dependency found! Graph can be found at "
- << QDir::toNativeSeparators(tempFile.fileName());
- } else {
- for (int i : qAsConst(unmappedResult)) {
- Q_ASSERT(reverseMap.contains(i));
- result << reverseMap[i];
- }
- }
-
- return result;
-}
-
-void AbstractMetaBuilderPrivate::pushScope(const NamespaceModelItem &item)
-{
- // For purposes of type lookup, join all namespaces of the same name
- // within the parent item.
- QVector<NamespaceModelItem> candidates;
- const QString name = item->name();
- if (!m_scopes.isEmpty()) {
- for (const auto &n : m_scopes.constLast()->namespaces()) {
- if (n->name() == name)
- candidates.append(n);
- }
- }
- if (candidates.size() > 1) {
- NamespaceModelItem joined(new _NamespaceModelItem(m_scopes.constLast()->model(),
- name, _CodeModelItem::Kind_Namespace));
- joined->setScope(item->scope());
- for (const auto &n : candidates)
- joined->appendNamespace(*n);
- m_scopes << joined;
- } else {
- m_scopes << item;
- }
-}
-
-AbstractMetaClassList AbstractMetaBuilder::classesTopologicalSorted(const AbstractMetaClassList &classList,
- const Dependencies &additionalDependencies) const
-{
- return d->classesTopologicalSorted(classList, additionalDependencies);
-}
-
-AbstractMetaArgumentList AbstractMetaBuilderPrivate::reverseList(const AbstractMetaArgumentList &list)
-{
- AbstractMetaArgumentList ret;
-
- int index = list.size();
- for (AbstractMetaArgument *arg : list) {
- arg->setArgumentIndex(index);
- ret.prepend(arg);
- index--;
- }
-
- return ret;
-}
-
-void AbstractMetaBuilder::setGlobalHeader(const QString& globalHeader)
-{
- d->m_globalHeader = QFileInfo(globalHeader);
-}
-
-void AbstractMetaBuilder::setHeaderPaths(const HeaderPaths &hp)
-{
- for (const auto & h: hp) {
- if (h.type != HeaderType::Framework && h.type != HeaderType::FrameworkSystem)
- d->m_headerPaths.append(QFile::decodeName(h.path));
- }
-}
-
-void AbstractMetaBuilder::setSkipDeprecated(bool value)
-{
- d->m_skipDeprecated = value;
-}
-
-// PYSIDE-975: When receiving an absolute path name from the code model, try
-// to resolve it against the include paths set on shiboken in order to recreate
-// relative paths like #include <foo/bar.h>.
-
-static inline bool isFileSystemSlash(QChar c)
-{
- return c == QLatin1Char('/') || c == QLatin1Char('\\');
-}
-
-static bool matchHeader(const QString &headerPath, const QString &fileName)
-{
-#if defined(Q_OS_WIN) || defined(Q_OS_DARWIN)
- static const Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive;
-#else
- static const Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive;
-#endif
- const int pathSize = headerPath.size();
- return fileName.size() > pathSize
- && isFileSystemSlash(fileName.at(pathSize))
- && fileName.startsWith(headerPath, caseSensitivity);
-}
-
-void AbstractMetaBuilderPrivate::setInclude(TypeEntry *te, const QString &fileName) const
-{
- auto it = m_resolveIncludeHash.find(fileName);
- if (it == m_resolveIncludeHash.end()) {
- QFileInfo info(fileName);
- if (m_globalHeader.fileName() == info.fileName())
- return;
-
- int bestMatchLength = 0;
- for (const auto &headerPath : m_headerPaths) {
- if (headerPath.size() > bestMatchLength && matchHeader(headerPath, fileName))
- bestMatchLength = headerPath.size();
- }
- const QString include = bestMatchLength > 0
- ? fileName.right(fileName.size() - bestMatchLength - 1)
- : info.fileName();
- it = m_resolveIncludeHash.insert(fileName, {Include::IncludePath, include});
- }
- te->setInclude(it.value());
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-template <class Container>
-static void debugFormatSequence(QDebug &d, const char *key, const Container& c,
- const char *separator = ", ")
-{
- if (c.isEmpty())
- return;
- const auto begin = c.begin();
- const auto end = c.end();
- d << "\n " << key << '[' << c.size() << "]=(";
- for (auto it = begin; it != end; ++it) {
- if (it != begin)
- d << separator;
- d << *it;
- }
- d << ')';
-}
-
-void AbstractMetaBuilder::formatDebug(QDebug &debug) const
-{
- debug << "m_globalHeader=" << d->m_globalHeader.absoluteFilePath();
- debugFormatSequence(debug, "globalEnums", d->m_globalEnums, "\n");
- debugFormatSequence(debug, "globalFunctions", d->m_globalFunctions, "\n");
- if (const int scopeCount = d->m_scopes.size()) {
- debug << "\n scopes[" << scopeCount << "]=(";
- for (int i = 0; i < scopeCount; ++i) {
- if (i)
- debug << ", ";
- _CodeModelItem::formatKind(debug, d->m_scopes.at(i)->kind());
- debug << " \"" << d->m_scopes.at(i)->name() << '"';
- }
- debug << ')';
- }
- debugFormatSequence(debug, "classes", d->m_metaClasses, "\n");
- debugFormatSequence(debug, "templates", d->m_templates, "\n");
-}
-
-QDebug operator<<(QDebug d, const AbstractMetaBuilder &ab)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaBuilder(";
- ab.formatDebug(d);
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
diff --git a/sources/shiboken2/ApiExtractor/abstractmetabuilder.h b/sources/shiboken2/ApiExtractor/abstractmetabuilder.h
deleted file mode 100644
index 93b9d9fd2..000000000
--- a/sources/shiboken2/ApiExtractor/abstractmetabuilder.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ABSTRACTMETABUILDER_H
-#define ABSTRACTMETABUILDER_H
-
-#include "abstractmetalang_typedefs.h"
-#include "header_paths.h"
-#include "dependency.h"
-
-#include "clangparser/compilersupport.h"
-
-QT_FORWARD_DECLARE_CLASS(QIODevice)
-
-class AbstractMetaBuilderPrivate;
-class AbstractMetaClass;
-class AbstractMetaType;
-class AbstractMetaEnumValue;
-class TypeInfo;
-class TypeEntry;
-
-class AbstractMetaBuilder
-{
-public:
- enum RejectReason {
- NotInTypeSystem,
- GenerationDisabled,
- RedefinedToNotClass,
- UnmatchedArgumentType,
- UnmatchedReturnType,
- ApiIncompatible,
- Deprecated,
- NoReason
- };
-
- AbstractMetaBuilder();
- virtual ~AbstractMetaBuilder();
-
- AbstractMetaClassList classes() const;
- AbstractMetaClassList templates() const;
- AbstractMetaClassList smartPointers() const;
- AbstractMetaFunctionList globalFunctions() const;
- AbstractMetaEnumList globalEnums() const;
- AbstractMetaEnum *findEnum(const TypeEntry *typeEntry) const;
-
- /**
- * Sorts a list of classes topologically.
- * \return a list of classes sorted topologically
- */
- AbstractMetaClassList classesTopologicalSorted(const AbstractMetaClassList &classList,
- const Dependencies &additionalDependencies = Dependencies()) const;
-
- bool build(const QByteArrayList &arguments,
- LanguageLevel level = LanguageLevel::Default,
- unsigned clangFlags = 0);
- void setLogDirectory(const QString& logDir);
-
- /**
- * AbstractMetaBuilder should know what's the global header being used,
- * so any class declared under this header wont have the include file
- * filled.
- */
- void setGlobalHeader(const QString& globalHeader);
- void setHeaderPaths(const HeaderPaths &h);
-
- void setSkipDeprecated(bool value);
-
- enum TranslateTypeFlag {
- DontResolveType = 0x1
- };
- Q_DECLARE_FLAGS(TranslateTypeFlags, TranslateTypeFlag);
-
- static AbstractMetaType *translateType(const TypeInfo &_typei,
- AbstractMetaClass *currentClass = nullptr,
- TranslateTypeFlags flags = {},
- QString *errorMessage = nullptr);
- static AbstractMetaType *translateType(const QString &t,
- AbstractMetaClass *currentClass = nullptr,
- TranslateTypeFlags flags = {},
- QString *errorMessage = nullptr);
-
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const;
-#endif
-
-private:
- friend class AbstractMetaBuilderPrivate;
- AbstractMetaBuilderPrivate *d;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(AbstractMetaBuilder::TranslateTypeFlags);
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaBuilder &ab);
-#endif
-
-#endif // ABSTRACTMETBUILDER_H
diff --git a/sources/shiboken2/ApiExtractor/abstractmetabuilder_p.h b/sources/shiboken2/ApiExtractor/abstractmetabuilder_p.h
deleted file mode 100644
index 7c5462658..000000000
--- a/sources/shiboken2/ApiExtractor/abstractmetabuilder_p.h
+++ /dev/null
@@ -1,206 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ABSTRACTMETABUILDER_P_H
-#define ABSTRACTMETABUILDER_P_H
-
-#include "abstractmetabuilder.h"
-#include "parser/codemodel_fwd.h"
-#include "abstractmetalang.h"
-#include "typesystem.h"
-#include "typeparser.h"
-
-#include <QSet>
-#include <QFileInfo>
-#include <QVector>
-
-class TypeDatabase;
-
-class AbstractMetaBuilderPrivate
-{
-public:
- using TranslateTypeFlags = AbstractMetaBuilder::TranslateTypeFlags;
-
- Q_DISABLE_COPY(AbstractMetaBuilderPrivate)
-
- AbstractMetaBuilderPrivate();
- ~AbstractMetaBuilderPrivate();
-
- static FileModelItem buildDom(QByteArrayList arguments,
- LanguageLevel level,
- unsigned clangFlags);
- void traverseDom(const FileModelItem &dom);
-
- void dumpLog() const;
- AbstractMetaClassList classesTopologicalSorted(const AbstractMetaClassList &classList,
- const Dependencies &additionalDependencies = Dependencies()) const;
- NamespaceModelItem popScope() { return m_scopes.takeLast(); }
-
- void pushScope(const NamespaceModelItem &item);
-
- NamespaceModelItem currentScope() const { return m_scopes.constLast(); }
-
- AbstractMetaClass *argumentToClass(const ArgumentModelItem &,
- AbstractMetaClass *currentClass);
-
- void addAbstractMetaClass(AbstractMetaClass *cls, const _CodeModelItem *item);
- AbstractMetaClass *traverseTypeDef(const FileModelItem &dom,
- const TypeDefModelItem &typeDef,
- AbstractMetaClass *currentClass);
- void traverseTypesystemTypedefs();
- AbstractMetaClass *traverseClass(const FileModelItem &dom,
- const ClassModelItem &item,
- AbstractMetaClass *currentClass);
- void traverseScopeMembers(const ScopeModelItem &item, AbstractMetaClass *metaClass);
- void traverseClassMembers(const ClassModelItem &scopeItem);
- void traverseNamespaceMembers(const NamespaceModelItem &scopeItem);
- bool setupInheritance(AbstractMetaClass *metaClass);
- AbstractMetaClass *traverseNamespace(const FileModelItem &dom,
- const NamespaceModelItem &item);
- AbstractMetaEnum *traverseEnum(const EnumModelItem &item, AbstractMetaClass *enclosing,
- const QSet<QString> &enumsDeclarations);
- void traverseEnums(const ScopeModelItem &item, AbstractMetaClass *parent,
- const QStringList &enumsDeclarations);
- AbstractMetaFunctionList classFunctionList(const ScopeModelItem &scopeItem,
- AbstractMetaClass::Attributes *constructorAttributes,
- AbstractMetaClass *currentClass);
- AbstractMetaFunctionList templateClassFunctionList(const ScopeModelItem &scopeItem,
- AbstractMetaClass *metaClass,
- bool *constructorRejected);
- void traverseFunctions(ScopeModelItem item, AbstractMetaClass *parent);
- void applyFunctionModifications(AbstractMetaFunction* func);
- void traverseFields(const ScopeModelItem &item, AbstractMetaClass *parent);
- void traverseStreamOperator(const FunctionModelItem &functionItem,
- AbstractMetaClass *currentClass);
- void traverseOperatorFunction(const FunctionModelItem &item,
- AbstractMetaClass *currentClass);
- AbstractMetaFunction* traverseFunction(const AddedFunctionPtr &addedFunc);
- AbstractMetaFunction* traverseFunction(const AddedFunctionPtr &addedFunc,
- AbstractMetaClass *metaClass);
- AbstractMetaFunction *traverseFunction(const FunctionModelItem &function,
- AbstractMetaClass *currentClass);
- AbstractMetaField *traverseField(const VariableModelItem &field,
- AbstractMetaClass *cls);
- void checkFunctionModifications();
- void registerHashFunction(const FunctionModelItem &functionItem,
- AbstractMetaClass *currentClass);
- void registerToStringCapabilityIn(const NamespaceModelItem &namespaceItem);
- void registerToStringCapability(const FunctionModelItem &functionItem,
- AbstractMetaClass *currentClass);
-
- /**
- * A conversion operator function should not have its owner class as
- * its return type, but unfortunately it does. This function fixes the
- * return type of operator functions of this kind making the return type
- * be the same as it is supposed to generate when used in C++.
- * If the returned type is a wrapped C++ class, this method also adds the
- * conversion operator to the collection of external conversions of the
- * said class.
- * \param metaFunction conversion operator function to be fixed.
- */
- void fixReturnTypeOfConversionOperator(AbstractMetaFunction *metaFunction);
-
- void parseQ_Property(AbstractMetaClass *metaClass, const QStringList &declarations);
- void setupEquals(AbstractMetaClass *metaClass);
- void setupComparable(AbstractMetaClass *metaClass);
- void setupClonable(AbstractMetaClass *cls);
- void setupExternalConversion(AbstractMetaClass *cls);
- void setupFunctionDefaults(AbstractMetaFunction *metaFunction,
- AbstractMetaClass *metaClass);
-
- QString fixDefaultValue(const ArgumentModelItem &item, AbstractMetaType *type,
- AbstractMetaFunction *fnc, AbstractMetaClass *,
- int argumentIndex);
- AbstractMetaType *translateType(const AddedFunction::TypeInfo &typeInfo,
- QString *errorMessage);
- AbstractMetaType *translateType(const TypeInfo &type,
- AbstractMetaClass *currentClass,
- TranslateTypeFlags flags = {},
- QString *errorMessage = nullptr);
- static AbstractMetaType *translateTypeStatic(const TypeInfo &type,
- AbstractMetaClass *current,
- AbstractMetaBuilderPrivate *d = nullptr,
- TranslateTypeFlags flags = {},
- QString *errorMessageIn = nullptr);
- static TypeEntries findTypeEntries(const QString &qualifiedName, const QString &name,
- AbstractMetaClass *currentClass = nullptr,
- AbstractMetaBuilderPrivate *d = nullptr);
-
- qint64 findOutValueFromString(const QString &stringValue, bool &ok);
-
- AbstractMetaClass *findTemplateClass(const QString& name, const AbstractMetaClass *context,
- TypeInfo *info = Q_NULLPTR,
- ComplexTypeEntry **baseContainerType = Q_NULLPTR) const;
- AbstractMetaClassList getBaseClasses(const AbstractMetaClass *metaClass) const;
- bool ancestorHasPrivateCopyConstructor(const AbstractMetaClass *metaClass) const;
-
- bool inheritTemplate(AbstractMetaClass *subclass,
- const AbstractMetaClass *templateClass,
- const TypeInfo &info);
- AbstractMetaType *inheritTemplateType(const AbstractMetaTypeList &templateTypes,
- const AbstractMetaType *metaType);
-
- bool isQObject(const FileModelItem &dom, const QString &qualifiedName);
- bool isEnum(const FileModelItem &dom, const QStringList &qualifiedName);
-
- void sortLists();
- AbstractMetaArgumentList reverseList(const AbstractMetaArgumentList &list);
- void setInclude(TypeEntry *te, const QString &fileName) const;
- void fixArgumentNames(AbstractMetaFunction *func, const FunctionModificationList &mods);
-
- void fillAddedFunctions(AbstractMetaClass *metaClass);
-
- AbstractMetaBuilder *q;
- AbstractMetaClassList m_metaClasses;
- AbstractMetaClassList m_templates;
- AbstractMetaClassList m_smartPointers;
- QHash<const _CodeModelItem *, AbstractMetaClass *> m_itemToClass;
- AbstractMetaFunctionList m_globalFunctions;
- AbstractMetaEnumList m_globalEnums;
-
- using RejectMap = QMap<QString, AbstractMetaBuilder::RejectReason>;
-
- RejectMap m_rejectedClasses;
- RejectMap m_rejectedEnums;
- RejectMap m_rejectedFunctions;
- RejectMap m_rejectedFields;
-
- QHash<const TypeEntry *, AbstractMetaEnum *> m_enums;
-
- QVector<NamespaceModelItem> m_scopes;
-
- QSet<AbstractMetaClass *> m_setupInheritanceDone;
-
- QString m_logDirectory;
- QFileInfo m_globalHeader;
- QStringList m_headerPaths;
- mutable QHash<QString, Include> m_resolveIncludeHash;
- bool m_skipDeprecated = false;
-};
-
-#endif // ABSTRACTMETBUILDER_P_H
diff --git a/sources/shiboken2/ApiExtractor/abstractmetalang.cpp b/sources/shiboken2/ApiExtractor/abstractmetalang.cpp
deleted file mode 100644
index 390143cda..000000000
--- a/sources/shiboken2/ApiExtractor/abstractmetalang.cpp
+++ /dev/null
@@ -1,2707 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "abstractmetalang.h"
-#include "messages.h"
-#include "reporthandler.h"
-#include "typedatabase.h"
-#include "typesystem.h"
-
-#include <parser/codemodel.h>
-
-#ifndef QT_NO_DEBUG_STREAM
-# include <QtCore/QMetaEnum>
-# include <QtCore/QMetaObject>
-#endif
-
-#include <QtCore/QRegularExpression>
-#include <QtCore/QStack>
-
-#include <algorithm>
-
-#include <algorithm>
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaAttributes *aa)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaAttributes(";
- if (aa)
- d << aa->attributes();
- else
- d << '0';
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-template <class MetaClass>
-MetaClass *findByName(QVector<MetaClass *> haystack, QStringView needle)
-{
- for (MetaClass *c : haystack) {
- if (c->name() == needle)
- return c;
- }
- return nullptr;
-}
-
-// Helper for recursing the base classes of an AbstractMetaClass.
-// Returns the class for which the predicate is true.
-template <class Predicate>
-const AbstractMetaClass *recurseClassHierarchy(const AbstractMetaClass *klass,
- Predicate pred)
-{
- if (pred(klass))
- return klass;
- for (auto base : klass->baseClasses()) {
- if (auto r = recurseClassHierarchy(base, pred))
- return r;
- }
- return nullptr;
-}
-
-/*******************************************************************************
- * AbstractMetaVariable
- */
-
-AbstractMetaVariable::AbstractMetaVariable() = default;
-
-AbstractMetaVariable::~AbstractMetaVariable()
-{
- delete m_type;
-}
-
-void AbstractMetaVariable::assignMetaVariable(const AbstractMetaVariable &other)
-{
- m_originalName = other.m_originalName;
- m_name = other.m_name;
- m_type = other.m_type->copy();
- m_hasName = other.m_hasName;
- m_doc = other.m_doc;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaVariable *av)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaVariable(";
- if (av) {
- d << av->type()->name() << ' ' << av->name();
- } else {
- d << '0';
- }
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-/*******************************************************************************
- * AbstractMetaAttributes
- */
-
-AbstractMetaAttributes::AbstractMetaAttributes() = default;
-AbstractMetaAttributes::~AbstractMetaAttributes() = default;
-
-void AbstractMetaAttributes::assignMetaAttributes(const AbstractMetaAttributes &other)
-{
- m_attributes = other.m_attributes;
- m_originalAttributes = other.m_originalAttributes;
- m_doc = other.m_doc;
-}
-
-/*******************************************************************************
- * AbstractMetaType
- */
-
-AbstractMetaType::AbstractMetaType() :
- m_constant(false),
- m_volatile(false),
- m_cppInstantiation(true),
- m_reserved(0)
-{
-}
-
-AbstractMetaType::~AbstractMetaType()
-{
- qDeleteAll(m_children);
- m_instantiations.clear();
-}
-
-QString AbstractMetaType::package() const
-{
- return m_typeEntry->targetLangPackage();
-}
-
-QString AbstractMetaType::name() const
-{
- return m_typeEntry->targetLangEntryName();
-}
-
-QString AbstractMetaType::fullName() const
-{
- return m_typeEntry->qualifiedTargetLangName();
-}
-
-AbstractMetaType *AbstractMetaType::copy() const
-{
- auto *cpy = new AbstractMetaType;
-
- cpy->setTypeUsagePattern(typeUsagePattern());
- cpy->setConstant(isConstant());
- cpy->setVolatile(isVolatile());
- cpy->setReferenceType(referenceType());
- cpy->setIndirectionsV(indirectionsV());
- cpy->setInstantiations(instantiations());
- cpy->setArrayElementCount(arrayElementCount());
- cpy->setOriginalTypeDescription(originalTypeDescription());
- cpy->setOriginalTemplateType(originalTemplateType() ? originalTemplateType()->copy() : nullptr);
-
- cpy->setArrayElementType(arrayElementType() ? arrayElementType()->copy() : nullptr);
-
- cpy->setTypeEntry(typeEntry());
-
- return cpy;
-}
-
-// For applying the <array> function argument modification: change into a type
-// where "int *" becomes "int[]".
-bool AbstractMetaType::applyArrayModification(QString *errorMessage)
-{
- if (m_pattern == AbstractMetaType::NativePointerAsArrayPattern) {
- *errorMessage = QLatin1String("<array> modification already applied.");
- return false;
- }
- if (m_arrayElementType != nullptr) {
- QTextStream(errorMessage) << "The type \"" << cppSignature()
- << "\" is an array of " << m_arrayElementType->name() << '.';
- return false;
- }
- if (m_indirections.isEmpty()) {
- QTextStream(errorMessage) << "The type \"" << cppSignature()
- << "\" does not have indirections.";
- return false;
- }
- // Element type to be used for ArrayHandle<>, strip constness.
- auto elementType = copy();
- elementType->m_indirections.pop_front();
- elementType->setConstant(false);
- elementType->setVolatile(false);
- elementType->decideUsagePattern();
- m_arrayElementType = elementType;
- setTypeUsagePattern(AbstractMetaType::NativePointerAsArrayPattern);
- return true;
-}
-
-AbstractMetaTypeCList AbstractMetaType::nestedArrayTypes() const
-{
- AbstractMetaTypeCList result;
- switch (m_pattern) {
- case ArrayPattern:
- for (const AbstractMetaType *t = this; t->typeUsagePattern() == ArrayPattern; ) {
- const AbstractMetaType *elt = t->arrayElementType();
- result.append(elt);
- t = elt;
- }
- break;
- case NativePointerAsArrayPattern:
- result.append(m_arrayElementType);
- break;
- default:
- break;
- }
- return result;
-}
-
-bool AbstractMetaType::passByConstRef() const
-{
- return isConstant() && m_referenceType == LValueReference && indirections() == 0;
-}
-
-bool AbstractMetaType::passByValue() const
-{
- return m_referenceType == NoReference && indirections() == 0;
-}
-
-QString AbstractMetaType::cppSignature() const
-{
- if (m_cachedCppSignature.isEmpty())
- m_cachedCppSignature = formatSignature(false);
- return m_cachedCppSignature;
-}
-
-QString AbstractMetaType::pythonSignature() const
-{
- // PYSIDE-921: Handle container returntypes correctly.
- // This is now a clean reimplementation.
- if (m_cachedPythonSignature.isEmpty())
- m_cachedPythonSignature = formatPythonSignature();
- return m_cachedPythonSignature;
-}
-
-AbstractMetaType::TypeUsagePattern AbstractMetaType::determineUsagePattern() const
-{
- if (m_typeEntry->isTemplateArgument() || m_referenceType == RValueReference)
- return InvalidPattern;
-
- if (m_typeEntry->isPrimitive() && (actualIndirections() == 0 || passByConstRef()))
- return PrimitivePattern;
-
- if (m_typeEntry->isVoid())
- return NativePointerPattern;
-
- if (m_typeEntry->isVarargs())
- return VarargsPattern;
-
- if (m_typeEntry->isEnum() && (actualIndirections() == 0 || passByConstRef()))
- return EnumPattern;
-
- if (m_typeEntry->isObject()) {
- if (indirections() == 0 && m_referenceType == NoReference)
- return ValuePattern;
- return ObjectPattern;
- }
-
- if (m_typeEntry->isContainer() && indirections() == 0)
- return ContainerPattern;
-
- if (m_typeEntry->isSmartPointer() && indirections() == 0)
- return SmartPointerPattern;
-
- if (m_typeEntry->isFlags() && (actualIndirections() == 0 || passByConstRef()))
- return FlagsPattern;
-
- if (m_typeEntry->isArray())
- return ArrayPattern;
-
- if (m_typeEntry->isValue())
- return indirections() == 1 ? ValuePointerPattern : ValuePattern;
-
- return NativePointerPattern;
-}
-
-void AbstractMetaType::decideUsagePattern()
-{
- TypeUsagePattern pattern = determineUsagePattern();
- if (m_typeEntry->isObject() && indirections() == 1
- && m_referenceType == LValueReference && isConstant()) {
- // const-references to pointers can be passed as pointers
- setReferenceType(NoReference);
- setConstant(false);
- pattern = ObjectPattern;
- }
- setTypeUsagePattern(pattern);
-}
-
-bool AbstractMetaType::hasTemplateChildren() const
-{
- QStack<AbstractMetaType *> children;
- children << m_children;
-
- // Recursively iterate over the children / descendants of the type, to check if any of them
- // corresponds to a template argument type.
- while (!children.isEmpty()) {
- AbstractMetaType *child = children.pop();
- if (child->typeEntry()->isTemplateArgument())
- return true;
- children << child->m_children;
- }
-
- return false;
-}
-
-bool AbstractMetaType::compare(const AbstractMetaType &rhs, ComparisonFlags flags) const
-{
- if (m_typeEntry != rhs.m_typeEntry
- || m_indirections != rhs.m_indirections
- || m_instantiations.size() != rhs.m_instantiations.size()
- || m_arrayElementCount != rhs.m_arrayElementCount) {
- return false;
- }
-
- if (m_constant != rhs.m_constant || m_referenceType != rhs.m_referenceType) {
- if (!flags.testFlag(ConstRefMatchesValue)
- || !(passByValue() || passByConstRef())
- || !(rhs.passByValue() || rhs.passByConstRef())) {
- return false;
- }
- }
-
- if ((m_arrayElementType != nullptr) != (rhs.m_arrayElementType != nullptr)
- || (m_arrayElementType != nullptr && !m_arrayElementType->compare(*rhs.m_arrayElementType, flags))) {
- return false;
- }
- for (int i = 0, size = m_instantiations.size(); i < size; ++i) {
- if (!m_instantiations.at(i)->compare(*rhs.m_instantiations.at(i), flags))
- return false;
- }
- return true;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaType *at)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaType(";
- if (at) {
- d << at->name();
- if (d.verbosity() > 2) {
- d << ", typeEntry=" << at->typeEntry() << ", signature=\""
- << at->cppSignature() << "\", pattern="
- << at->typeUsagePattern();
- const auto indirections = at->indirectionsV();
- if (!indirections.isEmpty()) {
- d << ", indirections=";
- for (auto i : indirections)
- d << ' ' << TypeInfo::indirectionKeyword(i);
- }
- if (at->referenceType())
- d << ", reftype=" << at->referenceType();
- if (at->isConstant())
- d << ", [const]";
- if (at->isVolatile())
- d << ", [volatile]";
- if (at->isArray()) {
- d << ", array of \"" << at->arrayElementType()->cppSignature()
- << "\", arrayElementCount=" << at->arrayElementCount();
- }
- const auto &instantiations = at->instantiations();
- if (const int instantiationsSize = instantiations.size()) {
- d << ", instantiations[" << instantiationsSize << "]=<";
- for (int i = 0; i < instantiationsSize; ++i) {
- if (i)
- d << ", ";
- d << instantiations.at(i);
- }
- }
- d << '>';
- }
- } else {
- d << '0';
- }
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-/*******************************************************************************
- * AbstractMetaArgument
- */
-
-AbstractMetaArgument::AbstractMetaArgument() = default;
-
-void AbstractMetaArgument::assignMetaArgument(const AbstractMetaArgument &other)
-{
- assignMetaVariable(other);
- m_expression = other.m_expression;
- m_originalExpression = other.m_originalExpression;
- m_argumentIndex = other.m_argumentIndex;
-}
-
-AbstractMetaArgument *AbstractMetaArgument::copy() const
-{
- auto *copy = new AbstractMetaArgument;
- copy->assignMetaArgument(*this);
- return copy;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaArgument *aa)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaArgument(";
- if (aa)
- d << aa->toString();
- else
- d << '0';
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-/*******************************************************************************
- * AbstractMetaFunction
- */
-
-AbstractMetaFunction::AbstractMetaFunction(const AddedFunctionPtr &addedFunc) :
- AbstractMetaFunction()
-{
- m_addedFunction = addedFunc;
- setConstant(addedFunc->isConstant());
- setName(addedFunc->name());
- setOriginalName(addedFunc->name());
- auto atts = attributes() | AbstractMetaAttributes::FinalInTargetLang;
- switch (addedFunc->access()) {
- case AddedFunction::InvalidAccess:
- break;
- case AddedFunction::Protected:
- atts |= AbstractMetaAttributes::Protected;
- break;
- case AddedFunction::Public:
- atts |= AbstractMetaAttributes::Public;
- break;
- }
- if (addedFunc->isStatic())
- atts |= AbstractMetaFunction::Static;
- setAttributes(atts);
-}
-
-AbstractMetaFunction::AbstractMetaFunction()
- : m_constant(false),
- m_reverse(false),
- m_explicit(false),
- m_pointerOperator(false),
- m_isCallOperator(false)
-{
-}
-
-AbstractMetaFunction::~AbstractMetaFunction()
-{
- qDeleteAll(m_arguments);
- delete m_type;
-}
-
-/*******************************************************************************
- * Indicates that this function has a modification that removes it
- */
-bool AbstractMetaFunction::isModifiedRemoved(int types) const
-{
- const FunctionModificationList &mods = modifications(implementingClass());
- for (const FunctionModification &mod : mods) {
- if (!mod.isRemoveModifier())
- continue;
-
- if ((mod.removal & types) == types)
- return true;
- }
-
- return false;
-}
-
-bool AbstractMetaFunction::operator<(const AbstractMetaFunction &other) const
-{
- return compareTo(&other) & NameLessThan;
-}
-
-
-/*!
- Returns a mask of CompareResult describing how this function is
- compares to another function
-*/
-AbstractMetaFunction::CompareResult AbstractMetaFunction::compareTo(const AbstractMetaFunction *other) const
-{
- CompareResult result;
-
- // Enclosing class...
- if (ownerClass() == other->ownerClass())
- result |= EqualImplementor;
-
- // Attributes
- if (attributes() == other->attributes())
- result |= EqualAttributes;
-
- // Compare types
- AbstractMetaType *t = type();
- AbstractMetaType *ot = other->type();
- if ((!t && !ot) || ((t && ot && t->name() == ot->name())))
- result |= EqualReturnType;
-
- // Compare names
- int cmp = originalName().compare(other->originalName());
-
- if (cmp < 0)
- result |= NameLessThan;
- else if (!cmp)
- result |= EqualName;
-
- // compare name after modification...
- cmp = modifiedName().compare(other->modifiedName());
- if (!cmp)
- result |= EqualModifiedName;
-
- // Compare arguments...
- AbstractMetaArgumentList minArguments;
- AbstractMetaArgumentList maxArguments;
- if (arguments().size() < other->arguments().size()) {
- minArguments = arguments();
- maxArguments = other->arguments();
- } else {
- minArguments = other->arguments();
- maxArguments = arguments();
- }
-
- int minCount = minArguments.size();
- int maxCount = maxArguments.size();
- bool same = true;
- for (int i = 0; i < maxCount; ++i) {
- if (i < minCount) {
- const AbstractMetaArgument *min_arg = minArguments.at(i);
- const AbstractMetaArgument *max_arg = maxArguments.at(i);
- if (min_arg->type()->name() != max_arg->type()->name()
- && (min_arg->defaultValueExpression().isEmpty() || max_arg->defaultValueExpression().isEmpty())) {
- same = false;
- break;
- }
- } else {
- if (maxArguments.at(i)->defaultValueExpression().isEmpty()) {
- same = false;
- break;
- }
- }
- }
-
- if (same)
- result |= minCount == maxCount ? EqualArguments : EqualDefaultValueOverload;
-
- return result;
-}
-
-AbstractMetaFunction *AbstractMetaFunction::copy() const
-{
- auto *cpy = new AbstractMetaFunction;
- cpy->assignMetaAttributes(*this);
- cpy->setName(name());
- cpy->setOriginalName(originalName());
- cpy->setOwnerClass(ownerClass());
- cpy->setImplementingClass(implementingClass());
- cpy->setFunctionType(functionType());
- cpy->setDeclaringClass(declaringClass());
- if (type())
- cpy->setType(type()->copy());
- cpy->setConstant(isConstant());
- cpy->setExceptionSpecification(m_exceptionSpecification);
- cpy->setAllowThreadModification(m_allowThreadModification);
- cpy->setExceptionHandlingModification(m_exceptionHandlingModification);
- cpy->m_addedFunction = m_addedFunction;
-
- for (AbstractMetaArgument *arg : m_arguments)
- cpy->addArgument(arg->copy());
-
- Q_ASSERT((!type() && !cpy->type())
- || (type()->instantiations() == cpy->type()->instantiations()));
-
- return cpy;
-}
-
-bool AbstractMetaFunction::usesRValueReferences() const
-{
- if (m_functionType == MoveConstructorFunction || m_functionType == MoveAssignmentOperatorFunction)
- return true;
- if (m_type && m_type->referenceType() == RValueReference)
- return true;
- for (const AbstractMetaArgument *a : m_arguments) {
- if (a->type()->referenceType() == RValueReference)
- return true;
- }
- return false;
-}
-
-QStringList AbstractMetaFunction::introspectionCompatibleSignatures(const QStringList &resolvedArguments) const
-{
- AbstractMetaArgumentList arguments = this->arguments();
- if (arguments.size() == resolvedArguments.size()) {
- QString signature = name() + QLatin1Char('(') + resolvedArguments.join(QLatin1Char(',')) + QLatin1Char(')');
- return QStringList(TypeDatabase::normalizedSignature(signature));
- }
- QStringList returned;
-
- AbstractMetaArgument *argument = arguments.at(resolvedArguments.size());
- QStringList minimalTypeSignature = argument->type()->minimalSignature().split(QLatin1String("::"));
- for (int i = 0; i < minimalTypeSignature.size(); ++i) {
- returned += introspectionCompatibleSignatures(QStringList(resolvedArguments)
- << QStringList(minimalTypeSignature.mid(minimalTypeSignature.size() - i - 1)).join(QLatin1String("::")));
- }
-
- return returned;
-}
-
-QString AbstractMetaFunction::signature() const
-{
- if (m_cachedSignature.isEmpty()) {
- m_cachedSignature = m_originalName;
-
- m_cachedSignature += QLatin1Char('(');
-
- for (int i = 0; i < m_arguments.count(); ++i) {
- AbstractMetaArgument *a = m_arguments.at(i);
- AbstractMetaType *t = a->type();
- if (t) {
- if (i > 0)
- m_cachedSignature += QLatin1String(", ");
- m_cachedSignature += t->cppSignature();
- // We need to have the argument names in the qdoc files
- m_cachedSignature += QLatin1Char(' ');
- m_cachedSignature += a->name();
- } else {
- qCWarning(lcShiboken).noquote().nospace()
- << QString::fromLatin1("No abstract meta type found for argument '%1' while"
- "constructing signature for function '%2'.")
- .arg(a->name(), name());
- }
- }
- m_cachedSignature += QLatin1Char(')');
-
- if (isConstant())
- m_cachedSignature += QLatin1String(" const");
- }
- return m_cachedSignature;
-}
-
-int AbstractMetaFunction::actualMinimumArgumentCount() const
-{
- AbstractMetaArgumentList arguments = this->arguments();
-
- int count = 0;
- for (int i = 0; i < arguments.size(); ++i && ++count) {
- if (argumentRemoved(i + 1))
- --count;
- else if (!arguments.at(i)->defaultValueExpression().isEmpty())
- break;
- }
-
- return count;
-}
-
-// Returns reference counts for argument at idx, or all arguments if idx == -2
-QVector<ReferenceCount> AbstractMetaFunction::referenceCounts(const AbstractMetaClass *cls, int idx) const
-{
- QVector<ReferenceCount> returned;
-
- const FunctionModificationList &mods = this->modifications(cls);
- for (const FunctionModification &mod : mods) {
- for (const ArgumentModification &argumentMod : mod.argument_mods) {
- if (argumentMod.index != idx && idx != -2)
- continue;
- returned += argumentMod.referenceCounts;
- }
- }
-
- return returned;
-}
-
-
-ArgumentOwner AbstractMetaFunction::argumentOwner(const AbstractMetaClass *cls, int idx) const
-{
- const FunctionModificationList &mods = this->modifications(cls);
- for (const FunctionModification &mod : mods) {
- for (const ArgumentModification &argumentMod : mod.argument_mods) {
- if (argumentMod.index != idx)
- continue;
- return argumentMod.owner;
- }
- }
- return ArgumentOwner();
-}
-
-QString AbstractMetaFunction::conversionRule(TypeSystem::Language language, int key) const
-{
- const FunctionModificationList &modifications = this->modifications(declaringClass());
- for (const FunctionModification &modification : modifications) {
- for (const ArgumentModification &argumentModification : modification.argument_mods) {
- if (argumentModification.index != key)
- continue;
-
- for (const CodeSnip &snip : argumentModification.conversion_rules) {
- if (snip.language == language && !snip.code().isEmpty())
- return snip.code();
- }
- }
- }
-
- return QString();
-}
-
-// FIXME If we remove a arg. in the method at the base class, it will not reflect here.
-bool AbstractMetaFunction::argumentRemoved(int key) const
-{
- const FunctionModificationList &modifications = this->modifications(declaringClass());
- for (const FunctionModification &modification : modifications) {
- for (const ArgumentModification &argumentModification : modification.argument_mods) {
- if (argumentModification.index == key) {
- if (argumentModification.removed)
- return true;
- }
- }
- }
-
- return false;
-}
-
-bool AbstractMetaFunction::isDeprecated() const
-{
- const FunctionModificationList &modifications = this->modifications(declaringClass());
- for (const FunctionModification &modification : modifications) {
- if (modification.isDeprecated())
- return true;
- }
- return false;
-}
-
-// Auto-detect whether a function should be wrapped into
-// Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS, that is, temporarily release
-// the GIL (global interpreter lock). Doing so is required for any thread-wait
-// functions, anything that might call a virtual function (potentially
-// reimplemented in Python), and recommended for lengthy I/O or similar.
-// It has performance costs, though.
-bool AbstractMetaFunction::autoDetectAllowThread() const
-{
- // Disallow for simple getter functions.
- const bool maybeGetter = m_constant != 0 && m_type != nullptr
- && m_arguments.isEmpty();
- return !maybeGetter;
-}
-
-static inline TypeSystem::AllowThread allowThreadMod(const AbstractMetaClass *klass)
-{
- return klass->typeEntry()->allowThread();
-}
-
-static inline bool hasAllowThreadMod(const AbstractMetaClass *klass)
-{
- return allowThreadMod(klass) != TypeSystem::AllowThread::Unspecified;
-}
-
-bool AbstractMetaFunction::allowThread() const
-{
- auto allowThreadModification = m_allowThreadModification;
- // If there is no modification on the function, check for a base class.
- if (m_class && allowThreadModification == TypeSystem::AllowThread::Unspecified) {
- if (auto base = recurseClassHierarchy(m_class, hasAllowThreadMod))
- allowThreadModification = allowThreadMod(base);
- }
-
- bool result = true;
- switch (allowThreadModification) {
- case TypeSystem::AllowThread::Disallow:
- result = false;
- break;
- case TypeSystem::AllowThread::Allow:
- break;
- case TypeSystem::AllowThread::Auto:
- result = autoDetectAllowThread();
- break;
- case TypeSystem::AllowThread::Unspecified:
- result = false;
- break;
- }
- if (!result && ReportHandler::isDebug(ReportHandler::MediumDebug))
- qCInfo(lcShiboken).noquote() << msgDisallowThread(this);
- return result;
-}
-
-TypeSystem::Ownership AbstractMetaFunction::ownership(const AbstractMetaClass *cls, TypeSystem::Language language, int key) const
-{
- const FunctionModificationList &modifications = this->modifications(cls);
- for (const FunctionModification &modification : modifications) {
- for (const ArgumentModification &argumentModification : modification.argument_mods) {
- if (argumentModification.index == key)
- return argumentModification.ownerships.value(language, TypeSystem::InvalidOwnership);
- }
- }
-
- return TypeSystem::InvalidOwnership;
-}
-
-bool AbstractMetaFunction::isRemovedFromAllLanguages(const AbstractMetaClass *cls) const
-{
- return isRemovedFrom(cls, TypeSystem::All);
-}
-
-bool AbstractMetaFunction::isRemovedFrom(const AbstractMetaClass *cls, TypeSystem::Language language) const
-{
- const FunctionModificationList &modifications = this->modifications(cls);
- for (const FunctionModification &modification : modifications) {
- if ((modification.removal & language) == language)
- return true;
- }
-
- return false;
-
-}
-
-QString AbstractMetaFunction::typeReplaced(int key) const
-{
- const FunctionModificationList &modifications = this->modifications(declaringClass());
- for (const FunctionModification &modification : modifications) {
- for (const ArgumentModification &argumentModification : modification.argument_mods) {
- if (argumentModification.index == key
- && !argumentModification.modified_type.isEmpty()) {
- return argumentModification.modified_type;
- }
- }
- }
-
- return QString();
-}
-
-bool AbstractMetaFunction::isModifiedToArray(int argumentIndex) const
-{
- const FunctionModificationList &modifications = this->modifications(declaringClass());
- for (const FunctionModification &modification : modifications) {
- for (const ArgumentModification &argumentModification : modification.argument_mods) {
- if (argumentModification.index == argumentIndex && argumentModification.array != 0)
- return true;
- }
- }
- return false;
-}
-
-QString AbstractMetaFunction::minimalSignature() const
-{
- if (!m_cachedMinimalSignature.isEmpty())
- return m_cachedMinimalSignature;
-
- QString minimalSignature = originalName() + QLatin1Char('(');
- AbstractMetaArgumentList arguments = this->arguments();
-
- for (int i = 0; i < arguments.count(); ++i) {
- AbstractMetaType *t = arguments.at(i)->type();
- if (t) {
- if (i > 0)
- minimalSignature += QLatin1Char(',');
- minimalSignature += t->minimalSignature();
- } else {
- qCWarning(lcShiboken).noquote().nospace()
- << QString::fromLatin1("No abstract meta type found for argument '%1' while constructing"
- " minimal signature for function '%2'.")
- .arg(arguments.at(i)->name(), name());
- }
- }
- minimalSignature += QLatin1Char(')');
- if (isConstant())
- minimalSignature += QLatin1String("const");
-
- minimalSignature = TypeDatabase::normalizedSignature(minimalSignature);
- m_cachedMinimalSignature = minimalSignature;
-
- return minimalSignature;
-}
-
-QString AbstractMetaFunction::debugSignature() const
-{
- QString result;
- const bool isOverride = attributes() & AbstractMetaFunction::OverriddenCppMethod;
- const bool isFinal = attributes() & AbstractMetaFunction::FinalCppMethod;
- if (!isOverride && !isFinal && (attributes() & AbstractMetaFunction::VirtualCppMethod))
- result += QLatin1String("virtual ");
- result += minimalSignature();
- if (isOverride)
- result += QLatin1String(" override");
- if (isFinal)
- result += QLatin1String(" final");
- return result;
-}
-
-FunctionModificationList AbstractMetaFunction::modifications(const AbstractMetaClass *implementor) const
-{
- if (!m_addedFunction.isNull())
- return m_addedFunction->modifications;
- if (!implementor)
- implementor = ownerClass();
-
- if (!implementor)
- return TypeDatabase::instance()->functionModifications(minimalSignature());
-
- FunctionModificationList mods;
- while (implementor) {
- mods += implementor->typeEntry()->functionModifications(minimalSignature());
- if ((implementor == implementor->baseClass()) ||
- (implementor == implementingClass() && !mods.isEmpty())) {
- break;
- }
- implementor = implementor->baseClass();
- }
- return mods;
-}
-
-QString AbstractMetaFunction::argumentName(int index,
- bool /* create */,
- const AbstractMetaClass * /* implementor */) const
-{
- return m_arguments[--index]->name();
-}
-
-bool AbstractMetaFunction::isCallOperator() const
-{
- return m_name == QLatin1String("operator()");
-}
-
-bool AbstractMetaFunction::hasInjectedCode() const
-{
- const FunctionModificationList &mods = modifications(ownerClass());
- for (const FunctionModification &mod : mods) {
- if (mod.isCodeInjection())
- return true;
- }
- return false;
-}
-
-CodeSnipList AbstractMetaFunction::injectedCodeSnips(TypeSystem::CodeSnipPosition position, TypeSystem::Language language) const
-{
- CodeSnipList result;
- const FunctionModificationList &mods = modifications(ownerClass());
- for (const FunctionModification &mod : mods) {
- if (mod.isCodeInjection()) {
- for (const CodeSnip &snip : mod.snips) {
- if ((snip.language & language) && (snip.position == position || position == TypeSystem::CodeSnipPositionAny))
- result << snip;
- }
- }
- }
- return result;
-}
-
-bool AbstractMetaFunction::hasSignatureModifications() const
-{
- const FunctionModificationList &mods = modifications();
- for (const FunctionModification &mod : mods) {
- if (mod.isRenameModifier())
- return true;
- for (const ArgumentModification &argmod : mod.argument_mods) {
- // since zero represents the return type and we're
- // interested only in checking the function arguments,
- // it will be ignored.
- if (argmod.index > 0)
- return true;
- }
- }
- return false;
-}
-
-bool AbstractMetaFunction::isConversionOperator(const QString &funcName)
-{
- static const QRegularExpression opRegEx(QStringLiteral("^operator(?:\\s+(?:const|volatile))?\\s+(\\w+\\s*)&?$"));
- Q_ASSERT(opRegEx.isValid());
- return opRegEx.match(funcName).hasMatch();
-}
-
-ExceptionSpecification AbstractMetaFunction::exceptionSpecification() const
-{
- return m_exceptionSpecification;
-}
-
-void AbstractMetaFunction::setExceptionSpecification(ExceptionSpecification e)
-{
- m_exceptionSpecification = e;
-}
-
-static inline TypeSystem::ExceptionHandling exceptionMod(const AbstractMetaClass *klass)
-{
- return klass->typeEntry()->exceptionHandling();
-}
-
-static inline bool hasExceptionMod(const AbstractMetaClass *klass)
-{
- return exceptionMod(klass) != TypeSystem::ExceptionHandling::Unspecified;
-}
-
-bool AbstractMetaFunction::generateExceptionHandling() const
-{
- switch (m_functionType) {
- case AbstractMetaFunction::CopyConstructorFunction:
- case AbstractMetaFunction::MoveConstructorFunction:
- case AbstractMetaFunction::AssignmentOperatorFunction:
- case AbstractMetaFunction::MoveAssignmentOperatorFunction:
- case AbstractMetaFunction::DestructorFunction:
- return false;
- default:
- break;
- }
-
- auto exceptionHandlingModification = m_exceptionHandlingModification;
- // If there is no modification on the function, check for a base class.
- if (m_class && exceptionHandlingModification == TypeSystem::ExceptionHandling::Unspecified) {
- if (auto base = recurseClassHierarchy(m_class, hasExceptionMod))
- exceptionHandlingModification = exceptionMod(base);
- }
-
- bool result = false;
- switch (exceptionHandlingModification) {
- case TypeSystem::ExceptionHandling::On:
- result = true;
- break;
- case TypeSystem::ExceptionHandling::AutoDefaultToOn:
- result = m_exceptionSpecification != ExceptionSpecification::NoExcept;
- break;
- case TypeSystem::ExceptionHandling::AutoDefaultToOff:
- result = m_exceptionSpecification == ExceptionSpecification::Throws;
- break;
- case TypeSystem::ExceptionHandling::Unspecified:
- case TypeSystem::ExceptionHandling::Off:
- break;
- }
- return result;
-}
-
-bool AbstractMetaFunction::isOperatorOverload(const QString &funcName)
-{
- if (isConversionOperator(funcName))
- return true;
-
- static const QRegularExpression opRegEx(QLatin1String("^operator([+\\-\\*/%=&\\|\\^\\<>!][=]?"
- "|\\+\\+|\\-\\-|&&|\\|\\||<<[=]?|>>[=]?|~"
- "|\\[\\]|\\s+delete\\[?\\]?"
- "|\\(\\)"
- "|\\s+new\\[?\\]?)$"));
- Q_ASSERT(opRegEx.isValid());
- return opRegEx.match(funcName).hasMatch();
-}
-
-bool AbstractMetaFunction::isCastOperator() const
-{
- return originalName().startsWith(QLatin1String("operator "));
-}
-
-bool AbstractMetaFunction::isArithmeticOperator() const
-{
- if (!isOperatorOverload())
- return false;
-
- QString name = originalName();
-
- // It's a dereference operator!
- if (name == QLatin1String("operator*") && m_arguments.isEmpty())
- return false;
-
- return name == QLatin1String("operator+") || name == QLatin1String("operator+=")
- || name == QLatin1String("operator-") || name == QLatin1String("operator-=")
- || name == QLatin1String("operator*") || name == QLatin1String("operator*=")
- || name == QLatin1String("operator/") || name == QLatin1String("operator/=")
- || name == QLatin1String("operator%") || name == QLatin1String("operator%=")
- || name == QLatin1String("operator++") || name == QLatin1String("operator--");
-}
-
-bool AbstractMetaFunction::isBitwiseOperator() const
-{
- if (!isOperatorOverload())
- return false;
-
- QString name = originalName();
- return name == QLatin1String("operator<<") || name == QLatin1String("operator<<=")
- || name == QLatin1String("operator>>") || name == QLatin1String("operator>>=")
- || name == QLatin1String("operator&") || name == QLatin1String("operator&=")
- || name == QLatin1String("operator|") || name == QLatin1String("operator|=")
- || name == QLatin1String("operator^") || name == QLatin1String("operator^=")
- || name == QLatin1String("operator~");
-}
-
-bool AbstractMetaFunction::isComparisonOperator() const
-{
- if (!isOperatorOverload())
- return false;
-
- QString name = originalName();
- return name == QLatin1String("operator<") || name == QLatin1String("operator<=")
- || name == QLatin1String("operator>") || name == QLatin1String("operator>=")
- || name == QLatin1String("operator==") || name == QLatin1String("operator!=");
-}
-
-bool AbstractMetaFunction::isLogicalOperator() const
-{
- if (!isOperatorOverload())
- return false;
-
- QString name = originalName();
- return name == QLatin1String("operator!")
- || name == QLatin1String("operator&&")
- || name == QLatin1String("operator||");
-}
-
-bool AbstractMetaFunction::isSubscriptOperator() const
-{
- if (!isOperatorOverload())
- return false;
-
- return originalName() == QLatin1String("operator[]");
-}
-
-bool AbstractMetaFunction::isAssignmentOperator() const
-{
- return m_functionType == AssignmentOperatorFunction
- || m_functionType == MoveAssignmentOperatorFunction;
-}
-
-bool AbstractMetaFunction::isOtherOperator() const
-{
- if (!isOperatorOverload())
- return false;
-
- return !isArithmeticOperator()
- && !isBitwiseOperator()
- && !isComparisonOperator()
- && !isLogicalOperator()
- && !isConversionOperator()
- && !isSubscriptOperator()
- && !isAssignmentOperator();
-}
-
-int AbstractMetaFunction::arityOfOperator() const
-{
- if (!isOperatorOverload() || isCallOperator())
- return -1;
-
- int arity = m_arguments.size();
-
- // Operator overloads that are class members
- // implicitly includes the instance and have
- // one parameter less than their arity,
- // so we increment it.
- if (ownerClass() && arity < 2)
- arity++;
-
- return arity;
-}
-
-bool AbstractMetaFunction::isInplaceOperator() const
-{
- if (!isOperatorOverload())
- return false;
-
- QString name = originalName();
- return name == QLatin1String("operator+=") || name == QLatin1String("operator&=")
- || name == QLatin1String("operator-=") || name == QLatin1String("operator|=")
- || name == QLatin1String("operator*=") || name == QLatin1String("operator^=")
- || name == QLatin1String("operator/=") || name == QLatin1String("operator<<=")
- || name == QLatin1String("operator%=") || name == QLatin1String("operator>>=");
-}
-
-bool AbstractMetaFunction::isVirtual() const
-{
- return attributes() & AbstractMetaAttributes::VirtualCppMethod;
-}
-
-QString AbstractMetaFunction::modifiedName() const
-{
- if (m_cachedModifiedName.isEmpty()) {
- const FunctionModificationList &mods = modifications(implementingClass());
- for (const FunctionModification &mod : mods) {
- if (mod.isRenameModifier()) {
- m_cachedModifiedName = mod.renamedToName;
- break;
- }
- }
- if (m_cachedModifiedName.isEmpty())
- m_cachedModifiedName = name();
- }
- return m_cachedModifiedName;
-}
-
-bool function_sorter(AbstractMetaFunction *a, AbstractMetaFunction *b)
-{
- return a->signature() < b->signature();
-}
-
-AbstractMetaFunction *
-AbstractMetaFunction::find(const AbstractMetaFunctionList &haystack,
- const QString &needle)
-{
- return findByName(haystack, needle);
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-static inline void formatMetaFunctionBrief(QDebug &d, const AbstractMetaFunction *af)
-{
- d << '"' << af->debugSignature() << '"';
-}
-
-void AbstractMetaFunction::formatDebugVerbose(QDebug &d) const
-{
- d << m_functionType << ' ' << m_type << ' ' << m_name;
- switch (m_exceptionSpecification) {
- case ExceptionSpecification::Unknown:
- break;
- case ExceptionSpecification::NoExcept:
- d << " noexcept";
- break;
- case ExceptionSpecification::Throws:
- d << " throw(...)";
- break;
- }
- if (m_exceptionHandlingModification != TypeSystem::ExceptionHandling::Unspecified)
- d << " exeption-mod " << int(m_exceptionHandlingModification);
- d << '(';
- for (int i = 0, count = m_arguments.size(); i < count; ++i) {
- if (i)
- d << ", ";
- d << m_arguments.at(i);
- }
- d << "), signature=\"" << minimalSignature() << '"';
- if (m_constant)
- d << " [const]";
- if (m_reverse)
- d << " [reverse]";
- if (isUserAdded())
- d << " [userAdded]";
- if (m_explicit)
- d << " [explicit]";
- if (attributes().testFlag(AbstractMetaAttributes::Deprecated))
- d << " [deprecated]";
- if (m_pointerOperator)
- d << " [operator->]";
- if (m_isCallOperator)
- d << " [operator()]";
- if (m_class)
- d << " class: " << m_class->name();
- if (m_implementingClass)
- d << " implementing class: " << m_implementingClass->name();
- if (m_declaringClass)
- d << " declaring class: " << m_declaringClass->name();
-}
-
-QDebug operator<<(QDebug d, const AbstractMetaFunction *af)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaFunction(";
- if (af) {
-#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
- if (d.verbosity() > 2) {
- af->formatDebugVerbose(d);
- } else {
-#endif
- d << "signature=";
- formatMetaFunctionBrief(d, af);
-#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
- }
-#endif
- } else {
- d << '0';
- }
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-/*******************************************************************************
- * AbstractMetaClass
- */
-
-AbstractMetaClass::AbstractMetaClass()
- : m_hasVirtuals(false),
- m_isPolymorphic(false),
- m_hasNonpublic(false),
- m_hasNonPrivateConstructor(false),
- m_hasPrivateConstructor(false),
- m_functionsFixed(false),
- m_hasPrivateDestructor(false),
- m_hasProtectedDestructor(false),
- m_hasVirtualDestructor(false),
- m_hasHashFunction(false),
- m_hasEqualsOperator(false),
- m_hasCloneOperator(false),
- m_isTypeDef(false),
- m_hasToStringCapability(false)
-{
-}
-
-AbstractMetaClass::~AbstractMetaClass()
-{
- qDeleteAll(m_functions);
- qDeleteAll(m_fields);
- qDeleteAll(m_enums);
- if (hasTemplateBaseClassInstantiations())
- qDeleteAll(templateBaseClassInstantiations());
-}
-
-/*******************************************************************************
- * Returns true if this class is a subclass of the given class
- */
-bool AbstractMetaClass::inheritsFrom(const AbstractMetaClass *cls) const
-{
- Q_ASSERT(cls);
-
- const AbstractMetaClass *clazz = this;
- while (clazz) {
- if (clazz == cls)
- return true;
-
- clazz = clazz->baseClass();
- }
-
- return false;
-}
-
-/*******************************************************************************
- * Returns a list of all the functions with a given name
- */
-AbstractMetaFunctionList AbstractMetaClass::queryFunctionsByName(const QString &name) const
-{
- AbstractMetaFunctionList returned;
- for (AbstractMetaFunction *function : m_functions) {
- if (function->name() == name)
- returned.append(function);
- }
-
- return returned;
-}
-
-/*******************************************************************************
- * Returns a list of all the functions retrieved during parsing which should
- * be added to the API.
- */
-AbstractMetaFunctionList AbstractMetaClass::functionsInTargetLang() const
-{
- FunctionQueryOptions default_flags = NormalFunctions | Visible | NotRemovedFromTargetLang;
-
- // Only public functions in final classes
- // default_flags |= isFinal() ? WasPublic : 0;
- FunctionQueryOptions public_flags;
- if (isFinalInTargetLang())
- public_flags |= WasPublic;
-
- // Constructors
- AbstractMetaFunctionList returned = queryFunctions(Constructors | default_flags | public_flags);
-
- // Final functions
- returned += queryFunctions(FinalInTargetLangFunctions | NonStaticFunctions | default_flags | public_flags);
-
- // Virtual functions
- returned += queryFunctions(VirtualInTargetLangFunctions | NonStaticFunctions | default_flags | public_flags);
-
- // Static functions
- returned += queryFunctions(StaticFunctions | default_flags | public_flags);
-
- // Empty, private functions, since they aren't caught by the other ones
- returned += queryFunctions(Empty | Invisible);
-
- return returned;
-}
-
-AbstractMetaFunctionList AbstractMetaClass::implicitConversions() const
-{
- if (!hasCloneOperator() && !hasExternalConversionOperators())
- return AbstractMetaFunctionList();
-
- AbstractMetaFunctionList returned;
- const AbstractMetaFunctionList list = queryFunctions(Constructors) + externalConversionOperators();
-
- // Exclude anything that uses rvalue references, be it a move
- // constructor "QPolygon(QPolygon &&)" or something else like
- // "QPolygon(QVector<QPoint> &&)".
- for (AbstractMetaFunction *f : list) {
- if ((f->actualMinimumArgumentCount() == 1 || f->arguments().size() == 1 || f->isConversionOperator())
- && !f->isExplicit()
- && f->functionType() != AbstractMetaFunction::CopyConstructorFunction
- && !f->usesRValueReferences()
- && !f->isModifiedRemoved()
- && (f->originalAttributes() & Public)) {
- returned += f;
- }
- }
- return returned;
-}
-
-AbstractMetaFunctionList AbstractMetaClass::operatorOverloads(OperatorQueryOptions query) const
-{
- const AbstractMetaFunctionList &list = queryFunctions(OperatorOverloads | Visible);
- AbstractMetaFunctionList returned;
- for (AbstractMetaFunction *f : list) {
- if (((query & ArithmeticOp) && f->isArithmeticOperator())
- || ((query & BitwiseOp) && f->isBitwiseOperator())
- || ((query & ComparisonOp) && f->isComparisonOperator())
- || ((query & LogicalOp) && f->isLogicalOperator())
- || ((query & SubscriptionOp) && f->isSubscriptOperator())
- || ((query & AssignmentOp) && f->isAssignmentOperator())
- || ((query & ConversionOp) && f->isConversionOperator())
- || ((query & OtherOp) && f->isOtherOperator()))
- returned += f;
- }
-
- return returned;
-}
-
-bool AbstractMetaClass::hasArithmeticOperatorOverload() const
-{
- for (const AbstractMetaFunction *f : m_functions) {
- if (f->ownerClass() == f->implementingClass() && f->isArithmeticOperator() && !f->isPrivate())
- return true;
- }
- return false;
-}
-
-bool AbstractMetaClass::hasBitwiseOperatorOverload() const
-{
- for (const AbstractMetaFunction *f : m_functions) {
- if (f->ownerClass() == f->implementingClass() && f->isBitwiseOperator() && !f->isPrivate())
- return true;
- }
- return false;
-}
-
-bool AbstractMetaClass::hasComparisonOperatorOverload() const
-{
- for (const AbstractMetaFunction *f : m_functions) {
- if (f->ownerClass() == f->implementingClass() && f->isComparisonOperator() && !f->isPrivate())
- return true;
- }
- return false;
-}
-
-bool AbstractMetaClass::hasLogicalOperatorOverload() const
-{
- for (const AbstractMetaFunction *f : m_functions) {
- if (f->ownerClass() == f->implementingClass() && f->isLogicalOperator() && !f->isPrivate())
- return true;
- }
- return false;
-}
-
-void AbstractMetaClass::sortFunctions()
-{
- std::sort(m_functions.begin(), m_functions.end(), function_sorter);
-}
-
-void AbstractMetaClass::setFunctions(const AbstractMetaFunctionList &functions)
-{
- m_functions = functions;
-
- // Functions must be sorted by name before next loop
- sortFunctions();
-
- for (AbstractMetaFunction *f : qAsConst(m_functions)) {
- f->setOwnerClass(this);
- if (!f->isPublic())
- m_hasNonpublic = true;
- }
-}
-
-bool AbstractMetaClass::hasFieldAccessors() const
-{
- for (const AbstractMetaField *field : m_fields) {
- if (field->getter() || field->setter())
- return true;
- }
-
- return false;
-}
-
-bool AbstractMetaClass::hasDefaultToStringFunction() const
-{
- const AbstractMetaFunctionList &funcs = queryFunctionsByName(QLatin1String("toString"));
- for (const AbstractMetaFunction *f : funcs) {
- if (!f->actualMinimumArgumentCount())
- return true;
- }
- return false;
-}
-
-void AbstractMetaClass::addFunction(AbstractMetaFunction *function)
-{
- Q_ASSERT(!function->signature().startsWith(QLatin1Char('(')));
- function->setOwnerClass(this);
-
- if (!function->isDestructor())
- m_functions << function;
- else
- Q_ASSERT(false); //memory leak
-
- m_hasVirtuals |= function->isVirtual();
- m_isPolymorphic |= m_hasVirtuals;
- m_hasNonpublic |= !function->isPublic();
-}
-
-bool AbstractMetaClass::hasSignal(const AbstractMetaFunction *other) const
-{
- if (!other->isSignal())
- return false;
-
- for (const AbstractMetaFunction *f : m_functions) {
- if (f->isSignal() && f->compareTo(other) & AbstractMetaFunction::EqualName)
- return other->modifiedName() == f->modifiedName();
- }
-
- return false;
-}
-
-
-QString AbstractMetaClass::name() const
-{
- return m_typeEntry->targetLangEntryName();
-}
-
-void AbstractMetaClass::addBaseClass(AbstractMetaClass *baseClass)
-{
- Q_ASSERT(baseClass);
- m_baseClasses.append(baseClass);
- m_isPolymorphic |= baseClass->isPolymorphic();
-}
-
-void AbstractMetaClass::setBaseClass(AbstractMetaClass *baseClass)
-{
- if (baseClass) {
- m_baseClasses.prepend(baseClass);
- m_isPolymorphic |= baseClass->isPolymorphic();
- }
-}
-
-QString AbstractMetaClass::package() const
-{
- return m_typeEntry->targetLangPackage();
-}
-
-bool AbstractMetaClass::isNamespace() const
-{
- return m_typeEntry->isNamespace();
-}
-
-static bool qObjectPredicate(const AbstractMetaClass *c)
-{
- return c->qualifiedCppName() == QLatin1String("QObject");
-}
-
-bool AbstractMetaClass::isQObject() const
-{
- return qObjectPredicate(this) || recurseClassHierarchy(this, qObjectPredicate) != nullptr;
-}
-
-QString AbstractMetaClass::qualifiedCppName() const
-{
- return m_typeEntry->qualifiedCppName();
-}
-
-bool AbstractMetaClass::hasFunction(const QString &str) const
-{
- return findFunction(str);
-}
-
-const AbstractMetaFunction *AbstractMetaClass::findFunction(const QString &functionName) const
-{
- return AbstractMetaFunction::find(m_functions, functionName);
-}
-
-bool AbstractMetaClass::hasProtectedFunctions() const
-{
- for (AbstractMetaFunction *func : m_functions) {
- if (func->isProtected())
- return true;
- }
- return false;
-}
-
-bool AbstractMetaClass::hasProtectedFields() const
-{
- for (const AbstractMetaField *field : m_fields) {
- if (field->isProtected())
- return true;
- }
- return false;
-}
-
-bool AbstractMetaClass::hasProtectedMembers() const
-{
- return hasProtectedFields() || hasProtectedFunctions();
-}
-
-QPropertySpec *AbstractMetaClass::propertySpecForRead(const QString &name) const
-{
- for (const auto &propertySpec : m_propertySpecs) {
- if (name == propertySpec->read())
- return propertySpec;
- }
- return nullptr;
-}
-
-QPropertySpec *AbstractMetaClass::propertySpecForWrite(const QString &name) const
-{
- for (const auto &propertySpec : m_propertySpecs) {
- if (name == propertySpec->write())
- return propertySpec;
- }
- return nullptr;
-}
-
-QPropertySpec *AbstractMetaClass::propertySpecForReset(const QString &name) const
-{
- for (const auto &propertySpec : m_propertySpecs) {
- if (name == propertySpec->reset())
- return propertySpec;
- }
- return nullptr;
-}
-
-using AbstractMetaClassBaseTemplateInstantiationsMap = QHash<const AbstractMetaClass *, AbstractMetaTypeList>;
-Q_GLOBAL_STATIC(AbstractMetaClassBaseTemplateInstantiationsMap, metaClassBaseTemplateInstantiations);
-
-bool AbstractMetaClass::hasTemplateBaseClassInstantiations() const
-{
- if (!templateBaseClass())
- return false;
- return metaClassBaseTemplateInstantiations()->contains(this);
-}
-
-AbstractMetaTypeList AbstractMetaClass::templateBaseClassInstantiations() const
-{
- if (!templateBaseClass())
- return AbstractMetaTypeList();
- return metaClassBaseTemplateInstantiations()->value(this);
-}
-
-void AbstractMetaClass::setTemplateBaseClassInstantiations(AbstractMetaTypeList &instantiations)
-{
- if (!templateBaseClass())
- return;
- metaClassBaseTemplateInstantiations()->insert(this, instantiations);
-}
-
-// Does any of the base classes require deletion in the main thread?
-bool AbstractMetaClass::deleteInMainThread() const
-{
- return typeEntry()->deleteInMainThread()
- || (!m_baseClasses.isEmpty() && m_baseClasses.constFirst()->deleteInMainThread());
-}
-
-static bool functions_contains(const AbstractMetaFunctionList &l, const AbstractMetaFunction *func)
-{
- for (const AbstractMetaFunction *f : l) {
- if ((f->compareTo(func) & AbstractMetaFunction::PrettySimilar) == AbstractMetaFunction::PrettySimilar)
- return true;
- }
- return false;
-}
-
-AbstractMetaField::AbstractMetaField() = default;
-
-AbstractMetaField::~AbstractMetaField()
-{
- delete m_setter;
- delete m_getter;
-}
-
-AbstractMetaField *AbstractMetaField::copy() const
-{
- auto *returned = new AbstractMetaField;
- returned->assignMetaVariable(*this);
- returned->assignMetaAttributes(*this);
- returned->setEnclosingClass(nullptr);
- return returned;
-}
-
-AbstractMetaField *AbstractMetaField::find(const AbstractMetaFieldList &haystack,
- const QString &needle)
-{
- return findByName(haystack, needle);
-}
-/*******************************************************************************
- * Indicates that this field has a modification that removes it
- */
-bool AbstractMetaField::isModifiedRemoved(int types) const
-{
- const FieldModificationList &mods = modifications();
- for (const FieldModification &mod : mods) {
- if (!mod.isRemoveModifier())
- continue;
-
- if ((mod.removal & types) == types)
- return true;
- }
-
- return false;
-}
-
-static QString upCaseFirst(const QString &str)
-{
- Q_ASSERT(!str.isEmpty());
- QString s = str;
- s[0] = s.at(0).toUpper();
- return s;
-}
-
-static AbstractMetaFunction *createXetter(const AbstractMetaField *g, const QString &name,
- AbstractMetaAttributes::Attributes type)
-{
- auto *f = new AbstractMetaFunction;
-
- f->setName(name);
- f->setOriginalName(name);
- f->setOwnerClass(g->enclosingClass());
- f->setImplementingClass(g->enclosingClass());
- f->setDeclaringClass(g->enclosingClass());
-
- AbstractMetaAttributes::Attributes attr = AbstractMetaAttributes::FinalInTargetLang | type;
- if (g->isStatic())
- attr |= AbstractMetaAttributes::Static;
- if (g->isPublic())
- attr |= AbstractMetaAttributes::Public;
- else if (g->isProtected())
- attr |= AbstractMetaAttributes::Protected;
- else
- attr |= AbstractMetaAttributes::Private;
- f->setAttributes(attr);
- f->setOriginalAttributes(attr);
-
- const FieldModificationList &mods = g->modifications();
- for (const FieldModification &mod : mods) {
- if (mod.isRenameModifier())
- f->setName(mod.renamedTo());
- if (mod.isAccessModifier()) {
- if (mod.isPrivate())
- f->setVisibility(AbstractMetaAttributes::Private);
- else if (mod.isProtected())
- f->setVisibility(AbstractMetaAttributes::Protected);
- else if (mod.isPublic())
- f->setVisibility(AbstractMetaAttributes::Public);
- else if (mod.isFriendly())
- f->setVisibility(AbstractMetaAttributes::Friendly);
- }
- }
- return f;
-}
-
-FieldModificationList AbstractMetaField::modifications() const
-{
- const FieldModificationList &mods = enclosingClass()->typeEntry()->fieldModifications();
- FieldModificationList returned;
-
- for (const FieldModification &mod : mods) {
- if (mod.name == name())
- returned += mod;
- }
-
- return returned;
-}
-
-const AbstractMetaFunction *AbstractMetaField::setter() const
-{
- if (!m_setter) {
- m_setter = createXetter(this,
- QLatin1String("set") + upCaseFirst(name()),
- AbstractMetaAttributes::SetterFunction);
- AbstractMetaArgumentList arguments;
- auto *argument = new AbstractMetaArgument;
- argument->setType(type()->copy());
- argument->setName(name());
- arguments.append(argument);
- m_setter->setArguments(arguments);
- }
- return m_setter;
-}
-
-const AbstractMetaClass *EnclosingClassMixin::targetLangEnclosingClass() const
-{
- auto result = m_enclosingClass;
- while (result && !NamespaceTypeEntry::isVisibleScope(result->typeEntry()))
- result = result->enclosingClass();
- return result;
-}
-
-const AbstractMetaFunction *AbstractMetaField::getter() const
-{
- if (!m_getter) {
- m_getter = createXetter(this,
- name(),
- AbstractMetaAttributes::GetterFunction);
- m_getter->setType(type());
- }
-
- return m_getter;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-static void formatMetaAttributes(QDebug &d, AbstractMetaAttributes::Attributes value)
-{
- static const int meIndex = AbstractMetaAttributes::staticMetaObject.indexOfEnumerator("Attribute");
- Q_ASSERT(meIndex >= 0);
- const QMetaEnum me = AbstractMetaAttributes::staticMetaObject.enumerator(meIndex);
- d << me.valueToKeys(value);
-}
-
-static void formatMetaField(QDebug &d, const AbstractMetaField *af)
-{
- formatMetaAttributes(d, af->attributes());
- d << ' ' << af->type()->name() << " \"" << af->name() << '"';
-}
-
-QDebug operator<<(QDebug d, const AbstractMetaField *af)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaField(";
- if (af)
- formatMetaField(d, af);
- else
- d << '0';
- d << ')';
- return d;
-}
-
-static void formatMetaEnumValue(QDebug &d, const AbstractMetaEnumValue *v)
-{
- const QString &name = v->stringValue();
- if (!name.isEmpty())
- d << name << '=';
- d << v->value();
-}
-
-QDebug operator<<(QDebug d, const AbstractMetaEnumValue *v)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaEnumValue(";
- if (v)
- formatMetaEnumValue(d, v);
- else
- d << '0';
- d << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const AbstractMetaEnum *ae)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaEnum(";
- if (ae) {
- d << ae->fullName();
- if (!ae->isSigned())
- d << " (unsigned) ";
- d << '[';
- const AbstractMetaEnumValueList &values = ae->values();
- for (int i = 0, count = values.size(); i < count; ++i) {
- if (i)
- d << ' ';
- formatMetaEnumValue(d, values.at(i));
- }
- d << ']';
- } else {
- d << '0';
- }
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-bool AbstractMetaClass::hasConstructors() const
-{
- return AbstractMetaClass::queryFirstFunction(m_functions, Constructors) != nullptr;
-}
-
-const AbstractMetaFunction *AbstractMetaClass::copyConstructor() const
-{
- for (const AbstractMetaFunction *f : m_functions) {
- if (f->functionType() == AbstractMetaFunction::CopyConstructorFunction)
- return f;
- }
- return nullptr;
-}
-
-bool AbstractMetaClass::hasPrivateCopyConstructor() const
-{
- const AbstractMetaFunction *copyCt = copyConstructor();
- return copyCt && copyCt->isPrivate();
-}
-
-void AbstractMetaClass::addDefaultConstructor()
-{
- auto *f = new AbstractMetaFunction;
- f->setOriginalName(name());
- f->setName(name());
- f->setOwnerClass(this);
- f->setFunctionType(AbstractMetaFunction::ConstructorFunction);
- f->setArguments(AbstractMetaArgumentList());
- f->setDeclaringClass(this);
-
- f->setAttributes(Public | FinalInTargetLang | AddedMethod);
- f->setImplementingClass(this);
- f->setOriginalAttributes(f->attributes());
-
- addFunction(f);
- this->setHasNonPrivateConstructor(true);
-}
-
-void AbstractMetaClass::addDefaultCopyConstructor(bool isPrivate)
-{
- auto f = new AbstractMetaFunction;
- f->setOriginalName(name());
- f->setName(name());
- f->setOwnerClass(this);
- f->setFunctionType(AbstractMetaFunction::CopyConstructorFunction);
- f->setDeclaringClass(this);
-
- auto argType = new AbstractMetaType;
- argType->setTypeEntry(typeEntry());
- argType->setReferenceType(LValueReference);
- argType->setConstant(true);
- argType->setTypeUsagePattern(AbstractMetaType::ValuePattern);
-
- auto arg = new AbstractMetaArgument;
- arg->setType(argType);
- arg->setName(name());
- f->addArgument(arg);
-
- AbstractMetaAttributes::Attributes attr = FinalInTargetLang | AddedMethod;
- if (isPrivate)
- attr |= AbstractMetaAttributes::Private;
- else
- attr |= AbstractMetaAttributes::Public;
- f->setAttributes(attr);
- f->setImplementingClass(this);
- f->setOriginalAttributes(f->attributes());
-
- addFunction(f);
-}
-
-void AbstractMetaClass::setHasVirtualDestructor(bool value)
-{
- m_hasVirtualDestructor = value;
- if (value)
- m_hasVirtuals = m_isPolymorphic = 1;
-}
-
-bool AbstractMetaClass::hasFunction(const AbstractMetaFunction *f) const
-{
- return functions_contains(m_functions, f);
-}
-
-bool AbstractMetaClass::generateExceptionHandling() const
-{
- return queryFirstFunction(m_functions, AbstractMetaClass::Visible
- | AbstractMetaClass::GenerateExceptionHandling) != nullptr;
-}
-/* Goes through the list of functions and returns a list of all
- functions matching all of the criteria in \a query.
- */
-
-bool AbstractMetaClass::queryFunction(const AbstractMetaFunction *f, FunctionQueryOptions query)
-{
- if ((query & NotRemovedFromTargetLang)
- && f->isRemovedFrom(f->implementingClass(), TypeSystem::TargetLangCode)) {
- return false;
- }
-
- if ((query & NotRemovedFromTargetLang) && f->isVirtual()
- && f->isRemovedFrom(f->declaringClass(), TypeSystem::TargetLangCode)) {
- return false;
- }
-
- if ((query & Visible) && f->isPrivate())
- return false;
-
- if ((query & VirtualInTargetLangFunctions) && f->isFinalInTargetLang())
- return false;
-
- if ((query & Invisible) && !f->isPrivate())
- return false;
-
- if ((query & Empty) && !f->isEmptyFunction())
- return false;
-
- if ((query & WasPublic) && !f->wasPublic())
- return false;
-
- if ((query & ClassImplements) && f->ownerClass() != f->implementingClass())
- return false;
-
- if ((query & FinalInTargetLangFunctions) && !f->isFinalInTargetLang())
- return false;
-
- if ((query & VirtualInCppFunctions) && !f->isVirtual())
- return false;
-
- if ((query & Signals) && (!f->isSignal()))
- return false;
-
- if ((query & Constructors) && (!f->isConstructor() || f->ownerClass() != f->implementingClass()))
- return false;
-
- if (!(query & Constructors) && f->isConstructor())
- return false;
-
- // Destructors are never included in the functions of a class currently
- /*
- if ((query & Destructors) && (!f->isDestructor()
- || f->ownerClass() != f->implementingClass())
- || f->isDestructor() && (query & Destructors) == 0) {
- return false;
- }*/
-
- if ((query & StaticFunctions) && (!f->isStatic() || f->isSignal()))
- return false;
-
- if ((query & NonStaticFunctions) && (f->isStatic()))
- return false;
-
- if ((query & NormalFunctions) && (f->isSignal()))
- return false;
-
- if ((query & OperatorOverloads) && !f->isOperatorOverload())
- return false;
-
- if ((query & GenerateExceptionHandling) && !f->generateExceptionHandling())
- return false;
-
- if (query.testFlag(GetAttroFunction)
- && f->functionType() != AbstractMetaFunction::GetAttroFunction) {
- return false;
- }
-
- if (query.testFlag(SetAttroFunction)
- && f->functionType() != AbstractMetaFunction::SetAttroFunction) {
- return false;
- }
-
- return true;
-}
-
-AbstractMetaFunctionList AbstractMetaClass::queryFunctionList(const AbstractMetaFunctionList &list,
- FunctionQueryOptions query)
-{
- AbstractMetaFunctionList result;
- for (AbstractMetaFunction *f : list) {
- if (queryFunction(f, query))
- result.append(f);
- }
- return result;
-}
-
-const AbstractMetaFunction *AbstractMetaClass::queryFirstFunction(const AbstractMetaFunctionList &list,
- FunctionQueryOptions query)
-{
- AbstractMetaFunctionList result;
- for (AbstractMetaFunction *f : list) {
- if (queryFunction(f, query))
- return f;
- }
- return nullptr;
-}
-
-AbstractMetaFunctionList AbstractMetaClass::queryFunctions(FunctionQueryOptions query) const
-{
- return AbstractMetaClass::queryFunctionList(m_functions, query);
-}
-
-bool AbstractMetaClass::hasSignals() const
-{
- return queryFirstFunction(m_functions, Signals | Visible | NotRemovedFromTargetLang) != nullptr;
-}
-
-AbstractMetaFunctionList AbstractMetaClass::cppSignalFunctions() const
-{
- return queryFunctions(Signals | Visible | NotRemovedFromTargetLang);
-}
-
-AbstractMetaField *AbstractMetaClass::findField(const QString &name) const
-{
- return AbstractMetaField::find(m_fields, name);
-}
-
-AbstractMetaEnum *AbstractMetaClass::findEnum(const QString &enumName)
-{
- if (AbstractMetaEnum *e = findByName(m_enums, enumName))
- return e;
- return nullptr;
-}
-
-/*! Recursively searches for the enum value named \a enumValueName in
- this class and its superclasses and interfaces.
-*/
-AbstractMetaEnumValue *AbstractMetaClass::findEnumValue(const QString &enumValueName)
-{
- for (AbstractMetaEnum *e : qAsConst(m_enums)) {
- if (AbstractMetaEnumValue *v = e->findEnumValue(enumValueName))
- return v;
- }
- if (baseClass())
- return baseClass()->findEnumValue(enumValueName);
-
- return nullptr;
-}
-
-
-static void addExtraIncludeForType(AbstractMetaClass *metaClass, const AbstractMetaType *type)
-{
- if (!type)
- return;
-
- Q_ASSERT(metaClass);
- const TypeEntry *entry = (type ? type->typeEntry() : nullptr);
- if (entry && entry->isComplex()) {
- const auto *centry = static_cast<const ComplexTypeEntry *>(entry);
- ComplexTypeEntry *class_entry = metaClass->typeEntry();
- if (class_entry && centry->include().isValid())
- class_entry->addExtraInclude(centry->include());
- }
-
- if (type->hasInstantiations()) {
- const AbstractMetaTypeList &instantiations = type->instantiations();
- for (const AbstractMetaType *instantiation : instantiations)
- addExtraIncludeForType(metaClass, instantiation);
- }
-}
-
-static void addExtraIncludesForFunction(AbstractMetaClass *metaClass, const AbstractMetaFunction *meta_function)
-{
- Q_ASSERT(metaClass);
- Q_ASSERT(meta_function);
- addExtraIncludeForType(metaClass, meta_function->type());
-
- const AbstractMetaArgumentList &arguments = meta_function->arguments();
- for (AbstractMetaArgument *argument : arguments)
- addExtraIncludeForType(metaClass, argument->type());
-}
-
-void AbstractMetaClass::fixFunctions()
-{
- if (m_functionsFixed)
- return;
-
- m_functionsFixed = true;
-
- AbstractMetaFunctionList funcs = functions();
-
- for (auto superClass : m_baseClasses) {
- superClass->fixFunctions();
- // Since we always traverse the complete hierarchy we are only
- // interrested in what each super class implements, not what
- // we may have propagated from their base classes again.
- AbstractMetaFunctionList superFuncs;
- // Super classes can never be final
- if (superClass->isFinalInTargetLang()) {
- qCWarning(lcShiboken).noquote().nospace()
- << "Final class '" << superClass->name() << "' set to non-final, as it is extended by other classes";
- *superClass -= AbstractMetaAttributes::FinalInTargetLang;
- }
- superFuncs = superClass->queryFunctions(AbstractMetaClass::ClassImplements);
- AbstractMetaFunctionList virtuals = superClass->queryFunctions(AbstractMetaClass::VirtualInCppFunctions);
- superFuncs += virtuals;
-
- QSet<AbstractMetaFunction *> funcsToAdd;
- for (auto sf : qAsConst(superFuncs)) {
- if (sf->isRemovedFromAllLanguages(sf->implementingClass()))
- continue;
-
- // skip functions added in base classes
- if (sf->isUserAdded() && sf->declaringClass() != this)
- continue;
-
- // we generally don't care about private functions, but we have to get the ones that are
- // virtual in case they override abstract functions.
- bool add = (sf->isNormal() || sf->isSignal() || sf->isEmptyFunction());
- for (AbstractMetaFunction *f : funcs) {
- if (f->isRemovedFromAllLanguages(f->implementingClass()))
- continue;
-
-
- const AbstractMetaFunction::CompareResult cmp = f->compareTo(sf);
-
- if (cmp & AbstractMetaFunction::EqualModifiedName) {
- add = false;
- if (cmp & AbstractMetaFunction::EqualArguments) {
- // Same function, propegate virtual...
- if (!(cmp & AbstractMetaFunction::EqualAttributes)) {
- if (!f->isEmptyFunction()) {
- if (!sf->isFinalInTargetLang() && f->isFinalInTargetLang()) {
- *f -= AbstractMetaAttributes::FinalInTargetLang;
- }
-#if 0
- if (!f->isFinalInTargetLang() && f->isPrivate()) {
- f->setFunctionType(AbstractMetaFunction::EmptyFunction);
- f->setVisibility(AbstractMetaAttributes::Protected);
- *f += AbstractMetaAttributes::FinalInTargetLang;
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("private virtual function '%1' in '%2'")
- .arg(f->signature(), f->implementingClass()->name());
- }
-#endif
- }
- }
-
- if (f->visibility() != sf->visibility()) {
- QString warn = QStringLiteral("visibility of function '%1' modified in class '%2'")
- .arg(f->name(), name());
- qCWarning(lcShiboken).noquote().nospace() << warn;
-#if 0
- // If new visibility is private, we can't
- // do anything. If it isn't, then we
- // prefer the parent class's visibility
- // setting for the function.
- if (!f->isPrivate() && !sf->isPrivate())
- f->setVisibility(sf->visibility());
-#endif
- // Private overrides of abstract functions have to go into the class or
- // the subclasses will not compile as non-abstract classes.
- // But they don't need to be implemented, since they can never be called.
- if (f->isPrivate()) {
- f->setFunctionType(AbstractMetaFunction::EmptyFunction);
- *f += AbstractMetaAttributes::FinalInTargetLang;
- }
- }
-
- // Set the class which first declares this function, afawk
- f->setDeclaringClass(sf->declaringClass());
-
- if (sf->isFinalInTargetLang() && !sf->isPrivate() && !f->isPrivate() && !sf->isStatic() && !f->isStatic()) {
- // Shadowed funcion, need to make base class
- // function non-virtual
- if (f->implementingClass() != sf->implementingClass() && f->implementingClass()->inheritsFrom(sf->implementingClass())) {
-
- // Check whether the superclass method has been redefined to non-final
-
- bool hasNonFinalModifier = false;
- bool isBaseImplPrivate = false;
- const FunctionModificationList &mods = sf->modifications(sf->implementingClass());
- for (const FunctionModification &mod : mods) {
- if (mod.isNonFinal()) {
- hasNonFinalModifier = true;
- break;
- }
- if (mod.isPrivate()) {
- isBaseImplPrivate = true;
- break;
- }
- }
-
- if (!hasNonFinalModifier && !isBaseImplPrivate) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("Shadowing: %1::%2 and %3::%4")
- .arg(sf->implementingClass()->name(), sf->signature(),
- f->implementingClass()->name(), f->signature());
- }
- }
- }
-
- }
-
- if (cmp & AbstractMetaFunction::EqualDefaultValueOverload) {
- AbstractMetaArgumentList arguments;
- if (f->arguments().size() < sf->arguments().size())
- arguments = sf->arguments();
- else
- arguments = f->arguments();
- //TODO: fix this
- //for (int i=0; i<arguments.size(); ++i)
- // arguments[i]->setDefaultValueExpression("<#>" + QString());
- }
-
-
- // Otherwise we have function shadowing and we can
- // skip the thing...
- } else if (cmp & AbstractMetaFunction::EqualName && !sf->isSignal()) {
- // In the case of function shadowing where the function name has been altered to
- // avoid conflict, we don't copy in the original.
- add = false;
- }
- }
-
- if (add)
- funcsToAdd << sf;
- }
-
- for (AbstractMetaFunction *f : qAsConst(funcsToAdd)) {
- AbstractMetaFunction *copy = f->copy();
- (*copy) += AddedMethod;
- funcs.append(copy);
- }
- }
-
- bool hasPrivateConstructors = false;
- bool hasPublicConstructors = false;
- for (AbstractMetaFunction *func : qAsConst(funcs)) {
- const FunctionModificationList &mods = func->modifications(this);
- for (const FunctionModification &mod : mods) {
- if (mod.isRenameModifier()) {
- func->setName(mod.renamedTo());
- }
- }
-
- // Make sure class is abstract if one of the functions is
- if (func->isAbstract()) {
- (*this) += AbstractMetaAttributes::Abstract;
- (*this) -= AbstractMetaAttributes::FinalInTargetLang;
- }
-
- if (func->isConstructor()) {
- if (func->isPrivate())
- hasPrivateConstructors = true;
- else
- hasPublicConstructors = true;
- }
-
-
-
- // Make sure that we include files for all classes that are in use
-
- if (!func->isRemovedFrom(this, TypeSystem::ShellCode))
- addExtraIncludesForFunction(this, func);
- }
-
- if (hasPrivateConstructors && !hasPublicConstructors) {
- (*this) += AbstractMetaAttributes::Abstract;
- (*this) -= AbstractMetaAttributes::FinalInTargetLang;
- }
-
- setFunctions(funcs);
-}
-
-static inline QString formatArraySize(int e)
-{
- QString result;
- result += QLatin1Char('[');
- if (e >= 0)
- result += QString::number(e);
- result += QLatin1Char(']');
- return result;
-}
-
-QString AbstractMetaType::formatSignature(bool minimal) const
-{
- QString result;
- if (isConstant())
- result += QLatin1String("const ");
- if (isVolatile())
- result += QLatin1String("volatile ");
- if (isArray()) {
- // Build nested array dimensions a[2][3] in correct order
- result += m_arrayElementType->minimalSignature();
- const int arrayPos = result.indexOf(QLatin1Char('['));
- if (arrayPos != -1)
- result.insert(arrayPos, formatArraySize(m_arrayElementCount));
- else
- result.append(formatArraySize(m_arrayElementCount));
- } else {
- result += typeEntry()->qualifiedCppName();
- }
- if (!m_instantiations.isEmpty()) {
- result += QLatin1Char('<');
- if (minimal)
- result += QLatin1Char(' ');
- for (int i = 0, size = m_instantiations.size(); i < size; ++i) {
- if (i > 0)
- result += QLatin1Char(',');
- result += m_instantiations.at(i)->minimalSignature();
- }
- result += QLatin1String(" >");
- }
-
- if (!minimal && (!m_indirections.isEmpty() || m_referenceType != NoReference))
- result += QLatin1Char(' ');
- for (Indirection i : m_indirections)
- result += TypeInfo::indirectionKeyword(i);
- switch (referenceType()) {
- case NoReference:
- break;
- case LValueReference:
- result += QLatin1Char('&');
- break;
- case RValueReference:
- result += QLatin1String("&&");
- break;
- }
- return result;
-}
-
-QString AbstractMetaType::formatPythonSignature() const
-{
- /*
- * This is a version of the above, more suitable for Python.
- * We avoid extra keywords that are not needed in Python.
- * We prepend the package name, unless it is a primitive type.
- *
- * Primitive types like 'int', 'char' etc.:
- * When we have a primitive with an indirection, we use that '*'
- * character for later postprocessing, since those indirections
- * need to be modified into a result tuple.
- */
- QString result;
- if (m_pattern == AbstractMetaType::NativePointerAsArrayPattern)
- result += QLatin1String("array ");
- // We no longer use the "const" qualifier for heuristics. Instead,
- // NativePointerAsArrayPattern indicates when we have <array> in XML.
- // if (m_typeEntry->isPrimitive() && isConstant())
- // result += QLatin1String("const ");
- if (!m_typeEntry->isPrimitive() && !package().isEmpty())
- result += package() + QLatin1Char('.');
- if (isArray()) {
- // Build nested array dimensions a[2][3] in correct order
- result += m_arrayElementType->formatPythonSignature();
- const int arrayPos = result.indexOf(QLatin1Char('['));
- if (arrayPos != -1)
- result.insert(arrayPos, formatArraySize(m_arrayElementCount));
- else
- result.append(formatArraySize(m_arrayElementCount));
- } else {
- result += typeEntry()->targetLangName();
- }
- if (!m_instantiations.isEmpty()) {
- result += QLatin1Char('[');
- for (int i = 0, size = m_instantiations.size(); i < size; ++i) {
- if (i > 0)
- result += QLatin1String(", ");
- result += m_instantiations.at(i)->formatPythonSignature();
- }
- result += QLatin1Char(']');
- }
- if (m_typeEntry->isPrimitive())
- for (Indirection i : m_indirections)
- result += TypeInfo::indirectionKeyword(i);
- // If it is a flags type, we replace it with the full name:
- // "PySide2.QtCore.Qt.ItemFlags" instead of "PySide2.QtCore.QFlags<Qt.ItemFlag>"
- if (m_typeEntry->isFlags())
- result = fullName();
- result.replace(QLatin1String("::"), QLatin1String("."));
- return result;
-}
-
-bool AbstractMetaType::isCppPrimitive() const
-{
- return m_pattern == PrimitivePattern && m_typeEntry->isCppPrimitive();
-}
-
-/*******************************************************************************
- * Other stuff...
- */
-
-
-AbstractMetaEnum *AbstractMetaClass::findEnum(const AbstractMetaClassList &classes,
- const EnumTypeEntry *entry)
-{
- Q_ASSERT(entry->isEnum());
-
- QString qualifiedName = entry->qualifiedCppName();
- int pos = qualifiedName.lastIndexOf(QLatin1String("::"));
-
- QString enumName;
- QString className;
-
- if (pos > 0) {
- enumName = qualifiedName.mid(pos + 2);
- className = qualifiedName.mid(0, pos);
- } else {
- enumName = qualifiedName;
- className = TypeDatabase::globalNamespaceClassName(entry);
- }
-
- AbstractMetaClass *metaClass = AbstractMetaClass::findClass(classes, className);
- if (!metaClass) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("AbstractMeta::findEnum(), unknown class '%1' in '%2'")
- .arg(className, entry->qualifiedCppName());
- return nullptr;
- }
-
- return metaClass->findEnum(enumName);
-}
-
-AbstractMetaEnumValue *AbstractMetaClass::findEnumValue(const AbstractMetaClassList &classes,
- const QString &name)
-{
- const QVector<QStringRef> lst = name.splitRef(QLatin1String("::"));
-
- if (lst.size() > 1) {
- const QStringRef &prefixName = lst.at(0);
- const QStringRef &enumName = lst.at(1);
- if (AbstractMetaClass *cl = findClass(classes, prefixName.toString()))
- return cl->findEnumValue(enumName.toString());
- }
-
- for (AbstractMetaClass *metaClass : classes) {
- if (AbstractMetaEnumValue *enumValue = metaClass->findEnumValue(name))
- return enumValue;
- }
-
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("no matching enum '%1'").arg(name);
- return nullptr;
-}
-
-/*!
- * Searches the list after a class that mathces \a name; either as
- * C++, Target language base name or complete Target language package.class name.
- */
-
-AbstractMetaClass *AbstractMetaClass::findClass(const AbstractMetaClassList &classes,
- const QString &name)
-{
- if (name.isEmpty())
- return nullptr;
-
- for (AbstractMetaClass *c : classes) {
- if (c->qualifiedCppName() == name)
- return c;
- }
-
- for (AbstractMetaClass *c : classes) {
- if (c->fullName() == name)
- return c;
- }
-
- for (AbstractMetaClass *c : classes) {
- if (c->name() == name)
- return c;
- }
-
- return nullptr;
-}
-
-AbstractMetaClass *AbstractMetaClass::findClass(const AbstractMetaClassList &classes,
- const TypeEntry *typeEntry)
-{
- for (AbstractMetaClass *c : classes) {
- if (c->typeEntry() == typeEntry)
- return c;
- }
- return nullptr;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-
-void AbstractMetaClass::format(QDebug &d) const
-{
- if (d.verbosity() > 2)
- d << static_cast<const void *>(this) << ", ";
- d << '"' << qualifiedCppName();
- if (const int count = m_templateArgs.size()) {
- for (int i = 0; i < count; ++i)
- d << (i ? ',' : '<') << m_templateArgs.at(i)->qualifiedCppName();
- d << '>';
- }
- d << '"';
- if (isNamespace())
- d << " [namespace]";
- if (attributes() & AbstractMetaAttributes::FinalCppClass)
- d << " [final]";
- if (attributes().testFlag(AbstractMetaAttributes::Deprecated))
- d << " [deprecated]";
- if (!m_baseClasses.isEmpty()) {
- d << ", inherits ";
- for (auto b : m_baseClasses)
- d << " \"" << b->name() << '"';
- }
- if (auto templateBase = templateBaseClass()) {
- const auto instantiatedTypes = templateBaseClassInstantiations();
- d << ", instantiates \"" << templateBase->name();
- for (int i = 0, count = instantiatedTypes.size(); i < count; ++i)
- d << (i ? ',' : '<') << instantiatedTypes.at(i)->name();
- d << ">\"";
- }
-}
-
-void AbstractMetaClass::formatMembers(QDebug &d) const
-{
- if (!m_enums.isEmpty())
- d << ", enums[" << m_enums.size() << "]=" << m_enums;
- if (!m_functions.isEmpty()) {
- const int count = m_functions.size();
- d << ", functions=[" << count << "](";
- for (int i = 0; i < count; ++i) {
- if (i)
- d << ", ";
- formatMetaFunctionBrief(d, m_functions.at(i));
- }
- d << ')';
- }
- if (const int count = m_fields.size()) {
- d << ", fields=[" << count << "](";
- for (int i = 0; i < count; ++i) {
- if (i)
- d << ", ";
- formatMetaField(d, m_fields.at(i));
- }
- d << ')';
- }
-}
-
-QDebug operator<<(QDebug d, const AbstractMetaClass *ac)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AbstractMetaClass(";
- if (ac) {
- ac->format(d);
- if (d.verbosity() > 2)
- ac->formatMembers(d);
- } else {
- d << '0';
- }
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-/*******************************************************************************
-* AbstractMetaEnum
-*/
-
-AbstractMetaEnum::AbstractMetaEnum() :
- m_hasQenumsDeclaration(false), m_signed(true)
-{
-}
-
-AbstractMetaEnum::~AbstractMetaEnum()
-{
- qDeleteAll(m_enumValues);
-}
-
-template <class String>
-AbstractMetaEnumValue *findMatchingEnumValue(const AbstractMetaEnumValueList &list, const String &value)
-{
- for (AbstractMetaEnumValue *enumValue : list) {
- if (enumValue->name() == value)
- return enumValue;
- }
- return nullptr;
-}
-
-// Find enum values for "enum Enum { e1 }" either for "e1" or "Enum::e1"
-AbstractMetaEnumValue *AbstractMetaEnum::findEnumValue(const QString &value) const
-{
- if (isAnonymous())
- return findMatchingEnumValue(m_enumValues, value);
- const int sepPos = value.indexOf(QLatin1String("::"));
- if (sepPos == -1)
- return findMatchingEnumValue(m_enumValues, value);
- return name() == value.leftRef(sepPos)
- ? findMatchingEnumValue(m_enumValues, value.rightRef(value.size() - sepPos - 2))
- : nullptr;
-}
-
-QString AbstractMetaEnum::name() const
-{
- return m_typeEntry->targetLangEntryName();
-}
-
-QString AbstractMetaEnum::qualifier() const
-{
- return m_typeEntry->targetLangQualifier();
-}
-
-QString AbstractMetaEnum::package() const
-{
- return m_typeEntry->targetLangPackage();
-}
diff --git a/sources/shiboken2/ApiExtractor/abstractmetalang.h b/sources/shiboken2/ApiExtractor/abstractmetalang.h
deleted file mode 100644
index 00f137100..000000000
--- a/sources/shiboken2/ApiExtractor/abstractmetalang.h
+++ /dev/null
@@ -1,1811 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ABSTRACTMETALANG_H
-#define ABSTRACTMETALANG_H
-
-#include "abstractmetalang_typedefs.h"
-#include "typesystem_enums.h"
-#include "typesystem_typedefs.h"
-
-#include "parser/codemodel_enums.h"
-#include "parser/enumvalue.h"
-
-#include <QtCore/qobjectdefs.h>
-#include <QtCore/QStringList>
-
-QT_FORWARD_DECLARE_CLASS(QDebug)
-
-class AbstractMeta;
-class AbstractMetaClass;
-class AbstractMetaField;
-class AbstractMetaFunction;
-class AbstractMetaType;
-class AbstractMetaVariable;
-class AbstractMetaArgument;
-class AbstractMetaEnumValue;
-class AbstractMetaEnum;
-class QPropertySpec;
-
-class CodeSnip;
-class ComplexTypeEntry;
-class EnumTypeEntry;
-class FlagsTypeEntry;
-class FunctionTypeEntry;
-class TypeEntry;
-
-struct ArgumentOwner;
-struct FieldModification;
-struct FunctionModification;
-struct ReferenceCount;
-
-class Documentation
-{
-public:
- enum Format {
- Native,
- Target
- };
-
- Documentation() = default;
-
- Documentation(const QString& value, Format fmt = Documentation::Native)
- : m_data(value.trimmed()), m_format(fmt) {}
-
- bool isEmpty() const { return m_data.isEmpty(); }
-
- QString value() const
- {
- return m_data;
- }
-
- void setValue(const QString& value, Format fmt = Documentation::Native)
- {
- m_data = value.trimmed();
- m_format = fmt;
- }
-
- Documentation::Format format() const
- {
- return m_format;
- }
-
- void setFormat(Format f) { m_format = f; }
-
-private:
- QString m_data;
- Format m_format = Documentation::Native;
-
-};
-
-class AbstractMetaAttributes
-{
- Q_GADGET
-public:
- Q_DISABLE_COPY(AbstractMetaAttributes)
-
- AbstractMetaAttributes();
- virtual ~AbstractMetaAttributes();
-
- enum Attribute {
- None = 0x00000000,
-
- Private = 0x00000001,
- Protected = 0x00000002,
- Public = 0x00000004,
- Friendly = 0x00000008,
- Visibility = 0x0000000f,
-
- Abstract = 0x00000020,
- Static = 0x00000040,
-
- FinalInTargetLang = 0x00000080,
-
- GetterFunction = 0x00000400,
- SetterFunction = 0x00000800,
-
- PropertyReader = 0x00004000,
- PropertyWriter = 0x00008000,
- PropertyResetter = 0x00010000,
-
- Invokable = 0x00040000,
-
- HasRejectedConstructor = 0x00080000,
- HasRejectedDefaultConstructor = 0x00100000,
-
- FinalCppClass = 0x00200000,
- VirtualCppMethod = 0x00400000,
- OverriddenCppMethod = 0x00800000,
- FinalCppMethod = 0x01000000,
- // Add by meta builder (implicit constructors, inherited methods, etc)
- AddedMethod = 0x02000000,
- Deprecated = 0x04000000
- };
- Q_DECLARE_FLAGS(Attributes, Attribute)
- Q_FLAG(Attribute)
-
- Attributes attributes() const
- {
- return m_attributes;
- }
-
- void setAttributes(Attributes attributes)
- {
- m_attributes = attributes;
- }
-
- Attributes originalAttributes() const
- {
- return m_originalAttributes;
- }
-
- void setOriginalAttributes(Attributes attributes)
- {
- m_originalAttributes = attributes;
- }
-
- Attributes visibility() const
- {
- return m_attributes & Visibility;
- }
-
- void setVisibility(Attributes visi)
- {
- m_attributes = (m_attributes & ~Visibility) | visi;
- }
-
- void operator+=(Attribute attribute)
- {
- m_attributes |= attribute;
- }
-
- void operator-=(Attribute attribute)
- {
- m_attributes &= ~attribute;
- }
-
- bool isFinalInTargetLang() const
- {
- return m_attributes & FinalInTargetLang;
- }
-
- bool isAbstract() const
- {
- return m_attributes & Abstract;
- }
-
- bool isStatic() const
- {
- return m_attributes & Static;
- }
-
- bool isInvokable() const
- {
- return m_attributes & Invokable;
- }
-
- bool isPropertyReader() const
- {
- return m_attributes & PropertyReader;
- }
-
- bool isPropertyWriter() const
- {
- return m_attributes & PropertyWriter;
- }
-
- bool isPropertyResetter() const
- {
- return m_attributes & PropertyResetter;
- }
-
- bool isPrivate() const
- {
- return m_attributes & Private;
- }
-
- bool isProtected() const
- {
- return m_attributes & Protected;
- }
-
- bool isPublic() const
- {
- return m_attributes & Public;
- }
-
- bool isFriendly() const
- {
- return m_attributes & Friendly;
- }
-
- bool wasPrivate() const
- {
- return m_originalAttributes & Private;
- }
-
- bool wasPublic() const
- {
- return m_originalAttributes & Public;
- }
-
- void setDocumentation(const Documentation& doc)
- {
- m_doc = doc;
- }
-
- Documentation documentation() const
- {
- return m_doc;
- }
-
-protected:
- void assignMetaAttributes(const AbstractMetaAttributes &other);
-
-private:
- Attributes m_attributes;
- Attributes m_originalAttributes;
- Documentation m_doc;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(AbstractMetaAttributes::Attributes)
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaAttributes *aa);
-#endif
-
-class AbstractMetaType
-{
- Q_GADGET
-public:
- using Indirections = QVector<Indirection>;
-
- enum TypeUsagePattern {
- InvalidPattern,
- PrimitivePattern,
- FlagsPattern,
- EnumPattern,
- ValuePattern,
- ObjectPattern,
- ValuePointerPattern,
- NativePointerPattern,
- NativePointerAsArrayPattern, // "int*" as "int[]"
- ContainerPattern,
- SmartPointerPattern,
- VarargsPattern,
- ArrayPattern
- };
- Q_ENUM(TypeUsagePattern)
-
- enum ComparisonFlag {
- ConstRefMatchesValue = 0x1
- };
- Q_DECLARE_FLAGS(ComparisonFlags, ComparisonFlag);
-
- AbstractMetaType();
- ~AbstractMetaType();
-
- QString package() const;
- QString name() const;
- QString fullName() const;
-
- void setTypeUsagePattern(TypeUsagePattern pattern)
- {
- m_pattern = pattern;
- }
- TypeUsagePattern typeUsagePattern() const
- {
- return m_pattern;
- }
-
- // true when use pattern is container
- bool hasInstantiations() const
- {
- return !m_instantiations.isEmpty();
- }
-
- void addInstantiation(AbstractMetaType* inst, bool owner = false)
- {
- if (owner)
- m_children << inst;
- m_instantiations << inst;
- }
-
- void setInstantiations(const AbstractMetaTypeList &insts, bool owner = false)
- {
- m_instantiations = insts;
- if (owner) {
- m_children.clear();
- m_children = insts;
- }
- }
-
- AbstractMetaTypeList instantiations() const
- {
- return m_instantiations;
- }
-
- void setInstantiationInCpp(bool incpp)
- {
- m_cppInstantiation = incpp;
- }
-
- QString minimalSignature() const { return formatSignature(true); }
-
- // returns true if the typs is used as a non complex primitive, no & or *'s
- bool isPrimitive() const
- {
- return m_pattern == PrimitivePattern;
- }
-
- bool isCppPrimitive() const;
-
- // returns true if the type is used as an enum
- bool isEnum() const
- {
- return m_pattern == EnumPattern;
- }
-
- // returns true if the type is used as an object, e.g. Xxx *
- bool isObject() const
- {
- return m_pattern == ObjectPattern;
- }
-
- // returns true if the type is used as an array, e.g. Xxx[42]
- bool isArray() const
- {
- return m_pattern == ArrayPattern;
- }
-
- // returns true if the type is used as a value type (X or const X &)
- bool isValue() const
- {
- return m_pattern == ValuePattern;
- }
-
- bool isValuePointer() const
- {
- return m_pattern == ValuePointerPattern;
- }
-
- // returns true for more complex types...
- bool isNativePointer() const
- {
- return m_pattern == NativePointerPattern;
- }
-
- // return true if the type was originally a varargs
- bool isVarargs() const
- {
- return m_pattern == VarargsPattern;
- }
-
- // returns true if the type was used as a container
- bool isContainer() const
- {
- return m_pattern == ContainerPattern;
- }
-
- // returns true if the type was used as a smart pointer
- bool isSmartPointer() const { return m_pattern == SmartPointerPattern; }
-
- // returns true if the type was used as a flag
- bool isFlags() const
- {
- return m_pattern == FlagsPattern;
- }
-
- bool isConstant() const
- {
- return m_constant;
- }
- void setConstant(bool constant)
- {
- m_constant = constant;
- }
-
- bool isVolatile() const { return m_volatile; }
- void setVolatile(bool v) { m_volatile = v; }
-
- bool passByConstRef() const;
- bool passByValue() const;
-
- ReferenceType referenceType() const { return m_referenceType; }
- void setReferenceType(ReferenceType ref) { m_referenceType = ref; }
-
- int actualIndirections() const
- {
- return m_indirections.size() + (m_referenceType == LValueReference ? 1 : 0);
- }
-
- Indirections indirectionsV() const { return m_indirections; }
- void setIndirectionsV(const Indirections &i) { m_indirections = i; }
- void clearIndirections() { m_indirections.clear(); }
-
- // "Legacy"?
- int indirections() const { return m_indirections.size(); }
- void setIndirections(int indirections)
- {
- m_indirections = Indirections(indirections, Indirection::Pointer);
- }
- void addIndirection(Indirection i = Indirection::Pointer)
- { m_indirections.append(i); }
-
- void setArrayElementCount(int n)
- {
- m_arrayElementCount = n;
- }
- int arrayElementCount() const
- {
- return m_arrayElementCount;
- }
-
- const AbstractMetaType *arrayElementType() const
- {
- return m_arrayElementType;
- }
- void setArrayElementType(const AbstractMetaType *t)
- {
- m_arrayElementType = t;
- }
-
- AbstractMetaTypeCList nestedArrayTypes() const;
-
- QString cppSignature() const;
-
- QString pythonSignature() const;
-
- AbstractMetaType *copy() const;
- bool applyArrayModification(QString *errorMessage);
-
- const TypeEntry *typeEntry() const
- {
- return m_typeEntry;
- }
- void setTypeEntry(const TypeEntry *type)
- {
- m_typeEntry = type;
- }
-
- void setOriginalTypeDescription(const QString &otd)
- {
- m_originalTypeDescription = otd;
- }
- QString originalTypeDescription() const
- {
- return m_originalTypeDescription;
- }
-
- void setOriginalTemplateType(const AbstractMetaType *type)
- {
- m_originalTemplateType = type;
- }
- const AbstractMetaType *originalTemplateType() const
- {
- return m_originalTemplateType;
- }
-
- AbstractMetaType *getSmartPointerInnerType() const
- {
- Q_ASSERT(isSmartPointer());
- AbstractMetaTypeList instantiations = this->instantiations();
- Q_ASSERT(!instantiations.isEmpty());
- AbstractMetaType *innerType = instantiations.at(0);
- return innerType;
- }
-
- QString getSmartPointerInnerTypeName() const
- {
- Q_ASSERT(isSmartPointer());
- AbstractMetaType *innerType = getSmartPointerInnerType();
- Q_ASSERT(innerType);
- return innerType->name();
- }
-
- /// Decides and sets the proper usage patter for the current meta type.
- void decideUsagePattern();
-
- bool hasTemplateChildren() const;
-
- bool compare(const AbstractMetaType &rhs, ComparisonFlags = {}) const;
-
-private:
- TypeUsagePattern determineUsagePattern() const;
- QString formatSignature(bool minimal) const;
- QString formatPythonSignature() const;
-
- const TypeEntry *m_typeEntry = nullptr;
- AbstractMetaTypeList m_instantiations;
- QString m_package;
- mutable QString m_cachedCppSignature;
- mutable QString m_cachedPythonSignature;
- QString m_originalTypeDescription;
-
- int m_arrayElementCount = -1;
- const AbstractMetaType *m_arrayElementType = nullptr;
- const AbstractMetaType *m_originalTemplateType = nullptr;
- Indirections m_indirections;
-
- TypeUsagePattern m_pattern = InvalidPattern;
- uint m_constant : 1;
- uint m_volatile : 1;
- uint m_cppInstantiation : 1;
- uint m_reserved : 29; // unused
-
- ReferenceType m_referenceType = NoReference;
- AbstractMetaTypeList m_children;
-
- Q_DISABLE_COPY(AbstractMetaType)
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(AbstractMetaType::ComparisonFlags);
-
-inline bool operator==(const AbstractMetaType &t1, const AbstractMetaType &t2)
-{ return t1.compare(t2); }
-inline bool operator!=(const AbstractMetaType &t1, const AbstractMetaType &t2)
-{ return !t1.compare(t2); }
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaType *at);
-#endif
-
-class AbstractMetaVariable
-{
- Q_DISABLE_COPY(AbstractMetaVariable)
-public:
- AbstractMetaVariable();
-
- virtual ~AbstractMetaVariable();
-
- AbstractMetaType *type() const
- {
- return m_type;
- }
- void setType(AbstractMetaType *type)
- {
- Q_ASSERT(m_type == nullptr);
- m_type = type;
- }
- void replaceType(AbstractMetaType *type)
- {
- delete m_type;
- m_type = type;
- }
-
- QString name() const
- {
- return m_name;
- }
- void setName(const QString &name, bool realName = true)
- {
- m_name = name;
- m_hasName = realName;
- }
- bool hasName() const
- {
- return m_hasName;
- }
- QString originalName() const
- {
- return m_originalName;
- }
- void setOriginalName(const QString& name)
- {
- m_originalName = name;
- }
- void setDocumentation(const Documentation& doc)
- {
- m_doc = doc;
- }
- Documentation documentation() const
- {
- return m_doc;
- }
-
-protected:
- void assignMetaVariable(const AbstractMetaVariable &other);
-
-private:
- QString m_originalName;
- QString m_name;
- AbstractMetaType *m_type = nullptr;
- bool m_hasName = false;
-
- Documentation m_doc;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaVariable *av);
-#endif
-
-class AbstractMetaArgument : public AbstractMetaVariable
-{
-public:
- AbstractMetaArgument();
-
- QString defaultValueExpression() const
- {
- return m_expression;
- }
- void setDefaultValueExpression(const QString &expr)
- {
- m_expression = expr;
- }
-
- QString originalDefaultValueExpression() const
- {
- return m_originalExpression;
- }
- void setOriginalDefaultValueExpression(const QString &expr)
- {
- m_originalExpression = expr;
- }
-
- bool hasDefaultValueExpression() const
- { return !m_expression.isEmpty(); }
- bool hasOriginalDefaultValueExpression() const
- { return !m_originalExpression.isEmpty(); }
- bool hasUnmodifiedDefaultValueExpression() const
- { return !m_originalExpression.isEmpty() && m_originalExpression == m_expression; }
- bool hasModifiedDefaultValueExpression() const
- { return !m_expression.isEmpty() && m_originalExpression != m_expression; }
-
- QString toString() const
- {
- return type()->name() + QLatin1Char(' ') + AbstractMetaVariable::name() +
- (m_expression.isEmpty() ? QString() : QLatin1String(" = ") + m_expression);
- }
-
- int argumentIndex() const
- {
- return m_argumentIndex;
- }
- void setArgumentIndex(int argIndex)
- {
- m_argumentIndex = argIndex;
- }
-
- AbstractMetaArgument *copy() const;
-
-protected:
- void assignMetaArgument(const AbstractMetaArgument &other);
-
-private:
- QString m_expression;
- QString m_originalExpression;
- int m_argumentIndex = 0;
-
- friend class AbstractMetaClass;
-};
-
-class EnclosingClassMixin {
-public:
- const AbstractMetaClass *enclosingClass() const { return m_enclosingClass; }
- void setEnclosingClass(const AbstractMetaClass *cls) { m_enclosingClass = cls; }
- const AbstractMetaClass *targetLangEnclosingClass() const;
-
-private:
- const AbstractMetaClass *m_enclosingClass = nullptr;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaArgument *aa);
-#endif
-
-class AbstractMetaField : public AbstractMetaVariable, public AbstractMetaAttributes, public EnclosingClassMixin
-{
-public:
- AbstractMetaField();
- ~AbstractMetaField();
-
- const AbstractMetaFunction *getter() const;
- const AbstractMetaFunction *setter() const;
-
- FieldModificationList modifications() const;
-
- bool isModifiedRemoved(int types = TypeSystem::All) const;
-
- using AbstractMetaVariable::setDocumentation;
- using AbstractMetaVariable::documentation;
-
- AbstractMetaField *copy() const;
-
- static AbstractMetaField *
- find(const AbstractMetaFieldList &haystack, const QString &needle);
-
-private:
- mutable AbstractMetaFunction *m_getter = nullptr;
- mutable AbstractMetaFunction *m_setter = nullptr;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaField *af);
-#endif
-
-class AbstractMetaFunction : public AbstractMetaAttributes
-{
- Q_GADGET
-public:
- enum FunctionType {
- ConstructorFunction,
- CopyConstructorFunction,
- MoveConstructorFunction,
- AssignmentOperatorFunction,
- MoveAssignmentOperatorFunction,
- DestructorFunction,
- NormalFunction,
- SignalFunction,
- EmptyFunction,
- SlotFunction,
- GlobalScopeFunction,
- GetAttroFunction,
- SetAttroFunction
- };
- Q_ENUM(FunctionType)
-
- enum CompareResultFlag {
- EqualName = 0x00000001,
- EqualArguments = 0x00000002,
- EqualAttributes = 0x00000004,
- EqualImplementor = 0x00000008,
- EqualReturnType = 0x00000010,
- EqualDefaultValueOverload = 0x00000020,
- EqualModifiedName = 0x00000040,
-
- NameLessThan = 0x00001000,
-
- PrettySimilar = EqualName | EqualArguments,
- Equal = 0x0000001f,
- NotEqual = 0x00001000
- };
- Q_DECLARE_FLAGS(CompareResult, CompareResultFlag)
- Q_FLAG(CompareResultFlag)
-
- AbstractMetaFunction();
- explicit AbstractMetaFunction(const AddedFunctionPtr &addedFunc);
- ~AbstractMetaFunction();
-
- QString name() const
- {
- return m_name;
- }
-
- void setName(const QString &name)
- {
- m_name = name;
- }
-
- QString originalName() const
- {
- return m_originalName.isEmpty() ? name() : m_originalName;
- }
-
- void setOriginalName(const QString &name)
- {
- m_originalName = name;
- }
-
- void setReverseOperator(bool reverse)
- {
- m_reverse = reverse;
- }
-
- bool isReverseOperator() const
- {
- return m_reverse;
- }
-
- /**
- * Returns true if this is a operator and the "self" operand is a pointer.
- * e.g. class Foo {}; operator+(SomeEnum, Foo*);
- */
- bool isPointerOperator() const
- {
- return m_pointerOperator;
- }
-
- void setPointerOperator(bool value)
- {
- m_pointerOperator = value;
- }
-
- void setExplicit(bool isExplicit)
- {
- m_explicit = isExplicit;
- }
- /**
- * Says if the function (a constructor) was declared as explicit in C++.
- * \return true if the function was declared as explicit in C++
- */
- bool isExplicit() const
- {
- return m_explicit;
- }
-
- static bool isConversionOperator(const QString& funcName);
-
- ExceptionSpecification exceptionSpecification() const;
- void setExceptionSpecification(ExceptionSpecification e);
-
- bool generateExceptionHandling() const;
-
- bool isConversionOperator() const
- {
- return isConversionOperator(originalName());
- }
-
- static bool isOperatorOverload(const QString& funcName);
- bool isOperatorOverload() const
- {
- return isOperatorOverload(originalName());
- }
- bool isCastOperator() const;
-
- bool isArithmeticOperator() const;
- bool isBitwiseOperator() const;
- bool isComparisonOperator() const;
- bool isLogicalOperator() const;
- bool isSubscriptOperator() const;
- bool isAssignmentOperator() const; // Assignment or move assignment
- bool isOtherOperator() const;
-
- /**
- * Informs the arity of the operator or -1 if the function is not
- * an operator overload.
- * /return the arity of the operator or -1
- */
- int arityOfOperator() const;
- bool isUnaryOperator() const { return arityOfOperator() == 1; }
- bool isBinaryOperator() const { return arityOfOperator() == 2; }
- bool isInplaceOperator() const;
-
- bool isVirtual() const;
- bool allowThread() const;
- QString modifiedName() const;
-
- QString minimalSignature() const;
- QString debugSignature() const; // including virtual/override/final, etc., for debugging only.
-
- bool isModifiedRemoved(int types = TypeSystem::All) const;
-
- AbstractMetaType *type() const
- {
- return m_type;
- }
- void setType(AbstractMetaType *type)
- {
- Q_ASSERT(m_type == nullptr);
- m_type = type;
- }
-
- void replaceType(AbstractMetaType *type)
- {
- delete m_type;
- m_type = type;
- }
-
- // The class that has this function as a member.
- const AbstractMetaClass *ownerClass() const
- {
- return m_class;
- }
- void setOwnerClass(const AbstractMetaClass *cls)
- {
- m_class = cls;
- }
-
- // The first class in a hierarchy that declares the function
- const AbstractMetaClass *declaringClass() const
- {
- return m_declaringClass;
- }
- void setDeclaringClass(const AbstractMetaClass *cls)
- {
- m_declaringClass = cls;
- }
-
- // The class that actually implements this function
- const AbstractMetaClass *implementingClass() const
- {
- return m_implementingClass;
- }
- void setImplementingClass(const AbstractMetaClass *cls)
- {
- m_implementingClass = cls;
- }
-
- AbstractMetaArgumentList arguments() const
- {
- return m_arguments;
- }
- void setArguments(const AbstractMetaArgumentList &arguments)
- {
- m_arguments = arguments;
- }
- void addArgument(AbstractMetaArgument *argument)
- {
- m_arguments << argument;
- }
- int actualMinimumArgumentCount() const;
-
- bool isDeprecated() const;
- bool isDestructor() const
- {
- return functionType() == DestructorFunction;
- }
- bool isConstructor() const
- {
- return m_functionType == ConstructorFunction || m_functionType == CopyConstructorFunction
- || m_functionType == MoveConstructorFunction;
- }
- bool isNormal() const
- {
- return functionType() == NormalFunction || isSlot() || isInGlobalScope();
- }
- bool isInGlobalScope() const
- {
- return functionType() == GlobalScopeFunction;
- }
- bool isSignal() const
- {
- return functionType() == SignalFunction;
- }
- bool isSlot() const
- {
- return functionType() == SlotFunction;
- }
- bool isEmptyFunction() const
- {
- return functionType() == EmptyFunction;
- }
- FunctionType functionType() const
- {
- return m_functionType;
- }
- void setFunctionType(FunctionType type)
- {
- m_functionType = type;
- }
-
- bool usesRValueReferences() const;
- QStringList introspectionCompatibleSignatures(const QStringList &resolvedArguments = QStringList()) const;
- QString signature() const;
-
- bool isConstant() const
- {
- return m_constant;
- }
- void setConstant(bool constant)
- {
- m_constant = constant;
- }
-
- /// Returns true if the AbstractMetaFunction was added by the user via the type system description.
- bool isUserAdded() const { return !m_addedFunction.isNull(); }
-
- QString toString() const
- {
- return m_name;
- }
-
- CompareResult compareTo(const AbstractMetaFunction *other) const;
-
- bool operator <(const AbstractMetaFunction &a) const;
-
- AbstractMetaFunction *copy() const;
-
- QString conversionRule(TypeSystem::Language language, int idx) const;
- QVector<ReferenceCount> referenceCounts(const AbstractMetaClass *cls, int idx = -2) const;
- ArgumentOwner argumentOwner(const AbstractMetaClass *cls, int idx) const;
-
- // Returns the ownership rules for the given argument in the given context
- TypeSystem::Ownership ownership(const AbstractMetaClass *cls, TypeSystem::Language language, int idx) const;
-
- QString typeReplaced(int argument_index) const;
- bool isModifiedToArray(int argumentIndex) const;
- bool isRemovedFromAllLanguages(const AbstractMetaClass *) const;
- bool isRemovedFrom(const AbstractMetaClass *, TypeSystem::Language language) const;
- bool argumentRemoved(int) const;
- /**
- * Verifies if any modification to the function is an inject code.
- * \return true if there is inject code modifications to the function.
- */
- bool hasInjectedCode() const;
- /**
- * Returns a list of code snips for this function.
- * The code snips can be filtered by position and language.
- * \return list of code snips
- */
- CodeSnipList injectedCodeSnips(TypeSystem::CodeSnipPosition position = TypeSystem::CodeSnipPositionAny,
- TypeSystem::Language language = TypeSystem::All) const;
-
- /**
- * Verifies if any modification to the function alters/removes its
- * arguments types or default values.
- * \return true if there is some modification to function signature
- */
- bool hasSignatureModifications() const;
- FunctionModificationList modifications(const AbstractMetaClass* implementor = nullptr) const;
-
- /**
- * Return the argument name if there is a modification the renamed value will be returned
- */
- QString argumentName(int index, bool create = true, const AbstractMetaClass *cl = nullptr) const;
-
- void setPropertySpec(QPropertySpec *spec)
- {
- m_propertySpec = spec;
- }
-
- QPropertySpec *propertySpec() const
- {
- return m_propertySpec;
- }
-
- FunctionTypeEntry* typeEntry() const
- {
- return m_typeEntry;
- }
-
- void setTypeEntry(FunctionTypeEntry* typeEntry)
- {
- m_typeEntry = typeEntry;
- }
-
- bool isCallOperator() const;
-
- static AbstractMetaFunction *
- find(const AbstractMetaFunctionList &haystack, const QString &needle);
-
- // for the meta builder only
- void setAllowThreadModification(TypeSystem::AllowThread am)
- { m_allowThreadModification = am; }
- void setExceptionHandlingModification(TypeSystem::ExceptionHandling em)
- { m_exceptionHandlingModification = em; }
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebugVerbose(QDebug &d) const;
-#endif
-
-private:
- bool autoDetectAllowThread() const;
-
- QString m_name;
- QString m_originalName;
- mutable QString m_cachedMinimalSignature;
- mutable QString m_cachedSignature;
- mutable QString m_cachedModifiedName;
-
- FunctionTypeEntry* m_typeEntry = nullptr;
- FunctionType m_functionType = NormalFunction;
- AbstractMetaType *m_type = nullptr;
- const AbstractMetaClass *m_class = nullptr;
- const AbstractMetaClass *m_implementingClass = nullptr;
- const AbstractMetaClass *m_declaringClass = nullptr;
- QPropertySpec *m_propertySpec = nullptr;
- AbstractMetaArgumentList m_arguments;
- AddedFunctionPtr m_addedFunction;
- uint m_constant : 1;
- uint m_reverse : 1;
- uint m_explicit : 1;
- uint m_pointerOperator : 1;
- uint m_isCallOperator : 1;
- ExceptionSpecification m_exceptionSpecification = ExceptionSpecification::Unknown;
- TypeSystem::AllowThread m_allowThreadModification = TypeSystem::AllowThread::Unspecified;
- TypeSystem::ExceptionHandling m_exceptionHandlingModification = TypeSystem::ExceptionHandling::Unspecified;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(AbstractMetaFunction::CompareResult)
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaFunction *af);
-#endif
-
-class AbstractMetaEnumValue
-{
-public:
- AbstractMetaEnumValue() = default;
-
- EnumValue value() const
- {
- return m_value;
- }
-
- void setValue(EnumValue value)
- {
- m_value = value;
- }
-
- QString stringValue() const
- {
- return m_stringValue;
- }
-
- void setStringValue(const QString &v)
- {
- m_stringValue = v;
- }
-
- QString name() const
- {
- return m_name;
- }
-
- void setName(const QString &name)
- {
- m_name = name;
- }
-
- void setDocumentation(const Documentation& doc)
- {
- m_doc = doc;
- }
-
- Documentation documentation() const
- {
- return m_doc;
- }
-
-private:
- QString m_name;
- QString m_stringValue;
-
- EnumValue m_value;
-
- Documentation m_doc;
-};
-
-class AbstractMetaEnum : public AbstractMetaAttributes, public EnclosingClassMixin
-{
-public:
- AbstractMetaEnum();
- ~AbstractMetaEnum();
-
- AbstractMetaEnumValueList values() const
- {
- return m_enumValues;
- }
-
- void addEnumValue(AbstractMetaEnumValue *enumValue)
- {
- m_enumValues << enumValue;
- }
-
- AbstractMetaEnumValue *findEnumValue(const QString &value) const;
-
- QString name() const;
-
- QString qualifier() const;
-
- QString package() const;
-
- QString fullName() const
- {
- return package() + QLatin1Char('.') + qualifier() + QLatin1Char('.') + name();
- }
-
- EnumKind enumKind() const { return m_enumKind; }
- void setEnumKind(EnumKind kind) { m_enumKind = kind; }
-
- bool isAnonymous() const { return m_enumKind == AnonymousEnum; }
-
- // Has the enum been declared inside a Q_ENUMS() macro in its enclosing class?
- void setHasQEnumsDeclaration(bool on)
- {
- m_hasQenumsDeclaration = on;
- }
-
- bool hasQEnumsDeclaration() const
- {
- return m_hasQenumsDeclaration;
- }
-
- EnumTypeEntry *typeEntry() const
- {
- return m_typeEntry;
- }
-
- void setTypeEntry(EnumTypeEntry *entry)
- {
- m_typeEntry = entry;
- }
-
- bool isSigned() const { return m_signed; }
- void setSigned(bool s) { m_signed = s; }
-
-private:
- AbstractMetaEnumValueList m_enumValues;
- EnumTypeEntry *m_typeEntry = nullptr;
-
- EnumKind m_enumKind = CEnum;
- uint m_hasQenumsDeclaration : 1;
- uint m_signed : 1;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AbstractMetaEnum *ae);
-#endif
-
-class AbstractMetaClass : public AbstractMetaAttributes, public EnclosingClassMixin
-{
- Q_GADGET
-public:
- enum FunctionQueryOption {
- Constructors = 0x0000001, // Only constructors
- //Destructors = 0x0000002, // Only destructors. Not included in class.
- FinalInTargetLangFunctions = 0x0000008, // Only functions that are non-virtual in TargetLang
- ClassImplements = 0x0000020, // Only functions implemented by the current class
- StaticFunctions = 0x0000080, // Only static functions
- Signals = 0x0000100, // Only signals
- NormalFunctions = 0x0000200, // Only functions that aren't signals
- Visible = 0x0000400, // Only public and protected functions
- WasPublic = 0x0001000, // Only functions that were originally public
- NonStaticFunctions = 0x0004000, // No static functions
- Empty = 0x0008000, // Empty overrides of abstract functions
- Invisible = 0x0010000, // Only private functions
- VirtualInCppFunctions = 0x0020000, // Only functions that are virtual in C++
- VirtualInTargetLangFunctions = 0x0080000, // Only functions which are virtual in TargetLang
- NotRemovedFromTargetLang = 0x0400000, // Only functions that have not been removed from TargetLang
- OperatorOverloads = 0x2000000, // Only functions that are operator overloads
- GenerateExceptionHandling = 0x4000000,
- GetAttroFunction = 0x8000000,
- SetAttroFunction = 0x10000000
- };
- Q_DECLARE_FLAGS(FunctionQueryOptions, FunctionQueryOption)
- Q_FLAG(FunctionQueryOption)
-
- enum OperatorQueryOption {
- ArithmeticOp = 0x01, // Arithmetic: +, -, *, /, %, +=, -=, *=, /=, %=, ++, --, unary+, unary-
- BitwiseOp = 0x02, // Bitwise: <<, <<=, >>, >>=, ~, &, &=, |, |=, ^, ^=
- ComparisonOp = 0x04, // Comparison: <, <=, >, >=, !=, ==
- LogicalOp = 0x08, // Logical: !, &&, ||
- ConversionOp = 0x10, // Conversion: operator [const] TYPE()
- SubscriptionOp = 0x20, // Subscription: []
- AssignmentOp = 0x40, // Assignment: =
- OtherOp = 0x80, // The remaining operators: call(), etc
- AllOperators = ArithmeticOp | BitwiseOp | ComparisonOp
- | LogicalOp | ConversionOp | SubscriptionOp
- | AssignmentOp | OtherOp
- };
- Q_DECLARE_FLAGS(OperatorQueryOptions, OperatorQueryOption)
- Q_FLAG(OperatorQueryOption)
-
- AbstractMetaClass();
- ~AbstractMetaClass();
-
- void fixFunctions();
-
- AbstractMetaFunctionList functions() const
- {
- return m_functions;
- }
-
- void setFunctions(const AbstractMetaFunctionList &functions);
- void addFunction(AbstractMetaFunction *function);
- bool hasFunction(const AbstractMetaFunction *f) const;
- bool hasFunction(const QString &str) const;
- const AbstractMetaFunction* findFunction(const QString& functionName) const;
- bool hasSignal(const AbstractMetaFunction *f) const;
-
- bool hasConstructors() const;
- const AbstractMetaFunction *copyConstructor() const;
- bool hasCopyConstructor() const { return copyConstructor() != nullptr; }
- bool hasPrivateCopyConstructor() const;
-
- void addDefaultConstructor();
- void addDefaultCopyConstructor(bool isPrivate = false);
-
- bool hasNonPrivateConstructor() const
- {
- return m_hasNonPrivateConstructor;
- }
-
- void setHasNonPrivateConstructor(bool value)
- {
- m_hasNonPrivateConstructor = value;
- }
-
- bool hasPrivateConstructor() const
- {
- return m_hasPrivateConstructor;
- }
-
- void setHasPrivateConstructor(bool value)
- {
- m_hasPrivateConstructor = value;
- }
-
- bool hasPrivateDestructor() const
- {
- return m_hasPrivateDestructor;
- }
-
- void setHasPrivateDestructor(bool value)
- {
- m_hasPrivateDestructor = value;
- }
-
- bool hasProtectedDestructor() const
- {
- return m_hasProtectedDestructor;
- }
-
- void setHasProtectedDestructor(bool value)
- {
- m_hasProtectedDestructor = value;
- }
-
- bool hasVirtualDestructor() const
- {
- return m_hasVirtualDestructor;
- }
-
- void setHasVirtualDestructor(bool value);
-
- bool isConstructible() const
- {
- return (hasNonPrivateConstructor() || !hasPrivateConstructor()) && !hasPrivateDestructor();
- }
-
- bool generateExceptionHandling() const;
-
- AbstractMetaFunctionList queryFunctionsByName(const QString &name) const;
- static bool queryFunction(const AbstractMetaFunction *f, FunctionQueryOptions query);
- static AbstractMetaFunctionList queryFunctionList(const AbstractMetaFunctionList &list,
- FunctionQueryOptions query);
- static const AbstractMetaFunction *queryFirstFunction(const AbstractMetaFunctionList &list,
- FunctionQueryOptions query);
-
- AbstractMetaFunctionList queryFunctions(FunctionQueryOptions query) const;
- AbstractMetaFunctionList functionsInTargetLang() const;
- AbstractMetaFunctionList cppSignalFunctions() const;
- AbstractMetaFunctionList implicitConversions() const;
-
- /**
- * Retrieves all class' operator overloads that meet
- * query criteria defined with the OperatorQueryOption
- * enum.
- * /param query composition of OperatorQueryOption enum values
- * /return list of operator overload methods that meet the
- * query criteria
- */
- AbstractMetaFunctionList operatorOverloads(OperatorQueryOptions query = AllOperators) const;
-
- bool hasArithmeticOperatorOverload() const;
- bool hasBitwiseOperatorOverload() const;
- bool hasComparisonOperatorOverload() const;
- bool hasLogicalOperatorOverload() const;
-
- AbstractMetaFieldList fields() const
- {
- return m_fields;
- }
-
- void setFields(const AbstractMetaFieldList &fields)
- {
- m_fields = fields;
- }
-
- void addField(AbstractMetaField *field)
- {
- m_fields << field;
- }
-
- AbstractMetaField *findField(const QString &name) const;
-
- AbstractMetaEnumList enums() const
- {
- return m_enums;
- }
- void setEnums(const AbstractMetaEnumList &enums)
- {
- m_enums = enums;
- }
-
- void addEnum(AbstractMetaEnum *e)
- {
- m_enums << e;
- }
-
- AbstractMetaEnum *findEnum(const QString &enumName);
- AbstractMetaEnumValue *findEnumValue(const QString &enumName);
-
- QString fullName() const
- {
- return package() + QLatin1Char('.') + name();
- }
-
- /**
- * Retrieves the class name without any namespace/scope information.
- * /return the class name without scope information
- */
- QString name() const;
-
- QString baseClassName() const
- {
- return m_baseClasses.isEmpty() ? QString() : m_baseClasses.constFirst()->name();
- }
-
- AbstractMetaClass *baseClass() const
- {
- return m_baseClasses.value(0, nullptr);
- }
- const AbstractMetaClassList &baseClasses() const { return m_baseClasses; }
-
- void addBaseClass(AbstractMetaClass *base_class);
- void setBaseClass(AbstractMetaClass *base_class);
-
- /**
- * \return the namespace from another package which this namespace extends.
- */
- AbstractMetaClass *extendedNamespace() const { return m_extendedNamespace; }
- void setExtendedNamespace(AbstractMetaClass *e) { m_extendedNamespace = e; }
-
- const AbstractMetaClassList& innerClasses() const
- {
- return m_innerClasses;
- }
-
- void addInnerClass(AbstractMetaClass* cl)
- {
- m_innerClasses << cl;
- }
-
- void setInnerClasses(const AbstractMetaClassList &innerClasses)
- {
- m_innerClasses = innerClasses;
- }
-
- QString package() const;
-
- bool isNamespace() const;
-
- bool isQObject() const;
-
- bool isQtNamespace() const
- {
- return isNamespace() && name() == QLatin1String("Qt");
- }
-
- QString qualifiedCppName() const;
-
- bool hasSignals() const;
- bool inheritsFrom(const AbstractMetaClass *other) const;
-
- /**
- * Says if the class that declares or inherits a virtual function.
- * \return true if the class implements or inherits any virtual methods
- */
- bool isPolymorphic() const
- {
- return m_isPolymorphic;
- }
-
- /**
- * Tells if this class has one or more functions that are protected.
- * \return true if the class has protected functions.
- */
- bool hasProtectedFunctions() const;
-
- /**
- * Tells if this class has one or more fields (member variables) that are protected.
- * \return true if the class has protected fields.
- */
- bool hasProtectedFields() const;
-
- /**
- * Tells if this class has one or more members (functions or fields) that are protected.
- * \return true if the class has protected members.
- */
- bool hasProtectedMembers() const;
-
-
- QVector<TypeEntry *> templateArguments() const
- {
- return m_templateArgs;
- }
-
- void setTemplateArguments(const QVector<TypeEntry *> &args)
- {
- m_templateArgs = args;
- }
-
- bool hasFieldAccessors() const;
-
- // only valid during metabuilder's run
- QStringList baseClassNames() const
- {
- return m_baseClassNames;
- }
-
- void setBaseClassNames(const QStringList &names)
- {
- m_baseClassNames = names;
- }
-
- const ComplexTypeEntry *typeEntry() const
- {
- return m_typeEntry;
- }
-
- ComplexTypeEntry *typeEntry()
- {
- return m_typeEntry;
- }
-
- void setTypeEntry(ComplexTypeEntry *type)
- {
- m_typeEntry = type;
- }
-
- void setHasHashFunction(bool on)
- {
- m_hasHashFunction = on;
- }
-
- bool hasHashFunction() const
- {
- return m_hasHashFunction;
- }
- virtual bool hasDefaultToStringFunction() const;
-
- void setHasEqualsOperator(bool on)
- {
- m_hasEqualsOperator = on;
- }
-
- bool hasEqualsOperator() const
- {
- return m_hasEqualsOperator;
- }
-
- void setHasCloneOperator(bool on)
- {
- m_hasCloneOperator = on;
- }
-
- bool hasCloneOperator() const
- {
- return m_hasCloneOperator;
- }
-
- void addPropertySpec(QPropertySpec *spec)
- {
- m_propertySpecs << spec;
- }
-
- QVector<QPropertySpec *> propertySpecs() const
- {
- return m_propertySpecs;
- }
-
- QPropertySpec *propertySpecForRead(const QString &name) const;
- QPropertySpec *propertySpecForWrite(const QString &name) const;
- QPropertySpec *propertySpecForReset(const QString &name) const;
-
- /// Returns a list of conversion operators for this class. The conversion operators are defined in other classes of the same module.
- AbstractMetaFunctionList externalConversionOperators() const
- {
- return m_externalConversionOperators;
- }
- /// Adds a converter operator for this class.
- void addExternalConversionOperator(AbstractMetaFunction* conversionOp)
- {
- if (!m_externalConversionOperators.contains(conversionOp))
- m_externalConversionOperators.append(conversionOp);
- }
- /// Returns true if this class has any converter operators defined elsewhere.
- bool hasExternalConversionOperators() const
- {
- return !m_externalConversionOperators.isEmpty();
- }
-
- void sortFunctions();
-
- const AbstractMetaClass *templateBaseClass() const
- {
- return m_templateBaseClass;
- }
-
- void setTemplateBaseClass(const AbstractMetaClass *cls)
- {
- m_templateBaseClass = cls;
- }
-
- bool hasTemplateBaseClassInstantiations() const;
- AbstractMetaTypeList templateBaseClassInstantiations() const;
- void setTemplateBaseClassInstantiations(AbstractMetaTypeList& instantiations);
-
- void setTypeDef(bool typeDef) { m_isTypeDef = typeDef; }
- bool isTypeDef() const { return m_isTypeDef; }
-
- void setStream(bool stream)
- {
- m_stream = stream;
- }
-
- bool isStream() const
- {
- return m_stream;
- }
-
- void setToStringCapability(bool value, uint indirections = 0)
- {
- m_hasToStringCapability = value;
- m_toStringCapabilityIndirections = indirections;
- }
-
- bool hasToStringCapability() const
- {
- return m_hasToStringCapability;
- }
-
- uint toStringCapabilityIndirections() const
- {
- return m_toStringCapabilityIndirections;
- }
-
- bool deleteInMainThread() const;
-
- static AbstractMetaClass *findClass(const AbstractMetaClassList &classes,
- const QString &name);
- static AbstractMetaClass *findClass(const AbstractMetaClassList &classes,
- const TypeEntry* typeEntry);
- static AbstractMetaEnumValue *findEnumValue(const AbstractMetaClassList &classes,
- const QString &string);
- static AbstractMetaEnum *findEnum(const AbstractMetaClassList &classes,
- const EnumTypeEntry *entry);
-
-private:
-#ifndef QT_NO_DEBUG_STREAM
- void format(QDebug &d) const;
- void formatMembers(QDebug &d) const;
- friend QDebug operator<<(QDebug d, const AbstractMetaClass *ac);
-#endif
- uint m_hasVirtuals : 1;
- uint m_isPolymorphic : 1;
- uint m_hasNonpublic : 1;
- uint m_hasNonPrivateConstructor : 1;
- uint m_hasPrivateConstructor : 1;
- uint m_functionsFixed : 1;
- uint m_hasPrivateDestructor : 1;
- uint m_hasProtectedDestructor : 1;
- uint m_hasVirtualDestructor : 1;
- uint m_hasHashFunction : 1;
- uint m_hasEqualsOperator : 1;
- uint m_hasCloneOperator : 1;
- uint m_isTypeDef : 1;
- uint m_hasToStringCapability : 1;
-
- const AbstractMetaClass *m_enclosingClass = nullptr;
- AbstractMetaClassList m_baseClasses; // Real base classes after setting up inheritance
- AbstractMetaClass *m_extendedNamespace = nullptr;
-
- const AbstractMetaClass *m_templateBaseClass = nullptr;
- AbstractMetaFunctionList m_functions;
- AbstractMetaFieldList m_fields;
- AbstractMetaEnumList m_enums;
- QVector<QPropertySpec *> m_propertySpecs;
- AbstractMetaClassList m_innerClasses;
-
- AbstractMetaFunctionList m_externalConversionOperators;
-
- QStringList m_baseClassNames; // Base class names from C++, including rejected
- QVector<TypeEntry *> m_templateArgs;
- ComplexTypeEntry *m_typeEntry = nullptr;
-// FunctionModelItem m_qDebugStreamFunction;
-
- bool m_stream = false;
- uint m_toStringCapabilityIndirections = 0;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(AbstractMetaClass::FunctionQueryOptions)
-Q_DECLARE_OPERATORS_FOR_FLAGS(AbstractMetaClass::OperatorQueryOptions)
-
-class QPropertySpec
-{
-public:
- explicit QPropertySpec(const TypeEntry *type) : m_type(type) {}
-
- const TypeEntry *type() const
- {
- return m_type;
- }
-
- QString name() const
- {
- return m_name;
- }
-
- void setName(const QString &name)
- {
- m_name = name;
- }
-
- QString read() const
- {
- return m_read;
- }
-
- void setRead(const QString &read)
- {
- m_read = read;
- }
-
- QString write() const
- {
- return m_write;
- }
-
- void setWrite(const QString &write)
- {
- m_write = write;
- }
-
- QString designable() const
- {
- return m_designable;
- }
-
- void setDesignable(const QString &designable)
- {
- m_designable = designable;
- }
-
- QString reset() const
- {
- return m_reset;
- }
-
- void setReset(const QString &reset)
- {
- m_reset = reset;
- }
-
- int index() const
- {
- return m_index;
- }
-
- void setIndex(int index)
- {
- m_index = index;
- }
-
-private:
- QString m_name;
- QString m_read;
- QString m_write;
- QString m_designable;
- QString m_reset;
- const TypeEntry *m_type;
- int m_index = -1;
-};
-
-#endif // ABSTRACTMETALANG_H
diff --git a/sources/shiboken2/ApiExtractor/abstractmetalang_typedefs.h b/sources/shiboken2/ApiExtractor/abstractmetalang_typedefs.h
deleted file mode 100644
index 617ebcf4f..000000000
--- a/sources/shiboken2/ApiExtractor/abstractmetalang_typedefs.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ABSTRACTMETALANG_TYPEDEFS_H
-#define ABSTRACTMETALANG_TYPEDEFS_H
-
-#include <QtCore/QVector>
-
-class AbstractMetaClass;
-class AbstractMetaField;
-class AbstractMetaArgument;
-class AbstractMetaEnum;
-class AbstractMetaEnumValue;
-class AbstractMetaFunction;
-class AbstractMetaType;
-
-using AbstractMetaArgumentList = QVector<AbstractMetaArgument *>;
-using AbstractMetaClassList = QVector<AbstractMetaClass *>;
-using AbstractMetaEnumList = QVector<AbstractMetaEnum *>;
-using AbstractMetaEnumValueList = QVector<AbstractMetaEnumValue *>;
-using AbstractMetaFieldList = QVector<AbstractMetaField *>;
-using AbstractMetaFunctionList = QVector<AbstractMetaFunction *>;
-using AbstractMetaTypeList = QVector<AbstractMetaType *>;
-using AbstractMetaTypeCList = QVector<const AbstractMetaType *>;
-
-#endif // ABSTRACTMETALANG_TYPEDEFS_H
diff --git a/sources/shiboken2/ApiExtractor/apiextractor.cpp b/sources/shiboken2/ApiExtractor/apiextractor.cpp
deleted file mode 100644
index 6ca628c0a..000000000
--- a/sources/shiboken2/ApiExtractor/apiextractor.cpp
+++ /dev/null
@@ -1,264 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "apiextractor.h"
-#include "abstractmetalang.h"
-
-#include <QDir>
-#include <QDebug>
-#include <QTemporaryFile>
-#include <algorithm>
-#include <iostream>
-#include <iterator>
-
-#include "reporthandler.h"
-#include "typesystem.h"
-#include "fileout.h"
-#include "abstractmetabuilder.h"
-#include "typedatabase.h"
-#include "typesystem.h"
-
-ApiExtractor::ApiExtractor()
-{
- // Environment TYPESYSTEMPATH
- QString envTypesystemPaths = QFile::decodeName(qgetenv("TYPESYSTEMPATH"));
- if (!envTypesystemPaths.isEmpty())
- TypeDatabase::instance()->addTypesystemPath(envTypesystemPaths);
-}
-
-ApiExtractor::~ApiExtractor()
-{
- delete m_builder;
-}
-
-void ApiExtractor::addTypesystemSearchPath (const QString& path)
-{
- TypeDatabase::instance()->addTypesystemPath(path);
-}
-
-void ApiExtractor::addTypesystemSearchPath(const QStringList& paths)
-{
- for (const QString &path : paths)
- addTypesystemSearchPath(path);
-}
-
-void ApiExtractor::addIncludePath(const HeaderPath& path)
-{
- m_includePaths << path;
-}
-
-void ApiExtractor::addIncludePath(const HeaderPaths& paths)
-{
- m_includePaths << paths;
-}
-
-void ApiExtractor::setLogDirectory(const QString& logDir)
-{
- m_logDirectory = logDir;
-}
-
-void ApiExtractor::setCppFileName(const QString& cppFileName)
-{
- m_cppFileName = cppFileName;
-}
-
-void ApiExtractor::setTypeSystem(const QString& typeSystemFileName)
-{
- m_typeSystemFileName = typeSystemFileName;
-}
-
-void ApiExtractor::setSkipDeprecated(bool value)
-{
- m_skipDeprecated = value;
- if (m_builder)
- m_builder->setSkipDeprecated(m_skipDeprecated);
-}
-
-void ApiExtractor::setSuppressWarnings ( bool value )
-{
- TypeDatabase::instance()->setSuppressWarnings(value);
-}
-
-void ApiExtractor::setSilent ( bool value )
-{
- ReportHandler::setSilent(value);
-}
-
-bool ApiExtractor::setApiVersion(const QString& package, const QString &version)
-{
- return TypeDatabase::setApiVersion(package, version);
-}
-
-void ApiExtractor::setDropTypeEntries(QString dropEntries)
-{
- dropEntries.remove(QLatin1Char(' '));
- QStringList entries = dropEntries.split(QLatin1Char(';'));
- TypeDatabase::instance()->setDropTypeEntries(entries);
-}
-
-AbstractMetaEnumList ApiExtractor::globalEnums() const
-{
- Q_ASSERT(m_builder);
- return m_builder->globalEnums();
-}
-
-AbstractMetaFunctionList ApiExtractor::globalFunctions() const
-{
- Q_ASSERT(m_builder);
- return m_builder->globalFunctions();
-}
-
-AbstractMetaClassList ApiExtractor::classes() const
-{
- Q_ASSERT(m_builder);
- return m_builder->classes();
-}
-
-AbstractMetaClassList ApiExtractor::smartPointers() const
-{
- Q_ASSERT(m_builder);
- return m_builder->smartPointers();
-}
-
-AbstractMetaClassList ApiExtractor::classesTopologicalSorted(const Dependencies &additionalDependencies) const
-{
- Q_ASSERT(m_builder);
- return m_builder->classesTopologicalSorted(m_builder->classes(), additionalDependencies);
-}
-
-PrimitiveTypeEntryList ApiExtractor::primitiveTypes() const
-{
- return TypeDatabase::instance()->primitiveTypes();
-}
-
-ContainerTypeEntryList ApiExtractor::containerTypes() const
-{
- return TypeDatabase::instance()->containerTypes();
-}
-
-const AbstractMetaEnum* ApiExtractor::findAbstractMetaEnum(const TypeEntry* typeEntry) const
-{
- return m_builder->findEnum(typeEntry);
-}
-
-int ApiExtractor::classCount() const
-{
- Q_ASSERT(m_builder);
- return m_builder->classes().count();
-}
-
-bool ApiExtractor::run()
-{
- if (m_builder)
- return false;
-
- if (!TypeDatabase::instance()->parseFile(m_typeSystemFileName)) {
- std::cerr << "Cannot parse file: " << qPrintable(m_typeSystemFileName);
- return false;
- }
-
- const QString pattern = QDir::tempPath() + QLatin1Char('/') +
- QFileInfo(m_cppFileName).baseName() + QStringLiteral("_XXXXXX.hpp");
- QTemporaryFile ppFile(pattern);
- bool autoRemove = !qEnvironmentVariableIsSet("KEEP_TEMP_FILES");
- // make sure that a tempfile can be written
- if (!ppFile.open()) {
- std::cerr << "could not create tempfile " << qPrintable(pattern)
- << ": " << qPrintable(ppFile.errorString()) << '\n';
- return false;
- }
- ppFile.write("#include \"");
- ppFile.write(m_cppFileName.toLocal8Bit());
- ppFile.write("\"\n");
- const QString preprocessedCppFileName = ppFile.fileName();
- ppFile.close();
- m_builder = new AbstractMetaBuilder;
- m_builder->setLogDirectory(m_logDirectory);
- m_builder->setGlobalHeader(m_cppFileName);
- m_builder->setSkipDeprecated(m_skipDeprecated);
- m_builder->setHeaderPaths(m_includePaths);
- QByteArrayList arguments;
- arguments.reserve(m_includePaths.size() + 1);
- for (const HeaderPath &headerPath : qAsConst(m_includePaths))
- arguments.append(HeaderPath::includeOption(headerPath));
- arguments.append(QFile::encodeName(preprocessedCppFileName));
- if (ReportHandler::isDebug(ReportHandler::SparseDebug)) {
- qCInfo(lcShiboken).noquote().nospace()
- << "clang language level: " << int(m_languageLevel)
- << "\nclang arguments: " << arguments;
- }
- const bool result = m_builder->build(arguments, m_languageLevel);
- if (!result)
- autoRemove = false;
- if (!autoRemove) {
- ppFile.setAutoRemove(false);
- std::cerr << "Keeping temporary file: " << qPrintable(QDir::toNativeSeparators(preprocessedCppFileName)) << '\n';
- }
- return result;
-}
-
-LanguageLevel ApiExtractor::languageLevel() const
-{
- return m_languageLevel;
-}
-
-void ApiExtractor::setLanguageLevel(LanguageLevel languageLevel)
-{
- m_languageLevel = languageLevel;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-template <class Container>
-static void debugFormatSequence(QDebug &d, const char *key, const Container& c)
-{
- if (c.isEmpty())
- return;
- const auto begin = c.begin();
- d << "\n " << key << '[' << c.size() << "]=(";
- for (auto it = begin, end = c.end(); it != end; ++it) {
- if (it != begin)
- d << ", ";
- d << *it;
- }
- d << ')';
-}
-
-QDebug operator<<(QDebug d, const ApiExtractor &ae)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- if (ReportHandler::debugLevel() >= ReportHandler::FullDebug)
- d.setVerbosity(3); // Trigger verbose output of AbstractMetaClass
- d << "ApiExtractor(typeSystem=\"" << ae.typeSystem() << "\", cppFileName=\""
- << ae.cppFileName() << ", ";
- ae.m_builder->formatDebug(d);
- d << ')';
- return d;
-}
-#endif // QT_NO_DEBUG_STREAM
diff --git a/sources/shiboken2/ApiExtractor/apiextractor.h b/sources/shiboken2/ApiExtractor/apiextractor.h
deleted file mode 100644
index 84319e64f..000000000
--- a/sources/shiboken2/ApiExtractor/apiextractor.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef APIEXTRACTOR_H
-#define APIEXTRACTOR_H
-
-#include "dependency.h"
-#include "abstractmetalang_typedefs.h"
-#include "apiextractormacros.h"
-#include "header_paths.h"
-#include "typedatabase_typedefs.h"
-#include "typesystem_typedefs.h"
-#include "clangparser/compilersupport.h"
-#include <QStringList>
-
-class AbstractMetaBuilder;
-class AbstractMetaClass;
-class AbstractMetaEnum;
-class AbstractMetaFunction;
-class AbstractMetaType;
-class ContainerTypeEntry;
-class EnumTypeEntry;
-class FlagsTypeEntry;
-class PrimitiveTypeEntry;
-class TypeEntry;
-
-QT_BEGIN_NAMESPACE
-class QDebug;
-class QIODevice;
-QT_END_NAMESPACE
-
-class ApiExtractor
-{
-public:
- Q_DISABLE_COPY(ApiExtractor)
-
- ApiExtractor();
- ~ApiExtractor();
-
- void setTypeSystem(const QString& typeSystemFileName);
- QString typeSystem() const { return m_typeSystemFileName; }
- void setCppFileName(const QString& cppFileName);
- QString cppFileName() const { return m_cppFileName; }
- void setSkipDeprecated(bool value);
- void setSuppressWarnings(bool value);
- void setSilent(bool value);
- void addTypesystemSearchPath(const QString& path);
- void addTypesystemSearchPath(const QStringList& paths);
- void addIncludePath(const HeaderPath& path);
- void addIncludePath(const HeaderPaths& paths);
- HeaderPaths includePaths() const { return m_includePaths; }
- void setLogDirectory(const QString& logDir);
- bool setApiVersion(const QString& package, const QString& version);
- void setDropTypeEntries(QString dropEntries);
- LanguageLevel languageLevel() const;
- void setLanguageLevel(LanguageLevel languageLevel);
-
- AbstractMetaEnumList globalEnums() const;
- AbstractMetaFunctionList globalFunctions() const;
- AbstractMetaClassList classes() const;
- AbstractMetaClassList smartPointers() const;
- AbstractMetaClassList classesTopologicalSorted(const Dependencies &additionalDependencies = Dependencies()) const;
- PrimitiveTypeEntryList primitiveTypes() const;
- ContainerTypeEntryList containerTypes() const;
-
- const AbstractMetaEnum* findAbstractMetaEnum(const TypeEntry* typeEntry) const;
-
- int classCount() const;
-
- bool run();
-private:
- QString m_typeSystemFileName;
- QString m_cppFileName;
- HeaderPaths m_includePaths;
- AbstractMetaBuilder* m_builder = nullptr;
- QString m_logDirectory;
- LanguageLevel m_languageLevel = LanguageLevel::Default;
- bool m_skipDeprecated = false;
-
-#ifndef QT_NO_DEBUG_STREAM
- friend QDebug operator<<(QDebug d, const ApiExtractor &ae);
-#endif
-};
-
-#endif // APIEXTRACTOR_H
-
diff --git a/sources/shiboken2/ApiExtractor/apiextractormacros.h b/sources/shiboken2/ApiExtractor/apiextractormacros.h
deleted file mode 100644
index 026cd5a9e..000000000
--- a/sources/shiboken2/ApiExtractor/apiextractormacros.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef APIEXTRACTORMACROS_H
-#define APIEXTRACTORMACROS_H
-
-
-// APIEXTRACTOR_API is used for the public API symbols.
-#if defined _WIN32
- #define APIEXTRACTOR_DEPRECATED(func) __declspec(deprecated) func
-#elif __GNUC__ >= 4
- #define APIEXTRACTOR_DEPRECATED(func) func __attribute__ ((deprecated))
-#else
- #define APIEXTRACTOR_DEPRECATED(func) func
-#endif
-#endif
diff --git a/sources/shiboken2/ApiExtractor/clangparser/clangbuilder.cpp b/sources/shiboken2/ApiExtractor/clangparser/clangbuilder.cpp
deleted file mode 100644
index 310a751e0..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/clangbuilder.cpp
+++ /dev/null
@@ -1,1150 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "clangbuilder.h"
-#include "compilersupport.h"
-#include "clangutils.h"
-
-#include <codemodel.h>
-
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QHash>
-#include <QtCore/QMap>
-#include <QtCore/QString>
-#include <QtCore/QStack>
-#include <QtCore/QVector>
-
-#include <cstring>
-#include <ctype.h>
-
-#if QT_VERSION < 0x050800
-# define Q_FALLTHROUGH() (void)0
-#endif
-
-namespace clang {
-
-static inline QString colonColon() { return QStringLiteral("::"); }
-static inline QString templateBrackets() { return QStringLiteral("<>"); }
-
-static inline bool isClassCursor(const CXCursor &c)
-{
- return c.kind == CXCursor_ClassDecl || c.kind == CXCursor_StructDecl
- || c.kind == CXCursor_ClassTemplate
- || c.kind == CXCursor_ClassTemplatePartialSpecialization;
-}
-
-static inline bool withinClassDeclaration(const CXCursor &cursor)
-{
- return isClassCursor(clang_getCursorLexicalParent(cursor));
-}
-
-static QString fixTypeName(QString t)
-{
- // Fix "Foo &" -> "Foo&", similarly "Bar **" -> "Bar**"
- int pos = t.size() - 1;
- for (; pos >= 0 && (t.at(pos) == QLatin1Char('&') || t.at(pos) == QLatin1Char('*')); --pos) {}
- if (pos > 0 && t.at(pos) == QLatin1Char(' '))
- t.remove(pos, 1);
- return t;
-}
-
-// Insert template parameter to class name: "Foo<>" -> "Foo<T1>" -> "Foo<T1,T2>"
-// This needs to be done immediately when template parameters are encountered since
-// the class name "Foo<T1,T2>" is the scope for nested items.
-static bool insertTemplateParameterIntoClassName(const QString &parmName, QString *name)
-{
- if (Q_UNLIKELY(!name->endsWith(QLatin1Char('>'))))
- return false;
- const bool needsComma = name->at(name->size() - 2) != QLatin1Char('<');
- const int insertionPos = name->size() - 1;
- name->insert(insertionPos, parmName);
- if (needsComma)
- name->insert(insertionPos, QLatin1Char(','));
- return true;
-}
-
-static inline bool insertTemplateParameterIntoClassName(const QString &parmName,
- const ClassModelItem &item)
-{
- QString name = item->name();
- const bool result = insertTemplateParameterIntoClassName(parmName, &name);
- item->setName(name);
- return result;
-}
-
-static inline CodeModel::AccessPolicy accessPolicy(CX_CXXAccessSpecifier access)
-{
- CodeModel::AccessPolicy result = CodeModel::Public;
- switch (access) {
- case CX_CXXProtected:
- result = CodeModel::Protected;
- break;
- case CX_CXXPrivate:
- result = CodeModel::Private;
- break;
- default:
- break;
- }
- return result;
-}
-
-static void setFileName(const CXCursor &cursor, _CodeModelItem *item)
-{
- const SourceRange range = getCursorRange(cursor);
- if (!range.first.file.isEmpty()) { // Has been observed to be 0 for invalid locations
- item->setFileName(QDir::cleanPath(range.first.file));
- item->setStartPosition(int(range.first.line), int(range.first.column));
- item->setEndPosition(int(range.second.line), int(range.second.column));
- }
-}
-
-static bool isSigned(CXTypeKind kind)
-{
- switch (kind) {
- case CXType_UChar:
- case CXType_Char16:
- case CXType_Char32:
- case CXType_UShort:
- case CXType_UInt:
- case CXType_ULong:
- case CXType_ULongLong:
- case CXType_UInt128:
- return false;
- default:
- break;
- }
- return true;
-}
-
-class BuilderPrivate {
-public:
- using CursorClassHash = QHash<CXCursor, ClassModelItem>;
- using CursorTypedefHash = QHash<CXCursor, TypeDefModelItem>;
- using TypeInfoHash = QHash<CXType, TypeInfo>;
-
- explicit BuilderPrivate(BaseVisitor *bv) : m_baseVisitor(bv), m_model(new CodeModel)
- {
- m_scopeStack.push(NamespaceModelItem(new _FileModelItem(m_model)));
- }
-
- // Determine scope from top item. Note that the scope list does not necessarily
- // match the scope stack in case of forward-declared inner classes whose definition
- // appears in the translation unit while the scope is the outer class.
- void updateScope()
- {
- if (m_scopeStack.size() <= 1)
- m_scope.clear();
- else
- m_scope = m_scopeStack.back()->scope() << m_scopeStack.back()->name();
- }
-
- void pushScope(const ScopeModelItem &i)
- {
- m_scopeStack.push(i);
- updateScope();
- }
-
- void popScope()
- {
- m_scopeStack.pop();
- updateScope();
- }
-
- bool addClass(const CXCursor &cursor, CodeModel::ClassType t);
- FunctionModelItem createFunction(const CXCursor &cursor,
- CodeModel::FunctionType t = CodeModel::Normal) const;
- FunctionModelItem createMemberFunction(const CXCursor &cursor) const;
- void qualifyConstructor(const CXCursor &cursor);
- TypeInfo createTypeInfoHelper(const CXType &type) const; // uncashed
- TypeInfo createTypeInfo(const CXType &type) const;
- TypeInfo createTypeInfo(const CXCursor &cursor) const
- { return createTypeInfo(clang_getCursorType(cursor)); }
- void addTemplateInstantiations(const CXType &type,
- QString *typeName,
- TypeInfo *t) const;
- bool addTemplateInstantiationsRecursion(const CXType &type, TypeInfo *t) const;
-
- void addTypeDef(const CXCursor &cursor, const CXType &cxType);
- void startTemplateTypeAlias(const CXCursor &cursor);
- void endTemplateTypeAlias(const CXCursor &typeAliasCursor);
-
- TemplateParameterModelItem createTemplateParameter(const CXCursor &cursor) const;
- TemplateParameterModelItem createNonTypeTemplateParameter(const CXCursor &cursor) const;
- void addField(const CXCursor &cursor);
-
- QString cursorValueExpression(BaseVisitor *bv, const CXCursor &cursor) const;
- void addBaseClass(const CXCursor &cursor);
-
- template <class Item>
- void qualifyTypeDef(const CXCursor &typeRefCursor, const QSharedPointer<Item> &item) const;
-
- bool visitHeader(const char *cFileName) const;
-
- BaseVisitor *m_baseVisitor;
- CodeModel *m_model;
-
- QStack<ScopeModelItem> m_scopeStack;
- QStringList m_scope;
- // Store all classes by cursor so that base classes can be found and inner
- // classes can be correctly parented in case of forward-declared inner classes
- // (QMetaObject::Connection)
- CursorClassHash m_cursorClassHash;
- CursorTypedefHash m_cursorTypedefHash;
-
- mutable TypeInfoHash m_typeInfoHash; // Cache type information
- mutable QHash<QString, TemplateTypeAliasModelItem> m_templateTypeAliases;
-
- ClassModelItem m_currentClass;
- EnumModelItem m_currentEnum;
- FunctionModelItem m_currentFunction;
- ArgumentModelItem m_currentArgument;
- VariableModelItem m_currentField;
- TemplateTypeAliasModelItem m_currentTemplateTypeAlias;
- QByteArrayList m_systemIncludes; // files, like "memory"
- QByteArrayList m_systemIncludePaths; // paths, like "/usr/include/Qt/"
-
- int m_anonymousEnumCount = 0;
- CodeModel::FunctionType m_currentFunctionType = CodeModel::Normal;
-};
-
-bool BuilderPrivate::addClass(const CXCursor &cursor, CodeModel::ClassType t)
-{
- QString className = getCursorSpelling(cursor);
- m_currentClass.reset(new _ClassModelItem(m_model, className));
- setFileName(cursor, m_currentClass.data());
- m_currentClass->setClassType(t);
- // Some inner class? Note that it does not need to be (lexically) contained in a
- // class since it is possible to forward declare an inner class:
- // class QMetaObject { class Connection; }
- // class QMetaObject::Connection {}
- const CXCursor semPar = clang_getCursorSemanticParent(cursor);
- if (isClassCursor(semPar)) {
- const CursorClassHash::const_iterator it = m_cursorClassHash.constFind(semPar);
- if (it == m_cursorClassHash.constEnd()) {
- const QString message = QStringLiteral("Unable to find parent of inner class ") + className;
- const Diagnostic d(message, cursor, CXDiagnostic_Error);
- qWarning() << d;
- m_baseVisitor->appendDiagnostic(d);
- return false;
- }
- const ClassModelItem &containingClass = it.value();
- containingClass->addClass(m_currentClass);
- m_currentClass->setScope(containingClass->scope() << containingClass->name());
- } else {
- m_currentClass->setScope(m_scope);
- m_scopeStack.back()->addClass(m_currentClass);
- }
- pushScope(m_currentClass);
- m_cursorClassHash.insert(cursor, m_currentClass);
- return true;
-}
-
-static inline ExceptionSpecification exceptionSpecificationFromClang(int ce)
-{
- switch (ce) {
- case CXCursor_ExceptionSpecificationKind_BasicNoexcept:
- case CXCursor_ExceptionSpecificationKind_ComputedNoexcept:
- case CXCursor_ExceptionSpecificationKind_DynamicNone: // throw()
- return ExceptionSpecification::NoExcept;
- case CXCursor_ExceptionSpecificationKind_Dynamic: // throw(t1..)
- case CXCursor_ExceptionSpecificationKind_MSAny: // throw(...)
- return ExceptionSpecification::Throws;
- default:
- // CXCursor_ExceptionSpecificationKind_None,
- // CXCursor_ExceptionSpecificationKind_Unevaluated,
- // CXCursor_ExceptionSpecificationKind_Uninstantiated
- break;
- }
- return ExceptionSpecification::Unknown;
-}
-
-FunctionModelItem BuilderPrivate::createFunction(const CXCursor &cursor,
- CodeModel::FunctionType t) const
-{
- QString name = getCursorSpelling(cursor);
- // Apply type fixes to "operator X &" -> "operator X&"
- if (name.startsWith(QLatin1String("operator ")))
- name = fixTypeName(name);
- FunctionModelItem result(new _FunctionModelItem(m_model, name));
- setFileName(cursor, result.data());
- result->setType(createTypeInfoHelper(clang_getCursorResultType(cursor)));
- result->setFunctionType(t);
- result->setScope(m_scope);
- result->setStatic(clang_Cursor_getStorageClass(cursor) == CX_SC_Static);
- result->setExceptionSpecification(exceptionSpecificationFromClang(clang_getCursorExceptionSpecificationType(cursor)));
- switch (clang_getCursorAvailability(cursor)) {
- case CXAvailability_Available:
- break;
- case CXAvailability_Deprecated:
- result->setDeprecated(true);
- break;
- case CXAvailability_NotAvailable: // "Foo(const Foo&) = delete;"
- result->setDeleted(true);
- break;
- case CXAvailability_NotAccessible:
- break;
- }
- return result;
-}
-
-static inline CodeModel::FunctionType functionTypeFromCursor(const CXCursor &cursor)
-{
- CodeModel::FunctionType result = CodeModel::Normal;
- switch (cursor.kind) {
- case CXCursor_Constructor:
- if (clang_CXXConstructor_isCopyConstructor(cursor) != 0)
- result = CodeModel::CopyConstructor;
- else if (clang_CXXConstructor_isMoveConstructor(cursor) != 0)
- result = CodeModel::MoveConstructor;
- else
- result = CodeModel::Constructor;
- break;
- case CXCursor_Destructor:
- result = CodeModel::Destructor;
- break;
- default:
- break;
- }
- return result;
-}
-
-FunctionModelItem BuilderPrivate::createMemberFunction(const CXCursor &cursor) const
-{
- const CodeModel::FunctionType functionType =
- m_currentFunctionType == CodeModel::Signal || m_currentFunctionType == CodeModel::Slot
- ? m_currentFunctionType // by annotation
- : functionTypeFromCursor(cursor);
- FunctionModelItem result = createFunction(cursor, functionType);
- result->setAccessPolicy(accessPolicy(clang_getCXXAccessSpecifier(cursor)));
- result->setConstant(clang_CXXMethod_isConst(cursor) != 0);
- result->setStatic(clang_CXXMethod_isStatic(cursor) != 0);
- result->setVirtual(clang_CXXMethod_isVirtual(cursor) != 0);
- result->setAbstract(clang_CXXMethod_isPureVirtual(cursor) != 0);
- return result;
-}
-
-// For CXCursor_Constructor, on endToken().
-void BuilderPrivate::qualifyConstructor(const CXCursor &cursor)
-{
- // Clang does not tell us whether a constructor is explicit, preventing it
- // from being used for implicit conversions. Try to guess whether a
- // constructor is explicit in the C++99 sense (1 parameter) by checking for
- // isConvertingConstructor() == 0. Fixme: The notion of "isConvertingConstructor"
- // should be used in the code model instead of "explicit"
- if (clang_CXXConstructor_isDefaultConstructor(cursor) == 0
- && m_currentFunction->arguments().size() == 1
- && clang_CXXConstructor_isCopyConstructor(cursor) == 0
- && clang_CXXConstructor_isMoveConstructor(cursor) == 0) {
- m_currentFunction->setExplicit(clang_CXXConstructor_isConvertingConstructor(cursor) == 0);
- }
-}
-
-TemplateParameterModelItem BuilderPrivate::createTemplateParameter(const CXCursor &cursor) const
-{
- return TemplateParameterModelItem(new _TemplateParameterModelItem(m_model, getCursorSpelling(cursor)));
-}
-
-TemplateParameterModelItem BuilderPrivate::createNonTypeTemplateParameter(const CXCursor &cursor) const
-{
- TemplateParameterModelItem result = createTemplateParameter(cursor);
- result->setType(createTypeInfoHelper(clang_getCursorType(cursor)));
- return result;
-}
-
-// CXCursor_VarDecl, CXCursor_FieldDecl cursors
-void BuilderPrivate::addField(const CXCursor &cursor)
-{
- VariableModelItem field(new _VariableModelItem(m_model, getCursorSpelling(cursor)));
- field->setAccessPolicy(accessPolicy(clang_getCXXAccessSpecifier(cursor)));
- field->setScope(m_scope);
- field->setType(createTypeInfo(cursor));
- field->setMutable(clang_CXXField_isMutable(cursor) != 0);
- m_currentField = field;
- m_scopeStack.back()->addVariable(field);
-}
-
-// Array helpers: Parse "a[2][4]" into a list of dimensions
-
-struct ArrayDimensionResult
-{
- QVector<QStringRef> dimensions;
- int position;
-};
-
-// Create qualified name "std::list<std::string>" -> ("std", "list<std::string>")
-static QStringList qualifiedName(const QString &t)
-{
- QStringList result;
- int end = t.indexOf(QLatin1Char('<'));
- if (end == -1)
- end = t.indexOf(QLatin1Char('('));
- if (end == -1)
- end = t.size();
- int lastPos = 0;
- while (true) {
- const int nextPos = t.indexOf(colonColon(), lastPos);
- if (nextPos < 0 || nextPos >= end)
- break;
- result.append(t.mid(lastPos, nextPos - lastPos));
- lastPos = nextPos + 2;
- }
- result.append(t.right(t.size() - lastPos));
- return result;
-}
-
-static bool isArrayType(CXTypeKind k)
-{
- return k == CXType_ConstantArray || k == CXType_IncompleteArray
- || k == CXType_VariableArray || k == CXType_DependentSizedArray;
-}
-
-static bool isPointerType(CXTypeKind k)
-{
- return k == CXType_Pointer || k == CXType_LValueReference || k == CXType_RValueReference;
-}
-
-bool BuilderPrivate::addTemplateInstantiationsRecursion(const CXType &type, TypeInfo *t) const
-{
- // Template arguments
- switch (type.kind) {
- case CXType_Elaborated:
- case CXType_Record:
- case CXType_Unexposed:
- if (const int numTemplateArguments = qMax(0, clang_Type_getNumTemplateArguments(type))) {
- for (unsigned tpl = 0; tpl < unsigned(numTemplateArguments); ++tpl) {
- const CXType argType = clang_Type_getTemplateArgumentAsType(type, tpl);
- // CXType_Invalid is returned when hitting on a specialization
- // of a non-type template (template <int v>).
- if (argType.kind == CXType_Invalid)
- return false;
- t->addInstantiation(createTypeInfoHelper(argType));
- }
- }
- break;
- default:
- break;
- }
- return true;
-}
-
-static void dummyTemplateArgumentHandler(int, const QStringRef &) {}
-
-void BuilderPrivate::addTemplateInstantiations(const CXType &type,
- QString *typeName,
- TypeInfo *t) const
-{
- // In most cases, for templates like "Vector<A>", Clang will give us the
- // arguments by recursing down the type. However this will fail for example
- // within template classes (for functions like the copy constructor):
- // template <class T>
- // class Vector {
- // Vector(const Vector&);
- // };
- // In that case, have TypeInfo parse the list from the spelling.
- // Finally, remove the list "<>" from the type name.
- const bool parsed = addTemplateInstantiationsRecursion(type, t)
- && !t->instantiations().isEmpty();
- if (!parsed)
- t->setInstantiations({});
- const QPair<int, int> pos = parsed
- ? parseTemplateArgumentList(*typeName, dummyTemplateArgumentHandler)
- : t->parseTemplateArgumentList(*typeName);
- if (pos.first != -1 && pos.second != -1 && pos.second > pos.first)
- typeName->remove(pos.first, pos.second - pos.first);
-}
-
-TypeInfo BuilderPrivate::createTypeInfoHelper(const CXType &type) const
-{
- if (type.kind == CXType_Pointer) { // Check for function pointers, first.
- const CXType pointeeType = clang_getPointeeType(type);
- const int argCount = clang_getNumArgTypes(pointeeType);
- if (argCount >= 0) {
- TypeInfo result = createTypeInfoHelper(clang_getResultType(pointeeType));
- result.setFunctionPointer(true);
- for (int a = 0; a < argCount; ++a)
- result.addArgument(createTypeInfoHelper(clang_getArgType(pointeeType, unsigned(a))));
- return result;
- }
- }
-
- TypeInfo typeInfo;
-
- CXType nestedType = type;
- for (; isArrayType(nestedType.kind); nestedType = clang_getArrayElementType(nestedType)) {
- const long long size = clang_getArraySize(nestedType);
- typeInfo.addArrayElement(size >= 0 ? QString::number(size) : QString());
- }
-
- TypeInfo::Indirections indirections;
- for (; isPointerType(nestedType.kind); nestedType = clang_getPointeeType(nestedType)) {
- switch (nestedType.kind) {
- case CXType_Pointer:
- indirections.prepend(clang_isConstQualifiedType(nestedType) != 0
- ? Indirection::ConstPointer : Indirection::Pointer);
- break;
- case CXType_LValueReference:
- typeInfo.setReferenceType(LValueReference);
- break;
- case CXType_RValueReference:
- typeInfo.setReferenceType(RValueReference);
- break;
- default:
- break;
- }
- }
- typeInfo.setIndirectionsV(indirections);
-
- typeInfo.setConstant(clang_isConstQualifiedType(nestedType) != 0);
- typeInfo.setVolatile(clang_isVolatileQualifiedType(nestedType) != 0);
-
- QString typeName = getTypeName(nestedType);
- while (TypeInfo::stripLeadingConst(&typeName)
- || TypeInfo::stripLeadingVolatile(&typeName)) {
- }
-
- // Obtain template instantiations if the name has '<' (thus excluding
- // typedefs like "std::string".
- if (typeName.contains(QLatin1Char('<')))
- addTemplateInstantiations(nestedType, &typeName, &typeInfo);
-
- typeInfo.setQualifiedName(qualifiedName(typeName));
- // 3320:CINDEX_LINKAGE int clang_getNumArgTypes(CXType T); function ptr types?
- typeInfo.simplifyStdType();
- return typeInfo;
-}
-
-TypeInfo BuilderPrivate::createTypeInfo(const CXType &type) const
-{
- TypeInfoHash::iterator it = m_typeInfoHash.find(type);
- if (it == m_typeInfoHash.end())
- it = m_typeInfoHash.insert(type, createTypeInfoHelper(type));
- return it.value();
-}
-
-void BuilderPrivate::addTypeDef(const CXCursor &cursor, const CXType &cxType)
-{
- const QString target = getCursorSpelling(cursor);
- TypeDefModelItem item(new _TypeDefModelItem(m_model, target));
- setFileName(cursor, item.data());
- item->setType(createTypeInfo(cxType));
- item->setScope(m_scope);
- m_scopeStack.back()->addTypeDef(item);
- m_cursorTypedefHash.insert(cursor, item);
-}
-
-void BuilderPrivate::startTemplateTypeAlias(const CXCursor &cursor)
-{
- const QString target = getCursorSpelling(cursor);
- m_currentTemplateTypeAlias.reset(new _TemplateTypeAliasModelItem(m_model, target));
- setFileName(cursor, m_currentTemplateTypeAlias.data());
- m_currentTemplateTypeAlias->setScope(m_scope);
-}
-
-void BuilderPrivate::endTemplateTypeAlias(const CXCursor &typeAliasCursor)
-{
- CXType type = clang_getTypedefDeclUnderlyingType(typeAliasCursor);
- // Usually "<elaborated>std::list<T>" or "<unexposed>Container1<T>",
- // as obtained with parser of PYSIDE-323
- if (type.kind == CXType_Unexposed || type.kind == CXType_Elaborated) {
- m_currentTemplateTypeAlias->setType(createTypeInfo(type));
- m_scopeStack.back()->addTemplateTypeAlias(m_currentTemplateTypeAlias);
- }
- m_currentTemplateTypeAlias.reset();
-}
-
-// extract an expression from the cursor via source
-// CXCursor_EnumConstantDecl, ParmDecl (a = Flag1 | Flag2)
-QString BuilderPrivate::cursorValueExpression(BaseVisitor *bv, const CXCursor &cursor) const
-{
- BaseVisitor::CodeSnippet snippet = bv->getCodeSnippet(cursor);
- const char *equalSign = std::find(snippet.first, snippet.second, '=');
- if (equalSign == snippet.second)
- return QString();
- ++equalSign;
- return QString::fromLocal8Bit(equalSign, int(snippet.second - equalSign)).trimmed();
-}
-
-// A hacky reimplementation of clang_EnumDecl_isScoped() for Clang < 5.0
-// which simply checks for a blank-delimited " class " keyword in the enum snippet.
-
-#define CLANG_NO_ENUMDECL_ISSCOPED \
- (CINDEX_VERSION_MAJOR == 0 && CINDEX_VERSION_MINOR < 43)
-
-#if CLANG_NO_ENUMDECL_ISSCOPED
-static const char *indexOf(const BaseVisitor::CodeSnippet &snippet, const char *needle)
-{
- const size_t snippetLength = snippet.first ? size_t(snippet.second - snippet.first) : 0;
- const size_t needleLength = strlen(needle);
- if (needleLength > snippetLength)
- return nullptr;
- for (const char *c = snippet.first, *end = snippet.second - needleLength; c < end; ++c) {
- if (memcmp(c, needle, needleLength) == 0)
- return c;
- }
- return nullptr;
-}
-
-long clang_EnumDecl_isScoped4(BaseVisitor *bv, const CXCursor &cursor)
-{
- BaseVisitor::CodeSnippet snippet = bv->getCodeSnippet(cursor);
- const char *classSpec = indexOf(snippet, "class");
- const bool isClass = classSpec && classSpec > snippet.first
- && isspace(*(classSpec - 1)) && isspace(*(classSpec + 5));
- return isClass ? 1 : 0;
-}
-#endif // CLANG_NO_ENUMDECL_ISSCOPED
-
-// Add a base class to the current class from CXCursor_CXXBaseSpecifier
-void BuilderPrivate::addBaseClass(const CXCursor &cursor)
-{
- // Note: spelling has "struct baseClass", use type
- QString baseClassName;
- const CXType inheritedType = clang_getCursorType(cursor);
- if (inheritedType.kind == CXType_Unexposed) {
- // The type is unexposed when the base class is a template type alias:
- // "class QItemSelection : public QList<X>" where QList is aliased to QVector.
- // Try to resolve via code model.
- TypeInfo info = createTypeInfo(inheritedType);
- auto parentScope = m_scopeStack.at(m_scopeStack.size() - 2); // Current is class.
- auto resolved = TypeInfo::resolveType(info, parentScope);
- if (resolved != info)
- baseClassName = resolved.toString();
- }
- if (baseClassName.isEmpty())
- baseClassName = getTypeName(inheritedType);
-
- const CXCursor declCursor = clang_getTypeDeclaration(inheritedType);
- const CursorClassHash::const_iterator it = m_cursorClassHash.constFind(declCursor);
- const CodeModel::AccessPolicy access = accessPolicy(clang_getCXXAccessSpecifier(cursor));
- if (it == m_cursorClassHash.constEnd()) {
- // Set unqualified name. This happens in cases like "class X : public std::list<...>"
- // "template<class T> class Foo : public T" and standard types like true_type, false_type.
- m_currentClass->addBaseClass(baseClassName, access);
- return;
- }
- // Completely qualify the class name by looking it up and taking its scope
- // plus the actual baseClass stripped off any scopes. Consider:
- // namespace std {
- // template <class T> class vector {};
- // namespace n {
- // class Foo : public vector<int> {};
- // }
- // }
- // should have "std::vector<int>" as base class (whereas the type of the base class is
- // "std::vector<T>").
- const QStringList &baseScope = it.value()->scope();
- if (!baseScope.isEmpty()) {
- const int lastSep = baseClassName.lastIndexOf(colonColon());
- if (lastSep >= 0)
- baseClassName.remove(0, lastSep + colonColon().size());
- baseClassName.prepend(colonColon());
- baseClassName.prepend(baseScope.join(colonColon()));
- }
- m_currentClass->addBaseClass(baseClassName, access);
-}
-
-static inline CXCursor definitionFromTypeRef(const CXCursor &typeRefCursor)
-{
- Q_ASSERT(typeRefCursor.kind == CXCursor_TypeRef);
- return clang_getTypeDeclaration(clang_getCursorType(typeRefCursor));
-}
-
-// Qualify function arguments or fields that are typedef'ed from another scope:
-// enum ConversionFlag {};
-// typedef QFlags<ConversionFlag> ConversionFlags;
-// class QTextCodec {
-// enum ConversionFlag {};
-// typedef QFlags<ConversionFlag> ConversionFlags;
-// struct ConverterState {
-// explicit ConverterState(ConversionFlags);
-// ^^ qualify to QTextCodec::ConversionFlags
-// ConversionFlags m_flags;
-// ^^ ditto
-
-template <class Item> // ArgumentModelItem, VariableModelItem
-void BuilderPrivate::qualifyTypeDef(const CXCursor &typeRefCursor, const QSharedPointer<Item> &item) const
-{
- TypeInfo type = item->type();
- if (type.qualifiedName().size() == 1) { // item's type is unqualified.
- const auto it = m_cursorTypedefHash.constFind(definitionFromTypeRef(typeRefCursor));
- if (it != m_cursorTypedefHash.constEnd() && !it.value()->scope().isEmpty()) {
- type.setQualifiedName(it.value()->scope() + type.qualifiedName());
- item->setType(type);
- }
- }
-}
-
-Builder::Builder()
-{
- d = new BuilderPrivate(this);
-}
-
-Builder::~Builder()
-{
- delete d;
-}
-
-static const char *cBaseName(const char *fileName)
-{
- const char *lastSlash = std::strrchr(fileName, '/');
-#ifdef Q_OS_WIN
- if (lastSlash == nullptr)
- lastSlash = std::strrchr(fileName, '\\');
-#endif
- return lastSlash != nullptr ? (lastSlash + 1) : fileName;
-}
-
-static inline bool cCompareFileName(const char *f1, const char *f2)
-{
-#ifdef Q_OS_WIN
- return _stricmp(f1, f2) == 0;
-#else
- return std::strcmp(f1, f2) == 0;
-#endif
-}
-
-#ifdef Q_OS_UNIX
-template<size_t N>
-static bool cStringStartsWith(const char *str, const char (&prefix)[N])
-{
- return std::strncmp(prefix, str, N - 1) == 0;
-}
-#endif
-
-static bool cStringStartsWith(const char *str, const QByteArray &prefix)
-{
- return std::strncmp(prefix.constData(), str, int(prefix.size())) == 0;
-}
-
-bool BuilderPrivate::visitHeader(const char *cFileName) const
-{
- // Resolve OpenGL typedefs although the header is considered a system header.
- const char *baseName = cBaseName(cFileName);
- if (cCompareFileName(baseName, "gl.h"))
- return true;
-#if defined(Q_OS_LINUX) || defined(Q_OS_MACOS)
- if (cStringStartsWith(cFileName, "/usr/include/stdint.h"))
- return true;
-#endif
-#ifdef Q_OS_LINUX
- if (cStringStartsWith(cFileName, "/usr/include/stdlib.h")
- || cStringStartsWith(cFileName, "/usr/include/sys/types.h")) {
- return true;
- }
-#endif // Q_OS_LINUX
-#ifdef Q_OS_MACOS
- // Parse the following system headers to get the correct typdefs for types like
- // int32_t, which are used in the macOS implementation of OpenGL framework.
- if (cCompareFileName(baseName, "gltypes.h")
- || cStringStartsWith(cFileName, "/usr/include/_types")
- || cStringStartsWith(cFileName, "/usr/include/_types")
- || cStringStartsWith(cFileName, "/usr/include/sys/_types")) {
- return true;
- }
-#endif // Q_OS_MACOS
- if (baseName) {
- for (const auto &systemInclude : m_systemIncludes) {
- if (systemInclude == baseName)
- return true;
- }
- }
- for (const auto &systemIncludePath : m_systemIncludePaths) {
- if (cStringStartsWith(cFileName, systemIncludePath))
- return true;
- }
- return false;
-}
-
-bool Builder::visitLocation(const CXSourceLocation &location) const
-{
- if (clang_Location_isInSystemHeader(location) == 0)
- return true;
- CXFile file; // void *
- unsigned line;
- unsigned column;
- unsigned offset;
- clang_getExpansionLocation(location, &file, &line, &column, &offset);
- const CXString cxFileName = clang_getFileName(file);
- // Has been observed to be 0 for invalid locations
- bool result = false;
- if (const char *cFileName = clang_getCString(cxFileName)) {
- result = d->visitHeader(cFileName);
- clang_disposeString(cxFileName);
- }
- return result;
-}
-
-void Builder::setSystemIncludes(const QByteArrayList &systemIncludes)
-{
- for (const auto &i : systemIncludes) {
- if (i.endsWith('/'))
- d->m_systemIncludePaths.append(i);
- else
- d->m_systemIncludes.append(i);
- }
-}
-
-FileModelItem Builder::dom() const
-{
- Q_ASSERT(!d->m_scopeStack.isEmpty());
- return qSharedPointerDynamicCast<_FileModelItem>(d->m_scopeStack.constFirst());
-}
-
-static QString msgOutOfOrder(const CXCursor &cursor, const char *expectedScope)
-{
- return getCursorKindName(cursor.kind) + QLatin1Char(' ')
- + getCursorSpelling(cursor) + QLatin1String(" encountered outside ")
- + QLatin1String(expectedScope) + QLatin1Char('.');
-}
-
-static CodeModel::ClassType codeModelClassTypeFromCursor(CXCursorKind kind)
-{
- CodeModel::ClassType result = CodeModel::Class;
- if (kind == CXCursor_UnionDecl)
- result = CodeModel::Union;
- else if (kind == CXCursor_StructDecl)
- result = CodeModel::Struct;
- return result;
-}
-
-static NamespaceType namespaceType(const CXCursor &cursor)
-{
- if (clang_Cursor_isAnonymous(cursor))
- return NamespaceType::Anonymous;
-#if CINDEX_VERSION_MAJOR > 0 || CINDEX_VERSION_MINOR >= 59
- if (clang_Cursor_isInlineNamespace(cursor))
- return NamespaceType::Inline;
-#endif
- return NamespaceType::Default;
-}
-
-static QString enumType(const CXCursor &cursor)
-{
- QString name = getCursorSpelling(cursor); // "enum Foo { v1, v2 };"
- if (name.isEmpty()) {
- // PYSIDE-1228: For "typedef enum { v1, v2 } Foo;", type will return
- // "Foo" as expected. Care must be taken to exclude real anonymous enums.
- name = getTypeName(clang_getCursorType(cursor));
- if (name.contains(QLatin1String("(anonymous")))
- name.clear();
- }
- return name;
-}
-
-BaseVisitor::StartTokenResult Builder::startToken(const CXCursor &cursor)
-{
- switch (cursor.kind) {
- case CXCursor_CXXAccessSpecifier:
- d->m_currentFunctionType = CodeModel::Normal;
- break;
- case CXCursor_AnnotateAttr: {
- const QString annotation = getCursorSpelling(cursor);
- if (annotation == QLatin1String("qt_slot"))
- d->m_currentFunctionType = CodeModel::Slot;
- else if (annotation == QLatin1String("qt_signal"))
- d->m_currentFunctionType = CodeModel::Signal;
- else
- d->m_currentFunctionType = CodeModel::Normal;
- }
- break;
- case CXCursor_CXXBaseSpecifier:
- if (d->m_currentClass.isNull()) {
- const Diagnostic d(msgOutOfOrder(cursor, "class"), cursor, CXDiagnostic_Error);
- qWarning() << d;
- appendDiagnostic(d);
- return Error;
- }
- d->addBaseClass(cursor);
- break;
- case CXCursor_ClassDecl:
- case CXCursor_UnionDecl:
- case CXCursor_StructDecl:
- if (clang_isCursorDefinition(cursor) == 0)
- return Skip;
- if (!d->addClass(cursor, codeModelClassTypeFromCursor(cursor.kind)))
- return Error;
- break;
- case CXCursor_ClassTemplate:
- case CXCursor_ClassTemplatePartialSpecialization:
- if (clang_isCursorDefinition(cursor) == 0)
- return Skip;
- d->addClass(cursor, CodeModel::Class);
- d->m_currentClass->setName(d->m_currentClass->name() + templateBrackets());
- d->m_scope.back() += templateBrackets();
- break;
- case CXCursor_EnumDecl: {
- QString name = enumType(cursor);
- EnumKind kind = CEnum;
- if (name.isEmpty()) {
- kind = AnonymousEnum;
- name = QStringLiteral("enum_") + QString::number(++d->m_anonymousEnumCount);
-#if !CLANG_NO_ENUMDECL_ISSCOPED
- } else if (clang_EnumDecl_isScoped(cursor) != 0) {
-#else
- } else if (clang_EnumDecl_isScoped4(this, cursor) != 0) {
-#endif
- kind = EnumClass;
- }
- d->m_currentEnum.reset(new _EnumModelItem(d->m_model, name));
- setFileName(cursor, d->m_currentEnum.data());
- d->m_currentEnum->setScope(d->m_scope);
- d->m_currentEnum->setEnumKind(kind);
- d->m_currentEnum->setSigned(isSigned(clang_getEnumDeclIntegerType(cursor).kind));
- if (!qSharedPointerDynamicCast<_ClassModelItem>(d->m_scopeStack.back()).isNull())
- d->m_currentEnum->setAccessPolicy(accessPolicy(clang_getCXXAccessSpecifier(cursor)));
- }
- break;
- case CXCursor_EnumConstantDecl: {
- const QString name = getCursorSpelling(cursor);
- if (d->m_currentEnum.isNull()) {
- const Diagnostic d(msgOutOfOrder(cursor, "enum"), cursor, CXDiagnostic_Error);
- qWarning() << d;
- appendDiagnostic(d);
- return Error;
- }
- EnumValue enumValue;
- if (d->m_currentEnum->isSigned())
- enumValue.setValue(clang_getEnumConstantDeclValue(cursor));
- else
- enumValue.setUnsignedValue(clang_getEnumConstantDeclUnsignedValue(cursor));
- EnumeratorModelItem enumConstant(new _EnumeratorModelItem(d->m_model, name));
- enumConstant->setStringValue(d->cursorValueExpression(this, cursor));
- enumConstant->setValue(enumValue);
- d->m_currentEnum->addEnumerator(enumConstant);
- }
- break;
- case CXCursor_VarDecl:
- // static class members are seen as CXCursor_VarDecl
- if (!d->m_currentClass.isNull() && isClassCursor(clang_getCursorSemanticParent(cursor))) {
- d->addField(cursor);
- d->m_currentField->setStatic(true);
- }
- break;
- case CXCursor_FieldDecl:
- d->addField(cursor);
- break;
-#if CINDEX_VERSION_MAJOR > 0 || CINDEX_VERSION_MINOR >= 37 // Clang 4.0
- case CXCursor_FriendDecl:
- return Skip;
-#endif
- case CXCursor_Constructor:
- case CXCursor_Destructor: // Note: Also use clang_CXXConstructor_is..Constructor?
- case CXCursor_CXXMethod:
- case CXCursor_ConversionFunction:
- // Skip inline member functions outside class, only go by declarations inside class
- if (!withinClassDeclaration(cursor))
- return Skip;
- d->m_currentFunction = d->createMemberFunction(cursor);
- d->m_scopeStack.back()->addFunction(d->m_currentFunction);
- break;
- // Not fully supported, currently, seen as normal function
- // Note: May appear inside class (member template) or outside (free template).
- case CXCursor_FunctionTemplate: {
- const CXCursor semParent = clang_getCursorSemanticParent(cursor);
- if (isClassCursor(semParent)) {
- if (semParent == clang_getCursorLexicalParent(cursor)) {
- d->m_currentFunction = d->createMemberFunction(cursor);
- d->m_scopeStack.back()->addFunction(d->m_currentFunction);
- break;
- }
- return Skip; // inline member functions outside class
- }
- }
- Q_FALLTHROUGH(); // fall through to free template function.
- case CXCursor_FunctionDecl:
- d->m_currentFunction = d->createFunction(cursor);
- d->m_scopeStack.back()->addFunction(d->m_currentFunction);
- break;
- case CXCursor_Namespace: {
- const auto type = namespaceType(cursor);
- if (type == NamespaceType::Anonymous)
- return Skip;
- const QString name = getCursorSpelling(cursor);
- const NamespaceModelItem parentNamespaceItem = qSharedPointerDynamicCast<_NamespaceModelItem>(d->m_scopeStack.back());
- if (parentNamespaceItem.isNull()) {
- const QString message = msgOutOfOrder(cursor, "namespace")
- + QLatin1String(" (current scope: ") + d->m_scopeStack.back()->name() + QLatin1Char(')');
- const Diagnostic d(message, cursor, CXDiagnostic_Error);
- qWarning() << d;
- appendDiagnostic(d);
- return Error;
- }
- // Treat namespaces separately to allow for extending namespaces
- // in subsequent modules.
- NamespaceModelItem namespaceItem = parentNamespaceItem->findNamespace(name);
- namespaceItem.reset(new _NamespaceModelItem(d->m_model, name));
- setFileName(cursor, namespaceItem.data());
- namespaceItem->setScope(d->m_scope);
- namespaceItem->setType(type);
- parentNamespaceItem->addNamespace(namespaceItem);
- d->pushScope(namespaceItem);
- }
- break;
- case CXCursor_ParmDecl:
- // Skip in case of nested CXCursor_ParmDecls in case one parameter is a function pointer
- // and function pointer typedefs.
- if (d->m_currentArgument.isNull() && !d->m_currentFunction.isNull()) {
- const QString name = getCursorSpelling(cursor);
- d->m_currentArgument.reset(new _ArgumentModelItem(d->m_model, name));
- d->m_currentArgument->setType(d->createTypeInfo(cursor));
- d->m_currentFunction->addArgument(d->m_currentArgument);
- QString defaultValueExpression = d->cursorValueExpression(this, cursor);
- if (!defaultValueExpression.isEmpty()) {
- d->m_currentArgument->setDefaultValueExpression(defaultValueExpression);
- d->m_currentArgument->setDefaultValue(true);
- }
- } else {
- return Skip;
- }
- break;
- case CXCursor_TemplateTypeParameter:
- case CXCursor_NonTypeTemplateParameter: {
- const TemplateParameterModelItem tItem = cursor.kind == CXCursor_TemplateTemplateParameter
- ? d->createTemplateParameter(cursor) : d->createNonTypeTemplateParameter(cursor);
- // Apply to function/member template?
- if (!d->m_currentFunction.isNull()) {
- d->m_currentFunction->setTemplateParameters(d->m_currentFunction->templateParameters() << tItem);
- } else if (!d->m_currentTemplateTypeAlias.isNull()) {
- d->m_currentTemplateTypeAlias->addTemplateParameter(tItem);
- } else if (!d->m_currentClass.isNull()) { // Apply to class
- const QString &tplParmName = tItem->name();
- if (Q_UNLIKELY(!insertTemplateParameterIntoClassName(tplParmName, d->m_currentClass)
- || !insertTemplateParameterIntoClassName(tplParmName, &d->m_scope.back()))) {
- const QString message = QStringLiteral("Error inserting template parameter \"") + tplParmName
- + QStringLiteral("\" into ") + d->m_currentClass->name();
- const Diagnostic d(message, cursor, CXDiagnostic_Error);
- qWarning() << d;
- appendDiagnostic(d);
- return Error;
- }
- d->m_currentClass->setTemplateParameters(d->m_currentClass->templateParameters() << tItem);
- }
- }
- break;
- case CXCursor_TypeAliasTemplateDecl:
- d->startTemplateTypeAlias(cursor);
- break;
- case CXCursor_TypeAliasDecl: // May contain nested CXCursor_TemplateTypeParameter
- if (d->m_currentTemplateTypeAlias.isNull()) {
- const CXType type = clang_getCanonicalType(clang_getCursorType(cursor));
- if (type.kind > CXType_Unexposed)
- d->addTypeDef(cursor, type);
- return Skip;
- } else {
- d->endTemplateTypeAlias(cursor);
- }
- break;
- case CXCursor_TypedefDecl: {
- auto underlyingType = clang_getTypedefDeclUnderlyingType(cursor);
- d->addTypeDef(cursor, underlyingType);
- // For "typedef enum/struct {} Foo;", skip the enum/struct
- // definition nested into the typedef (PYSIDE-1228).
- if (underlyingType.kind == CXType_Elaborated)
- return Skip;
- }
- break;
- case CXCursor_TypeRef:
- if (!d->m_currentFunction.isNull()) {
- if (d->m_currentArgument.isNull())
- d->qualifyTypeDef(cursor, d->m_currentFunction); // return type
- else
- d->qualifyTypeDef(cursor, d->m_currentArgument);
- } else if (!d->m_currentField.isNull()) {
- d->qualifyTypeDef(cursor, d->m_currentField);
- }
- break;
- case CXCursor_CXXFinalAttr:
- if (!d->m_currentFunction.isNull())
- d->m_currentFunction->setFinal(true);
- else if (!d->m_currentClass.isNull())
- d->m_currentClass->setFinal(true);
- break;
- case CXCursor_CXXOverrideAttr:
- if (!d->m_currentFunction.isNull())
- d->m_currentFunction->setOverride(true);
- break;
- default:
- break;
- }
- return BaseVisitor::Recurse;
-}
-
-bool Builder::endToken(const CXCursor &cursor)
-{
- switch (cursor.kind) {
- case CXCursor_UnionDecl:
- case CXCursor_ClassDecl:
- case CXCursor_StructDecl:
- case CXCursor_ClassTemplate:
- case CXCursor_ClassTemplatePartialSpecialization:
- d->popScope();
- // Continue in outer class after leaving inner class?
- if (ClassModelItem lastClass = qSharedPointerDynamicCast<_ClassModelItem>(d->m_scopeStack.back()))
- d->m_currentClass = lastClass;
- else
- d->m_currentClass.clear();
- d->m_currentFunctionType = CodeModel::Normal;
- break;
- case CXCursor_EnumDecl:
- // Add enum only if values were encountered, otherwise assume it
- // is a forward declaration of an enum class.
- if (!d->m_currentEnum.isNull() && d->m_currentEnum->hasValues())
- d->m_scopeStack.back()->addEnum(d->m_currentEnum);
- d->m_currentEnum.clear();
- break;
- case CXCursor_VarDecl:
- case CXCursor_FieldDecl:
- d->m_currentField.clear();
- break;
- case CXCursor_Constructor:
- d->qualifyConstructor(cursor);
- d->m_currentFunction.clear();
- break;
- case CXCursor_Destructor:
- case CXCursor_CXXMethod:
- case CXCursor_FunctionDecl:
- case CXCursor_FunctionTemplate:
- d->m_currentFunction.clear();
- break;
- case CXCursor_Namespace:
- d->popScope();
- break;
- case CXCursor_ParmDecl:
- d->m_currentArgument.clear();
- break;
- case CXCursor_TypeAliasTemplateDecl:
- d->m_currentTemplateTypeAlias.reset();
- break;
- default:
- break;
- }
- return true;
-}
-
-} // namespace clang
diff --git a/sources/shiboken2/ApiExtractor/clangparser/clangbuilder.h b/sources/shiboken2/ApiExtractor/clangparser/clangbuilder.h
deleted file mode 100644
index dc37dff0f..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/clangbuilder.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CLANGBUILDER_H
-#define CLANGBUILDER_H
-
-#include "clangparser.h"
-
-#include <codemodel_fwd.h>
-
-namespace clang {
-
-class BuilderPrivate;
-
-class Builder : public BaseVisitor {
-public:
- Q_DISABLE_COPY(Builder)
-
- Builder();
- ~Builder();
-
- void setSystemIncludes(const QByteArrayList &systemIncludes);
-
- bool visitLocation(const CXSourceLocation &location) const override;
-
- StartTokenResult startToken(const CXCursor &cursor) override;
- bool endToken(const CXCursor &cursor) override;
-
- FileModelItem dom() const;
-
-private:
- BuilderPrivate *d;
-};
-
-} // namespace clang
-
-#endif // CLANGBUILDER_H
diff --git a/sources/shiboken2/ApiExtractor/clangparser/clangdebugutils.cpp b/sources/shiboken2/ApiExtractor/clangparser/clangdebugutils.cpp
deleted file mode 100644
index d6915daab..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/clangdebugutils.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "clangdebugutils.h"
-#include "clangutils.h"
-
-#include <QtCore/QDebug>
-#include <QtCore/QString>
-
-#include <string.h>
-
-#ifndef QT_NO_DEBUG_STREAM
-
-#ifdef Q_OS_WIN
-const char pathSep = '\\';
-#else
-const char pathSep = '/';
-#endif
-
-static const char *baseName(const char *fileName)
-{
- const char *b = strrchr(fileName, pathSep);
- return b ? b + 1 : fileName;
-}
-
-QDebug operator<<(QDebug s, const CXString &cs)
-{
- s << clang_getCString(cs);
- return s;
-}
-
-QDebug operator<<(QDebug s, CXCursorKind cursorKind) // Enum
-{
- const CXString kindName = clang_getCursorKindSpelling(cursorKind);
- s << kindName;
- clang_disposeString(kindName);
- return s;
-}
-
-static const char *accessSpecsStrings[]
-{
- // CX_CXXInvalidAccessSpecifier, CX_CXXPublic, CX_CXXProtected, CX_CXXPrivate
- "invalid", "public", "protected", "private"
-};
-
-QDebug operator<<(QDebug s, CX_CXXAccessSpecifier ac)
-{
- s << accessSpecsStrings[ac];
- return s;
-}
-
-QDebug operator<<(QDebug s, const CXType &t)
-{
- CXString typeSpelling = clang_getTypeSpelling(t);
- s << typeSpelling;
- clang_disposeString(typeSpelling);
- return s;
-}
-
-QDebug operator<<(QDebug s, const CXCursor &cursor)
-{
- QDebugStateSaver saver(s);
- s.nospace();
- s.noquote();
- const CXCursorKind kind = clang_getCursorKind(cursor);
- s << kind;
- if (kind >= CXCursor_FirstInvalid && kind <= CXCursor_LastInvalid)
- return s;
- const CXType type = clang_getCursorType(cursor);
- switch (kind) {
- case CXCursor_CXXAccessSpecifier:
- s << ' ' << clang_getCXXAccessSpecifier(cursor);
- break;
- case CXCursor_CXXBaseSpecifier:
- s << ", inherits=\"" << clang::getCursorSpelling(clang_getTypeDeclaration(type)) << '"';
- break;
- case CXCursor_CXXMethod:
- case CXCursor_FunctionDecl:
- case CXCursor_ConversionFunction:
- s << ", result type=\"" << clang_getCursorResultType(cursor) << '"';
- break;
- case CXCursor_TypedefDecl:
- s << ", underlyingType=\"" << clang_getTypedefDeclUnderlyingType(cursor) << '"';
- break;
- default:
- break;
- }
-
- if (type.kind != CXType_Invalid)
- s << ", type=\"" << type << '"';
- if (clang_Cursor_hasAttrs(cursor))
- s << ", [attrs]";
-
- const QString cursorSpelling = clang::getCursorSpelling(cursor);
- if (!cursorSpelling.isEmpty())
- s << ", spelling=\"" << cursorSpelling << '"';
- CXString cursorDisplay = clang_getCursorDisplayName(cursor);
- if (const char *dpy = clang_getCString(cursorDisplay)) {
- const QString display = QString::fromUtf8(dpy);
- if (display != cursorSpelling)
- s << ", display=\"" << dpy << '"';
- }
- clang_disposeString(cursorDisplay);
- return s;
-}
-
-QDebug operator<<(QDebug s, const CXSourceLocation &location)
-{
- QDebugStateSaver saver(s);
- s.nospace();
- CXFile file; // void *
- unsigned line;
- unsigned column;
- unsigned offset;
- clang_getExpansionLocation(location, &file, &line, &column, &offset);
- const CXString cxFileName = clang_getFileName(file);
- // Has been observed to be 0 for invalid locations
- if (const char *cFileName = clang_getCString(cxFileName))
- s << baseName(cFileName) << ':';
- s << line << ':' << column;
- clang_disposeString(cxFileName);
- return s;
-}
-
-#endif // !QT_NO_DEBUG_STREAM
diff --git a/sources/shiboken2/ApiExtractor/clangparser/clangdebugutils.h b/sources/shiboken2/ApiExtractor/clangparser/clangdebugutils.h
deleted file mode 100644
index 2bbe526f7..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/clangdebugutils.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CLANGDEBUGUTILS_H
-#define CLANGDEBUGUTILS_H
-
-#include <QtCore/QtGlobal>
-
-#include <clang-c/Index.h>
-
-QT_FORWARD_DECLARE_CLASS(QDebug)
-QT_FORWARD_DECLARE_CLASS(QString)
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug s, const CXString &cs);
-QDebug operator<<(QDebug s, CXCursorKind cursorKind);
-QDebug operator<<(QDebug s, CX_CXXAccessSpecifier ac);
-QDebug operator<<(QDebug s, const CXType &t);
-QDebug operator<<(QDebug s, const CXCursor &cursor);
-QDebug operator<<(QDebug s, const CXSourceLocation &location);
-#endif // !QT_NO_DEBUG_STREAM
-
-#endif // CLANGDEBUGUTILS_H
diff --git a/sources/shiboken2/ApiExtractor/clangparser/clangparser.cpp b/sources/shiboken2/ApiExtractor/clangparser/clangparser.cpp
deleted file mode 100644
index 6303d09e5..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/clangparser.cpp
+++ /dev/null
@@ -1,266 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "clangparser.h"
-#include "clangutils.h"
-#include "clangdebugutils.h"
-#include "compilersupport.h"
-
-#include <QtCore/QByteArrayList>
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QScopedArrayPointer>
-#include <QtCore/QString>
-
-namespace clang {
-
-SourceFileCache::Snippet SourceFileCache::getCodeSnippet(const CXCursor &cursor)
-{
- Snippet result(nullptr, nullptr);
- const SourceRange range = getCursorRange(cursor);
- if (range.first.file.isEmpty() || range.second.file != range.first.file)
- return result;
- FileBufferCache::Iterator it = m_fileBufferCache.find(range.first.file);
- if (it == m_fileBufferCache.end()) {
- QFile file(range.first.file);
- if (!file.open(QIODevice::ReadOnly)) {
- qWarning().noquote().nospace()
- << "Can't open " << QDir::toNativeSeparators(range.first.file)
- << ": " << file.errorString();
- return result;
- }
- it = m_fileBufferCache.insert(range.first.file, file.readAll());
- }
-
- const unsigned pos = range.first.offset;
- const unsigned end = range.second.offset;
- const QByteArray &contents = it.value();
- if (end >= unsigned(contents.size())) {
- qWarning().noquote().nospace() << "Range end " << end << " is above size of "
- << range.first.file << " (" << contents.size() << ')';
- return result;
- }
- result.first = contents.constData() + pos;
- result.second = contents.constData() + end;
- return result;
-}
-
-BaseVisitor::BaseVisitor() = default;
-BaseVisitor::~BaseVisitor() = default;
-
-bool BaseVisitor::visitLocation(const CXSourceLocation &location) const
-{
- return clang_Location_isFromMainFile(location) != 0;
-}
-
-BaseVisitor::StartTokenResult BaseVisitor::cbHandleStartToken(const CXCursor &cursor)
-{
- switch (cursor.kind) {
- default:
- break;
- }
-
- return startToken(cursor);
-}
-
-bool BaseVisitor::cbHandleEndToken(const CXCursor &cursor, StartTokenResult startResult)
-{
- const bool result = startResult != Recurse || endToken(cursor);
- switch (cursor.kind) {
- default:
- break;
- }
-
- return result;
-}
-
-BaseVisitor::CodeSnippet BaseVisitor::getCodeSnippet(const CXCursor &cursor)
-{
- CodeSnippet result = m_fileCache.getCodeSnippet(cursor);
- if (result.first == nullptr)
- appendDiagnostic(Diagnostic(QStringLiteral("Unable to retrieve code snippet."), cursor, CXDiagnostic_Error));
- return result;
-}
-
-QString BaseVisitor::getCodeSnippetString(const CXCursor &cursor)
-{
- CodeSnippet result = m_fileCache.getCodeSnippet(cursor);
- return result.first != nullptr
- ? QString::fromUtf8(result.first, int(result.second - result.first))
- : QString();
-}
-
-static CXChildVisitResult
- visitorCallback(CXCursor cursor, CXCursor /* parent */, CXClientData clientData)
-{
- auto *bv = reinterpret_cast<BaseVisitor *>(clientData);
-
- const CXSourceLocation location = clang_getCursorLocation(cursor);
- if (!bv->visitLocation(location))
- return CXChildVisit_Continue;
-
- const BaseVisitor::StartTokenResult startResult = bv->cbHandleStartToken(cursor);
- switch (startResult) {
- case clang::BaseVisitor::Error:
- return CXChildVisit_Break;
- case clang::BaseVisitor::Skip:
- break;
- case clang::BaseVisitor::Recurse:
- clang_visitChildren(cursor, visitorCallback, clientData);
- break;
- }
-
- if (!bv->cbHandleEndToken(cursor, startResult))
- return CXChildVisit_Break;
-
- return CXChildVisit_Continue;
-}
-
-BaseVisitor::Diagnostics BaseVisitor::diagnostics() const
-{
- return m_diagnostics;
-}
-
-void BaseVisitor::setDiagnostics(const Diagnostics &d)
-{
- m_diagnostics = d;
-}
-
-void BaseVisitor::appendDiagnostic(const Diagnostic &d)
-{
- m_diagnostics.append(d);
-}
-
-static inline const char **byteArrayListToFlatArgV(const QByteArrayList &bl)
-{
- const char **result = new const char *[bl.size() + 1];
- result[bl.size()] = nullptr;
- std::transform(bl.cbegin(), bl.cend(), result,
- [] (const QByteArray &a) { return a.constData(); });
- return result;
-}
-
-static QByteArray msgCreateTranslationUnit(const QByteArrayList &clangArgs, unsigned flags)
-{
- QByteArray result = "clang_parseTranslationUnit2(0x";
- result += QByteArray::number(flags, 16);
- const int count = clangArgs.size();
- result += ", cmd[" + QByteArray::number(count) + "]=";
- for (int i = 0; i < count; ++i) {
- const QByteArray &arg = clangArgs.at(i);
- if (i)
- result += ' ';
- const bool quote = arg.contains(' ') || arg.contains('(');
- if (quote)
- result += '"';
- result += arg;
- if (quote)
- result += '"';
- }
- result += ')';
- return result;
-}
-
-static CXTranslationUnit createTranslationUnit(CXIndex index,
- const QByteArrayList &args,
- unsigned flags = 0)
-{
- // courtesy qdoc
- const unsigned defaultFlags = CXTranslationUnit_SkipFunctionBodies
- | CXTranslationUnit_Incomplete;
-
- static const QByteArrayList defaultArgs = {
-#ifndef Q_OS_WIN
- "-fPIC",
-#endif
-#ifdef Q_OS_MACOS
- "-Wno-expansion-to-defined", // Workaround for warnings in Darwin stdlib, see
- // https://github.com/darlinghq/darling/issues/204
-#endif
- "-Wno-constant-logical-operand"
- };
-
- const QByteArrayList clangArgs = emulatedCompilerOptions() + defaultArgs + args;
- QScopedArrayPointer<const char *> argv(byteArrayListToFlatArgV(clangArgs));
- qDebug().noquote().nospace() << msgCreateTranslationUnit(clangArgs, flags);
-
- CXTranslationUnit tu;
- CXErrorCode err = clang_parseTranslationUnit2(index, nullptr, argv.data(),
- clangArgs.size(), nullptr, 0,
- defaultFlags | flags, &tu);
- if (err || !tu) {
- qWarning().noquote().nospace() << "Could not parse "
- << clangArgs.constLast().constData() << ", error code: " << err;
- return nullptr;
- }
- return tu;
-}
-
-/* clangFlags are flags to clang_parseTranslationUnit2() such as
- * CXTranslationUnit_KeepGoing (from CINDEX_VERSION_MAJOR/CINDEX_VERSION_MINOR 0.35)
- */
-
-bool parse(const QByteArrayList &clangArgs, unsigned clangFlags, BaseVisitor &bv)
-{
- CXIndex index = clang_createIndex(0 /* excludeDeclarationsFromPCH */,
- 1 /* displayDiagnostics */);
- if (!index) {
- qWarning() << "clang_createIndex() failed!";
- return false;
- }
-
- CXTranslationUnit translationUnit = createTranslationUnit(index, clangArgs, clangFlags);
- if (!translationUnit)
- return false;
-
- CXCursor rootCursor = clang_getTranslationUnitCursor(translationUnit);
-
- clang_visitChildren(rootCursor, visitorCallback, reinterpret_cast<CXClientData>(&bv));
-
- QVector<Diagnostic> diagnostics = getDiagnostics(translationUnit);
- diagnostics.append(bv.diagnostics());
- bv.setDiagnostics(diagnostics);
-
- const bool ok = maxSeverity(diagnostics) < CXDiagnostic_Error;
- if (!ok) {
- QDebug debug = qWarning();
- debug.noquote();
- debug.nospace();
- debug << "Errors in "
- << QDir::toNativeSeparators(QFile::decodeName(clangArgs.constLast())) << ":\n";
- for (const Diagnostic &diagnostic : qAsConst(diagnostics))
- debug << diagnostic << '\n';
- }
-
- clang_disposeTranslationUnit(translationUnit);
- clang_disposeIndex(index);
- return ok;
-}
-
-} // namespace clang
diff --git a/sources/shiboken2/ApiExtractor/clangparser/clangparser.h b/sources/shiboken2/ApiExtractor/clangparser/clangparser.h
deleted file mode 100644
index 4248be853..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/clangparser.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CLANGPARSER_H
-#define CLANGPARSER_H
-
-#include <clang-c/Index.h>
-
-#include <QtCore/QByteArrayList>
-#include <QtCore/QHash>
-#include <QtCore/QPair>
-#include <QtCore/QString>
-#include <QtCore/QVector>
-
-namespace clang {
-
-struct Diagnostic;
-
-class SourceFileCache {
-public:
- using Snippet = QPair<const char *, const char *>;
-
- Snippet getCodeSnippet(const CXCursor &cursor);
-
-private:
- using FileBufferCache = QHash<QString, QByteArray>;
-
- FileBufferCache m_fileBufferCache;
-};
-
-class BaseVisitor {
- Q_DISABLE_COPY(BaseVisitor)
-public:
- using Diagnostics = QVector<Diagnostic>;
- using CodeSnippet = SourceFileCache::Snippet;
-
- enum StartTokenResult { Error, Skip, Recurse };
-
- BaseVisitor();
- virtual ~BaseVisitor();
-
- // Whether location should be visited.
- // defaults to clang_Location_isFromMainFile()
- virtual bool visitLocation(const CXSourceLocation &location) const;
-
- virtual StartTokenResult startToken(const CXCursor &cursor) = 0;
- virtual bool endToken(const CXCursor &cursor) = 0;
-
- StartTokenResult cbHandleStartToken(const CXCursor &cursor);
- bool cbHandleEndToken(const CXCursor &cursor, StartTokenResult startResult);
-
- CodeSnippet getCodeSnippet(const CXCursor &cursor);
- QString getCodeSnippetString(const CXCursor &cursor);
-
- Diagnostics diagnostics() const;
- void setDiagnostics(const Diagnostics &d);
- void appendDiagnostic(const Diagnostic &d);
-
-private:
- SourceFileCache m_fileCache;
- Diagnostics m_diagnostics;
-};
-
-bool parse(const QByteArrayList &clangArgs, unsigned clangFlags, BaseVisitor &ctx);
-
-} // namespace clang
-
-#endif // !CLANGPARSER_H
diff --git a/sources/shiboken2/ApiExtractor/clangparser/clangutils.cpp b/sources/shiboken2/ApiExtractor/clangparser/clangutils.cpp
deleted file mode 100644
index df2476100..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/clangutils.cpp
+++ /dev/null
@@ -1,276 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "clangutils.h"
-
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QHashFunctions>
-#include <QtCore/QProcess>
-
-bool operator==(const CXCursor &c1, const CXCursor &c2)
-{
- return c1.kind == c2.kind
- && c1.xdata == c2.xdata
- && std::equal(c1.data, c1.data + sizeof(c1.data) / sizeof(c1.data[0]), c2.data);
-}
-
-QtCompatHashFunctionType qHash(const CXCursor &c, QtCompatHashFunctionType seed)
-{
- return qHash(c.kind) ^ qHash(c.xdata) ^ qHash(c.data[0])
- ^ qHash(c.data[1]) ^ qHash(c.data[2]) ^ seed;
-}
-
-bool operator==(const CXType &t1, const CXType &t2)
-{
- return t1.kind == t2.kind && t1.data[0] == t2.data[0]
- && t1.data[1] == t2.data[1];
-}
-
-QtCompatHashFunctionType qHash(const CXType &ct, QtCompatHashFunctionType seed)
-{
- return QtCompatHashFunctionType(ct.kind) ^ QtCompatHashFunctionType(0xFFFFFFFF & quintptr(ct.data[0]))
- ^ QtCompatHashFunctionType(0xFFFFFFFF & quintptr(ct.data[1])) ^ seed;
-}
-
-namespace clang {
-
-SourceLocation getExpansionLocation(const CXSourceLocation &location)
-{
- SourceLocation result;
- CXFile file; // void *
- clang_getExpansionLocation(location, &file, &result.line, &result.column, &result.offset);
- const CXString cxFileName = clang_getFileName(file);
- // Has been observed to be 0 for invalid locations
- if (const char *cFileName = clang_getCString(cxFileName))
- result.file = QString::fromUtf8(cFileName);
- clang_disposeString(cxFileName);
- return result;
-}
-
-SourceLocation getCursorLocation(const CXCursor &cursor)
-{
- const CXSourceRange extent = clang_getCursorExtent(cursor);
- return getExpansionLocation(clang_getRangeStart(extent));
-}
-
-CXString getFileNameFromLocation(const CXSourceLocation &location)
-{
- CXFile file;
- unsigned line;
- unsigned column;
- unsigned offset;
- clang_getExpansionLocation(location, &file, &line, &column, &offset);
- return clang_getFileName(file);
-}
-
-SourceRange getCursorRange(const CXCursor &cursor)
-{
- const CXSourceRange extent = clang_getCursorExtent(cursor);
- return qMakePair(getExpansionLocation(clang_getRangeStart(extent)),
- getExpansionLocation(clang_getRangeEnd(extent)));
-}
-
-QString getCursorKindName(CXCursorKind cursorKind)
-{
- CXString kindName = clang_getCursorKindSpelling(cursorKind);
- const QString result = QString::fromUtf8(clang_getCString(kindName));
- clang_disposeString(kindName);
- return result;
-}
-
-QString getCursorSpelling(const CXCursor &cursor)
-{
- CXString cursorSpelling = clang_getCursorSpelling(cursor);
- const QString result = QString::fromUtf8(clang_getCString(cursorSpelling));
- clang_disposeString(cursorSpelling);
- return result;
-}
-
-QString getCursorDisplayName(const CXCursor &cursor)
-{
- CXString displayName = clang_getCursorDisplayName(cursor);
- const QString result = QString::fromUtf8(clang_getCString(displayName));
- clang_disposeString(displayName);
- return result;
-}
-
-QString getTypeName(const CXType &type)
-{
- CXString typeSpelling = clang_getTypeSpelling(type);
- const QString result = QString::fromUtf8(clang_getCString(typeSpelling));
- clang_disposeString(typeSpelling);
- return result;
-}
-
-Diagnostic::Diagnostic(const QString &m, const CXCursor &c, CXDiagnosticSeverity s)
- : message(m), location(getCursorLocation(c)), source(Other), severity(s)
-{
-}
-
-Diagnostic Diagnostic::fromCXDiagnostic(CXDiagnostic cd)
-{
- Diagnostic result;
- result.source = Clang;
- CXString spelling = clang_getDiagnosticSpelling(cd);
- result.message = QString::fromUtf8(clang_getCString(spelling));
- clang_disposeString(spelling);
- result.severity = clang_getDiagnosticSeverity(cd);
- result.location = getExpansionLocation(clang_getDiagnosticLocation(cd));
-
- CXDiagnosticSet childDiagnostics = clang_getChildDiagnostics(cd);
- if (const unsigned childCount = clang_getNumDiagnosticsInSet(childDiagnostics)) {
- result.childMessages.reserve(int(childCount));
- const unsigned format = clang_defaultDiagnosticDisplayOptions();
- for (unsigned i = 0; i < childCount; ++i) {
- CXDiagnostic childDiagnostic = clang_getDiagnosticInSet(childDiagnostics, i);
- CXString cdm = clang_formatDiagnostic(childDiagnostic, format);
- result.childMessages.append(QString::fromUtf8(clang_getCString(cdm)));
- clang_disposeString(cdm);
- clang_disposeDiagnostic(childDiagnostic);
- }
- }
-
- return result;
-}
-
-QVector<Diagnostic> getDiagnostics(CXTranslationUnit tu)
-{
- QVector<Diagnostic> result;
- const unsigned count = clang_getNumDiagnostics(tu);
- result.reserve(int(count));
- for (unsigned i = 0; i < count; ++i) {
- const CXDiagnostic d = clang_getDiagnostic(tu, i);
- result.append(Diagnostic::fromCXDiagnostic(d));
- clang_disposeDiagnostic(d);
- }
- return result;
-}
-
-QPair<int, int> parseTemplateArgumentList(const QString &l,
- const TemplateArgumentHandler &handler,
- int from)
-{
- const int ltPos = l.indexOf(QLatin1Char('<'), from);
- if (ltPos == - 1)
- return qMakePair(-1, -1);
- int startPos = ltPos + 1;
- int level = 1;
- for (int p = startPos, end = l.size(); p < end; ) {
- const char c = l.at(p).toLatin1();
- switch (c) {
- case ',':
- case '>':
- handler(level, l.midRef(startPos, p - startPos).trimmed());
- ++p;
- if (c == '>') {
- if (--level == 0)
- return qMakePair(ltPos, p);
- // Skip over next ',': "a<b<c,d>,e>"
- for (; p < end && (l.at(p).isSpace() || l.at(p) == QLatin1Char(',')); ++p) {}
- }
- startPos = p;
- break;
- case '<':
- handler(level, l.midRef(startPos, p - startPos).trimmed());
- ++level;
- startPos = ++p;
- break;
- default:
- ++p;
- break;
- }
- }
- return qMakePair(-1, -1);
-}
-
-CXDiagnosticSeverity maxSeverity(const QVector<Diagnostic> &ds)
-{
- CXDiagnosticSeverity result = CXDiagnostic_Ignored;
- for (const Diagnostic& d : ds) {
- if (d.severity > result)
- result = d.severity;
- }
- return result;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-
-QDebug operator<<(QDebug s, const SourceLocation &l)
-{
- QDebugStateSaver saver(s);
- s.nospace();
- s.noquote();
- s << QDir::toNativeSeparators(l.file) << ':' << l.line;
- if (l.column)
- s << ':' << l.column;
- return s;
-}
-
-// Roughly follow g++ format:
-// file.cpp:214:37: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
-QDebug operator<<(QDebug s, const Diagnostic &d)
-{
- QDebugStateSaver saver(s);
- s.nospace();
- s.noquote();
- s << d.location << ": ";
- switch (d.severity) {
- case CXDiagnostic_Ignored:
- s << "ignored";
- break;
- case CXDiagnostic_Note:
- s << "note";
- break;
- case CXDiagnostic_Warning:
- s << "warning";
- break;
- case CXDiagnostic_Error:
- s << "error";
- break;
- case CXDiagnostic_Fatal:
- s << "fatal";
- break;
- }
- s << ": " << d.message;
-
- if (d.source != Diagnostic::Clang)
- s << " [other]";
-
- if (const int childMessagesCount = d.childMessages.size()) {
- s << '\n';
- for (int i = 0; i < childMessagesCount; ++i)
- s << " " << d.childMessages.at(i) << '\n';
- }
-
- return s;
-}
-
-#endif // QT_NO_DEBUG_STREAM
-
-} // namespace clang
diff --git a/sources/shiboken2/ApiExtractor/clangparser/clangutils.h b/sources/shiboken2/ApiExtractor/clangparser/clangutils.h
deleted file mode 100644
index 5f005bd5d..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/clangutils.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CLANGUTILS_H
-#define CLANGUTILS_H
-
-#include <clang-c/Index.h>
-#include <qtcompat.h>
-#include <QtCore/QPair>
-#include <QtCore/QString>
-#include <QtCore/QStringList>
-#include <QtCore/QVector>
-
-#include <functional>
-
-QT_FORWARD_DECLARE_CLASS(QDebug)
-
-bool operator==(const CXCursor &c1, const CXCursor &c2);
-QtCompatHashFunctionType qHash(const CXCursor &c, QtCompatHashFunctionType seed = 0);
-
-bool operator==(const CXType &t1, const CXType &t2);
-QtCompatHashFunctionType qHash(const CXType &ct, QtCompatHashFunctionType seed);
-
-namespace clang {
-
-QString getCursorKindName(CXCursorKind cursorKind);
-QString getCursorSpelling(const CXCursor &cursor);
-QString getCursorDisplayName(const CXCursor &cursor);
-QString getTypeName(const CXType &type);
-inline QString getCursorTypeName(const CXCursor &cursor)
- { return getTypeName(clang_getCursorType(cursor)); }
-inline QString getCursorResultTypeName(const CXCursor &cursor)
- { return getTypeName(clang_getCursorResultType(cursor)); }
-
-inline bool isCursorValid(const CXCursor &c)
-{
- return c.kind < CXCursor_FirstInvalid || c.kind > CXCursor_LastInvalid;
-}
-
-struct SourceLocation
-{
- int compare(const SourceLocation &rhs) const;
-
- QString file;
- unsigned line = 0;
- unsigned column = 0;
- unsigned offset = 0;
-};
-
-SourceLocation getExpansionLocation(const CXSourceLocation &location);
-
-using SourceRange =QPair<SourceLocation, SourceLocation>;
-
-SourceLocation getCursorLocation(const CXCursor &cursor);
-CXString getFileNameFromLocation(const CXSourceLocation &location);
-SourceRange getCursorRange(const CXCursor &cursor);
-
-struct Diagnostic {
- enum Source { Clang, Other };
-
- Diagnostic() = default;
- // Clang
- static Diagnostic fromCXDiagnostic(CXDiagnostic cd);
- // Other
- explicit Diagnostic(const QString &m, const CXCursor &c, CXDiagnosticSeverity s = CXDiagnostic_Warning);
-
- QString message;
- QStringList childMessages;
- SourceLocation location;
- Source source = Clang;
- CXDiagnosticSeverity severity = CXDiagnostic_Warning;
-};
-
-QVector<Diagnostic> getDiagnostics(CXTranslationUnit tu);
-CXDiagnosticSeverity maxSeverity(const QVector<Diagnostic> &ds);
-
-// Parse a template argument list "a<b<c,d>,e>" and invoke a handler
-// with each match (level and string). Return begin and end of the list.
-using TemplateArgumentHandler = std::function<void (int, const QStringRef &)>;
-
-QPair<int, int> parseTemplateArgumentList(const QString &l,
- const TemplateArgumentHandler &handler,
- int from = 0);
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug, const SourceLocation &);
-QDebug operator<<(QDebug, const Diagnostic &);
-#endif // QT_NO_DEBUG_STREAM
-} // namespace clang
-
-#endif // CLANGUTILS_H
diff --git a/sources/shiboken2/ApiExtractor/clangparser/compilersupport.cpp b/sources/shiboken2/ApiExtractor/clangparser/compilersupport.cpp
deleted file mode 100644
index dac511003..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/compilersupport.cpp
+++ /dev/null
@@ -1,404 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "compilersupport.h"
-#include "header_paths.h"
-
-#include <reporthandler.h>
-
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QFileInfo>
-#include <QtCore/QProcess>
-#include <QtCore/QStandardPaths>
-#include <QtCore/QStringList>
-#include <QtCore/QVersionNumber>
-
-#include <clang-c/Index.h>
-
-#include <string.h>
-#include <algorithm>
-#include <iterator>
-
-namespace clang {
-
-QVersionNumber libClangVersion()
-{
- return QVersionNumber(CINDEX_VERSION_MAJOR, CINDEX_VERSION_MINOR);
-}
-
-static bool runProcess(const QString &program, const QStringList &arguments,
- QByteArray *stdOutIn = nullptr, QByteArray *stdErrIn = nullptr)
-{
- QProcess process;
- process.start(program, arguments, QProcess::ReadWrite);
- if (!process.waitForStarted()) {
- qWarning().noquote().nospace() << "Unable to start "
- << process.program() << ": " << process.errorString();
- return false;
- }
- process.closeWriteChannel();
- const bool finished = process.waitForFinished();
- const QByteArray stdErr = process.readAllStandardError();
- if (stdErrIn)
- *stdErrIn = stdErr;
- if (stdOutIn)
- *stdOutIn = process.readAllStandardOutput();
-
- if (!finished) {
- qWarning().noquote().nospace() << process.program() << " timed out: " << stdErr;
- process.kill();
- return false;
- }
-
- if (process.exitStatus() != QProcess::NormalExit) {
- qWarning().noquote().nospace() << process.program() << " crashed: " << stdErr;
- return false;
- }
-
- if (process.exitCode() != 0) {
- qWarning().noquote().nospace() << process.program() << " exited "
- << process.exitCode() << ": " << stdErr;
- return false;
- }
-
- return true;
-}
-
-#if defined(Q_CC_GNU)
-
-static QByteArray frameworkPath() { return QByteArrayLiteral(" (framework directory)"); }
-
-#if defined(Q_OS_MACOS)
-static void filterHomebrewHeaderPaths(HeaderPaths &headerPaths)
-{
- QByteArray homebrewPrefix = qgetenv("HOMEBREW_OPT");
-
- // If HOMEBREW_OPT is found we assume that the build is happening
- // inside a brew environment, which means we need to filter out
- // the -isystem flags added by the brew clang shim. This is needed
- // because brew passes the Qt include paths as system include paths
- // and because our parser ignores system headers, Qt classes won't
- // be found and thus compilation errors will occur.
- if (homebrewPrefix.isEmpty())
- return;
-
- qCInfo(lcShiboken) << "Found HOMEBREW_OPT with value:" << homebrewPrefix
- << "Assuming homebrew build environment.";
-
- HeaderPaths::iterator it = headerPaths.begin();
- while (it != headerPaths.end()) {
- if (it->path.startsWith(homebrewPrefix)) {
- qCInfo(lcShiboken) << "Filtering out homebrew include path: "
- << it->path;
- it = headerPaths.erase(it);
- } else {
- ++it;
- }
- }
-}
-#endif
-
-// Determine g++'s internal include paths from the output of
-// g++ -E -x c++ - -v </dev/null
-// Output looks like:
-// #include <...> search starts here:
-// /usr/local/include
-// /System/Library/Frameworks (framework directory)
-// End of search list.
-static HeaderPaths gppInternalIncludePaths(const QString &compiler)
-{
- HeaderPaths result;
- QStringList arguments;
- arguments << QStringLiteral("-E") << QStringLiteral("-x") << QStringLiteral("c++")
- << QStringLiteral("-") << QStringLiteral("-v");
- QByteArray stdOut;
- QByteArray stdErr;
- if (!runProcess(compiler, arguments, &stdOut, &stdErr))
- return result;
- const QByteArrayList stdErrLines = stdErr.split('\n');
- bool isIncludeDir = false;
- for (const QByteArray &line : stdErrLines) {
- if (isIncludeDir) {
- if (line.startsWith(QByteArrayLiteral("End of search list"))) {
- isIncludeDir = false;
- } else {
- HeaderPath headerPath{line.trimmed(), HeaderType::System};
- if (headerPath.path.endsWith(frameworkPath())) {
- headerPath.type = HeaderType::FrameworkSystem;
- headerPath.path.truncate(headerPath.path.size() - frameworkPath().size());
- }
- result.append(headerPath);
- }
- } else if (line.startsWith(QByteArrayLiteral("#include <...> search starts here"))) {
- isIncludeDir = true;
- }
- }
-
-#if defined(Q_OS_MACOS)
- filterHomebrewHeaderPaths(result);
-#endif
- return result;
-}
-#endif // Q_CC_MSVC
-
-// Detect Vulkan as supported from Qt 5.10 by checking the environment variables.
-static void detectVulkan(HeaderPaths *headerPaths)
-{
- static const char *vulkanVariables[] = {"VULKAN_SDK", "VK_SDK_PATH"};
- for (const char *vulkanVariable : vulkanVariables) {
- if (qEnvironmentVariableIsSet(vulkanVariable)) {
- const QByteArray path = qgetenv(vulkanVariable) + QByteArrayLiteral("/include");
- headerPaths->append(HeaderPath{path, HeaderType::System});
- break;
- }
- }
-}
-
-#if defined(Q_CC_GNU)
-enum class LinuxDistribution { RedHat, CentOs, Other };
-
-static LinuxDistribution linuxDistribution()
-{
- const QString &productType = QSysInfo::productType();
- if (productType == QLatin1String("rhel"))
- return LinuxDistribution::RedHat;
- if (productType.compare(QLatin1String("centos"), Qt::CaseInsensitive) == 0)
- return LinuxDistribution::CentOs;
- return LinuxDistribution::Other;
-}
-
-static bool checkProductVersion(const QVersionNumber &minimum,
- const QVersionNumber &excludedMaximum)
-{
- const QVersionNumber osVersion = QVersionNumber::fromString(QSysInfo::productVersion());
- return osVersion.isNull() || (osVersion >= minimum && osVersion < excludedMaximum);
-}
-
-static inline bool needsGppInternalHeaders()
-{
- const LinuxDistribution distro = linuxDistribution();
- switch (distro) {
- case LinuxDistribution::RedHat:
- case LinuxDistribution::CentOs:
- return checkProductVersion(QVersionNumber(6, 10), QVersionNumber(8));
- case LinuxDistribution::Other:
- break;
- }
- return false;
-}
-#endif // Q_CC_GNU
-
-// For MSVC, we set the MS compatibility version and let Clang figure out its own
-// options and include paths.
-// For the others, we pass "-nostdinc" since libclang tries to add it's own system
-// include paths, which together with the clang compiler paths causes some clash
-// which causes std types not being found and construct -I/-F options from the
-// include paths of the host compiler.
-
-#ifdef Q_CC_CLANG
-static QByteArray noStandardIncludeOption() { return QByteArrayLiteral("-nostdinc"); }
-#endif
-
-// The clang builtin includes directory is used to find the definitions for
-// intrinsic functions and builtin types. It is necessary to use the clang
-// includes to prevent redefinition errors. The default toolchain includes
-// should be picked up automatically by clang without specifying
-// them implicitly.
-
-#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
-# define NEED_CLANG_BUILTIN_INCLUDES 1
-#else
-# define NEED_CLANG_BUILTIN_INCLUDES 0
-#endif
-
-#if NEED_CLANG_BUILTIN_INCLUDES
-static QString findClangLibDir()
-{
- for (const char *envVar : {"LLVM_INSTALL_DIR", "CLANG_INSTALL_DIR"}) {
- if (qEnvironmentVariableIsSet(envVar)) {
- const QString path = QFile::decodeName(qgetenv(envVar)) + QLatin1String("/lib");
- if (QFileInfo::exists(path))
- return path;
- }
- }
- const QString llvmConfig =
- QStandardPaths::findExecutable(QLatin1String("llvm-config"));
- if (!llvmConfig.isEmpty()) {
- QByteArray stdOut;
- if (runProcess(llvmConfig, QStringList{QLatin1String("--libdir")}, &stdOut)) {
- const QString path = QFile::decodeName(stdOut.trimmed());
- if (QFileInfo::exists(path))
- return path;
- }
- }
- return QString();
-}
-
-static QString findClangBuiltInIncludesDir()
-{
- // Find the include directory of the highest version.
- const QString clangPathLibDir = findClangLibDir();
- if (!clangPathLibDir.isEmpty()) {
- QString candidate;
- QVersionNumber lastVersionNumber(1, 0, 0);
- QDir clangDir(clangPathLibDir + QLatin1String("/clang"));
- const QFileInfoList versionDirs =
- clangDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
- for (const QFileInfo &fi : versionDirs) {
- const QString fileName = fi.fileName();
- if (fileName.at(0).isDigit()) {
- const QVersionNumber versionNumber = QVersionNumber::fromString(fileName);
- if (!versionNumber.isNull() && versionNumber > lastVersionNumber) {
- candidate = fi.absoluteFilePath();
- lastVersionNumber = versionNumber;
- }
- }
- }
- if (!candidate.isEmpty())
- return candidate + QStringLiteral("/include");
- }
- return QString();
-}
-#endif // NEED_CLANG_BUILTIN_INCLUDES
-
-#if defined(Q_CC_CLANG) || defined(Q_CC_GNU)
-static QString compilerFromCMake(const QString &defaultCompiler)
-{
-// Added !defined(Q_OS_DARWIN) due to PYSIDE-1032
-# if defined(CMAKE_CXX_COMPILER) && !defined(Q_OS_DARWIN)
- Q_UNUSED(defaultCompiler)
- return QString::fromLocal8Bit(CMAKE_CXX_COMPILER);
-# else
- return defaultCompiler;
-# endif
-}
-#endif // Q_CC_CLANG, Q_CC_GNU
-
-// Returns clang options needed for emulating the host compiler
-QByteArrayList emulatedCompilerOptions()
-{
- QByteArrayList result;
-#if defined(Q_CC_MSVC)
- HeaderPaths headerPaths;
- result.append(QByteArrayLiteral("-fms-compatibility-version=19"));
- result.append(QByteArrayLiteral("-Wno-microsoft-enum-value"));
- // Fix yvals_core.h: STL1000: Unexpected compiler version, expected Clang 7 or newer (MSVC2017 update)
- result.append(QByteArrayLiteral("-D_ALLOW_COMPILER_AND_STL_VERSION_MISMATCH"));
-#elif defined(Q_CC_CLANG)
- HeaderPaths headerPaths = gppInternalIncludePaths(compilerFromCMake(QStringLiteral("clang++")));
- result.append(noStandardIncludeOption());
-#elif defined(Q_CC_GNU)
- HeaderPaths headerPaths;
-
-#if NEED_CLANG_BUILTIN_INCLUDES
- const QString clangBuiltinIncludesDir =
- QDir::toNativeSeparators(findClangBuiltInIncludesDir());
- if (clangBuiltinIncludesDir.isEmpty()) {
- qCWarning(lcShiboken, "Unable to locate Clang's built-in include directory "
- "(neither by checking the environment variables LLVM_INSTALL_DIR, CLANG_INSTALL_DIR "
- " nor running llvm-config). This may lead to parse errors.");
- } else {
- qCInfo(lcShiboken, "CLANG builtins includes directory: %s",
- qPrintable(clangBuiltinIncludesDir));
- headerPaths.append(HeaderPath{QFile::encodeName(clangBuiltinIncludesDir),
- HeaderType::System});
- }
-#endif // NEED_CLANG_BUILTIN_INCLUDES
-
- // Append the c++ include paths since Clang is unable to find <list> etc
- // on RHEL 7 with g++ 6.3 or CentOS 7.2.
- // A fix for this has been added to Clang 5.0, so, the code can be removed
- // once Clang 5.0 is the minimum version.
- if (needsGppInternalHeaders()) {
- const HeaderPaths gppPaths = gppInternalIncludePaths(compilerFromCMake(QStringLiteral("g++")));
- for (const HeaderPath &h : gppPaths) {
- if (h.path.contains("c++")
- || h.path.contains("sysroot")) { // centOS
- headerPaths.append(h);
- }
- }
- }
-#else
- HeaderPaths headerPaths;
-#endif
- detectVulkan(&headerPaths);
- std::transform(headerPaths.cbegin(), headerPaths.cend(),
- std::back_inserter(result), HeaderPath::includeOption);
- return result;
-}
-
-LanguageLevel emulatedCompilerLanguageLevel()
-{
-#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
- return LanguageLevel::Cpp17;
-#else
-# if defined(Q_CC_MSVC) && _MSC_VER > 1900
- // Fixes constexpr errors in MSVC2017 library headers with Clang 4.1..5.X (0.45 == Clang 6).
- if (libClangVersion() < QVersionNumber(0, 45))
- return LanguageLevel::Cpp1Z;
-# endif // Q_CC_MSVC && _MSC_VER > 1900
- return LanguageLevel::Cpp14; // otherwise, t.h is parsed as "C"
-#endif // Qt 5
-}
-
-struct LanguageLevelMapping
-{
- const char *option;
- LanguageLevel level;
-};
-
-static const LanguageLevelMapping languageLevelMapping[] =
-{
- {"c++11", LanguageLevel::Cpp11},
- {"c++14", LanguageLevel::Cpp14},
- {"c++17", LanguageLevel::Cpp17},
- {"c++20", LanguageLevel::Cpp20},
- {"c++1z", LanguageLevel::Cpp1Z}
-};
-
-const char *languageLevelOption(LanguageLevel l)
-{
- for (const LanguageLevelMapping &m : languageLevelMapping) {
- if (m.level == l)
- return m.option;
- }
- return nullptr;
-}
-
-LanguageLevel languageLevelFromOption(const char *o)
-{
- for (const LanguageLevelMapping &m : languageLevelMapping) {
- if (!strcmp(m.option, o))
- return m.level;
- }
- return LanguageLevel::Default;
-}
-
-} // namespace clang
diff --git a/sources/shiboken2/ApiExtractor/clangparser/compilersupport.h b/sources/shiboken2/ApiExtractor/clangparser/compilersupport.h
deleted file mode 100644
index d9e213e73..000000000
--- a/sources/shiboken2/ApiExtractor/clangparser/compilersupport.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef COMPILERSUPPORT_H
-#define COMPILERSUPPORT_H
-
-#include <QtCore/QByteArrayList>
-
-QT_FORWARD_DECLARE_CLASS(QVersionNumber)
-
-enum class LanguageLevel {
- Default,
- Cpp11,
- Cpp14,
- Cpp17,
- Cpp20,
- Cpp1Z
-};
-
-namespace clang {
-QVersionNumber libClangVersion();
-
-QByteArrayList emulatedCompilerOptions();
-LanguageLevel emulatedCompilerLanguageLevel();
-
-const char *languageLevelOption(LanguageLevel l);
-LanguageLevel languageLevelFromOption(const char *);
-} // namespace clang
-
-#endif // COMPILERSUPPORT_H
diff --git a/sources/shiboken2/ApiExtractor/cmake_uninstall.cmake b/sources/shiboken2/ApiExtractor/cmake_uninstall.cmake
deleted file mode 100644
index df95fb9d8..000000000
--- a/sources/shiboken2/ApiExtractor/cmake_uninstall.cmake
+++ /dev/null
@@ -1,21 +0,0 @@
-IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
- MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"")
-ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
-
-FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
-STRING(REGEX REPLACE "\n" ";" files "${files}")
-FOREACH(file ${files})
- MESSAGE(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"")
- IF(EXISTS "$ENV{DESTDIR}${file}")
- EXEC_PROGRAM(
- "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
- OUTPUT_VARIABLE rm_out
- RETURN_VALUE rm_retval
- )
- IF(NOT "${rm_retval}" STREQUAL 0)
- MESSAGE(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"")
- ENDIF(NOT "${rm_retval}" STREQUAL 0)
- ELSE(EXISTS "$ENV{DESTDIR}${file}")
- MESSAGE(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.")
- ENDIF(EXISTS "$ENV{DESTDIR}${file}")
-ENDFOREACH(file)
diff --git a/sources/shiboken2/ApiExtractor/dependency.h b/sources/shiboken2/ApiExtractor/dependency.h
deleted file mode 100644
index 7168ea3bc..000000000
--- a/sources/shiboken2/ApiExtractor/dependency.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DEPENDENCY_H
-#define DEPENDENCY_H
-
-#include <QtCore/QVector>
-
-#include <utility>
-
-// Dependencies for topologically sorting classes
-
-class AbstractMetaClass;
-
-struct Dependency {
- AbstractMetaClass *parent;
- AbstractMetaClass *child;
-};
-
-using Dependencies = QVector<Dependency>;
-
-#endif // DEPENDENCY_H
diff --git a/sources/shiboken2/ApiExtractor/docparser.cpp b/sources/shiboken2/ApiExtractor/docparser.cpp
deleted file mode 100644
index cb5d85074..000000000
--- a/sources/shiboken2/ApiExtractor/docparser.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include "docparser.h"
-#include "abstractmetalang.h"
-#include "messages.h"
-#include "reporthandler.h"
-#include "typesystem.h"
-#include "xmlutils.h"
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QTextStream>
-#include <QBuffer>
-
-#include <cstdlib>
-#ifdef HAVE_LIBXSLT
-# include <libxslt/xsltutils.h>
-# include <libxslt/transform.h>
-#endif
-
-#include <algorithm>
-
-DocParser::DocParser()
-{
-#ifdef HAVE_LIBXSLT
- xmlSubstituteEntitiesDefault(1);
-#endif
-}
-
-DocParser::~DocParser() = default;
-
-QString DocParser::getDocumentation(const XQueryPtr &xquery, const QString& query,
- const DocModificationList& mods) const
-{
- QString doc = execXQuery(xquery, query);
- return applyDocModifications(mods, doc.trimmed());
-}
-
-QString DocParser::execXQuery(const XQueryPtr &xquery, const QString& query) const
-{
- QString errorMessage;
- const QString result = xquery->evaluate(query, &errorMessage);
- if (!errorMessage.isEmpty())
- qCWarning(lcShibokenDoc, "%s", qPrintable(errorMessage));
- return result;
-}
-
-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()) {
- return true;
- }
- switch (func->functionType()) {
- case AbstractMetaFunction::MoveConstructorFunction:
- case AbstractMetaFunction::AssignmentOperatorFunction:
- case AbstractMetaFunction::MoveAssignmentOperatorFunction:
- return true;
- default:
- break;
- }
- return false;
-}
-
-AbstractMetaFunctionList DocParser::documentableFunctions(const AbstractMetaClass *metaClass)
-{
- AbstractMetaFunctionList result = metaClass->functionsInTargetLang();
- for (int i = result.size() - 1; i >= 0; --i) {
- if (DocParser::skipForQuery(result.at(i)) || result.at(i)->isUserAdded())
- result.removeAt(i);
- }
- return result;
-}
-
-static inline bool isXpathDocModification(const DocModification &mod)
-{
- return mod.mode() == TypeSystem::DocModificationXPathReplace;
-}
-
-QString DocParser::applyDocModifications(const DocModificationList& mods, const QString& xml) const
-{
- const char xslPrefix[] =
-R"(<xsl:template match="/">
- <xsl:apply-templates />
-</xsl:template>
-<xsl:template match="*">
-<xsl:copy>
- <xsl:copy-of select="@*"/>
- <xsl:apply-templates/>
-</xsl:copy>
-</xsl:template>
-)";
-
- if (mods.isEmpty() || xml.isEmpty()
- || !std::any_of(mods.cbegin(), mods.cend(), isXpathDocModification)) {
- return xml;
- }
-
- QString xsl = QLatin1String(xslPrefix);
- for (const DocModification &mod : mods) {
- if (isXpathDocModification(mod)) {
- QString xpath = mod.xpath();
- xpath.replace(QLatin1Char('"'), QLatin1String("&quot;"));
- xsl += QLatin1String("<xsl:template match=\"")
- + xpath + QLatin1String("\">")
- + mod.code() + QLatin1String("</xsl:template>\n");
- }
- }
-
- QString errorMessage;
- const QString result = xsl_transform(xml, xsl, &errorMessage);
- if (!errorMessage.isEmpty())
- qCWarning(lcShibokenDoc, "%s",
- qPrintable(msgXpathDocModificationError(mods, errorMessage)));
- if (result == xml) {
- const QString message = QLatin1String("Query did not result in any modifications to \"")
- + xml + QLatin1Char('"');
- qCWarning(lcShibokenDoc, "%s",
- qPrintable(msgXpathDocModificationError(mods, message)));
- }
- return result;
-}
diff --git a/sources/shiboken2/ApiExtractor/docparser.h b/sources/shiboken2/ApiExtractor/docparser.h
deleted file mode 100644
index 1dccae4d6..000000000
--- a/sources/shiboken2/ApiExtractor/docparser.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef DOCPARSER_H
-#define DOCPARSER_H
-
-#include "typesystem_typedefs.h"
-#include "abstractmetalang_typedefs.h"
-
-#include <QtCore/QString>
-#include <QtCore/QSharedPointer>
-
-class AbstractMetaClass;
-class DocModification;
-class Documentation;
-
-class XQuery;
-
-class DocParser
-{
-public:
- Q_DISABLE_COPY(DocParser)
-
- using XQueryPtr = QSharedPointer<XQuery>;
-
- DocParser();
- virtual ~DocParser();
- virtual void fillDocumentation(AbstractMetaClass* metaClass) = 0;
-
- /**
- * Process and retrieves documentation concerning the entire
- * module or library.
- * \return object containing module/library documentation information
- */
- virtual Documentation retrieveModuleDocumentation() = 0;
-
- void setDocumentationDataDirectory(const QString& dir)
- {
- m_docDataDir = dir;
- }
-
- /**
- * Informs the location of the XML data generated by the tool
- * (e.g.: DoxyGen, qdoc) used to extract the library's documentation
- * comment.
- * \return the path for the directory containing the XML data created
- * from the library's documentation beign parsed.
- */
- QString documentationDataDirectory() const
- {
- return m_docDataDir;
- }
-
- void setLibrarySourceDirectory(const QString& dir)
- {
- m_libSourceDir = dir;
- }
- /**
- * Informs the location of the library being parsed. The library
- * source code is parsed for the documentation comments.
- * \return the path for the directory containing the source code of
- * the library beign parsed.
- */
- QString librarySourceDirectory() const
- {
- return m_libSourceDir;
- }
-
- void setPackageName(const QString& packageName)
- {
- m_packageName = packageName;
- }
- /**
- * Retrieves the name of the package (or module or library) being parsed.
- * \return the name of the package (module/library) being parsed
- */
- QString packageName() const
- {
- return m_packageName;
- }
-
- /**
- * Process and retrieves documentation concerning the entire
- * module or library.
- * \param name module name
- * \return object containing module/library documentation information
- * \todo Merge with retrieveModuleDocumentation() on next ABI change.
- */
- virtual Documentation retrieveModuleDocumentation(const QString& name) = 0;
-
- static bool skipForQuery(const AbstractMetaFunction *func);
-
-protected:
- QString getDocumentation(const XQueryPtr &xquery, const QString& query,
- const DocModificationList& mods) const;
-
-
- static AbstractMetaFunctionList documentableFunctions(const AbstractMetaClass *metaClass);
-
-private:
- QString m_packageName;
- QString m_docDataDir;
- QString m_libSourceDir;
-
- QString execXQuery(const XQueryPtr &xquery, const QString& query) const;
- QString applyDocModifications(const DocModificationList& mods, const QString& xml) const;
-};
-
-#endif // DOCPARSER_H
-
diff --git a/sources/shiboken2/ApiExtractor/doxygenparser.cpp b/sources/shiboken2/ApiExtractor/doxygenparser.cpp
deleted file mode 100644
index 7c15db1ca..000000000
--- a/sources/shiboken2/ApiExtractor/doxygenparser.cpp
+++ /dev/null
@@ -1,209 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "doxygenparser.h"
-#include "abstractmetalang.h"
-#include "messages.h"
-#include "reporthandler.h"
-#include "typesystem.h"
-#include "xmlutils.h"
-
-#include <QtCore/QFile>
-#include <QtCore/QDir>
-
-static QString getSectionKindAttr(const AbstractMetaFunction *func)
-{
- if (func->isSignal())
- return QLatin1String("signal");
- QString kind = func->isPublic()
- ? QLatin1String("public") : QLatin1String("protected");
- if (func->isStatic())
- kind += QLatin1String("-static");
- else if (func->isSlot())
- kind += QLatin1String("-slot");
- return kind;
-}
-
-Documentation DoxygenParser::retrieveModuleDocumentation()
-{
- return retrieveModuleDocumentation(packageName());
-}
-
-void DoxygenParser::fillDocumentation(AbstractMetaClass* metaClass)
-{
- if (!metaClass)
- return;
-
- QString doxyFileSuffix;
- if (metaClass->enclosingClass()) {
- doxyFileSuffix += metaClass->enclosingClass()->name();
- doxyFileSuffix += QLatin1String("_1_1"); // FIXME: Check why _1_1!!
- }
- doxyFileSuffix += metaClass->name();
- doxyFileSuffix += QLatin1String(".xml");
-
- const char* prefixes[] = { "class", "struct", "namespace" };
- bool isProperty = false;
-
- QString doxyFilePath;
- for (const char *prefix : prefixes) {
- doxyFilePath = documentationDataDirectory() + QLatin1Char('/')
- + QLatin1String(prefix) + doxyFileSuffix;
- if (QFile::exists(doxyFilePath))
- break;
- doxyFilePath.clear();
- }
-
- if (doxyFilePath.isEmpty()) {
- qCWarning(lcShibokenDoc).noquote().nospace()
- << "Can't find doxygen file for class " << metaClass->name() << ", tried: "
- << QDir::toNativeSeparators(documentationDataDirectory())
- << "/{struct|class|namespace}"<< doxyFileSuffix;
- return;
- }
-
- QString errorMessage;
- XQueryPtr xquery = XQuery::create(doxyFilePath, &errorMessage);
- if (xquery.isNull()) {
- qCWarning(lcShibokenDoc, "%s", qPrintable(errorMessage));
- return;
- }
-
- // Get class documentation
- const QString classQuery = QLatin1String("/doxygen/compounddef/detaileddescription");
- QString classDoc = getDocumentation(xquery, classQuery,
- metaClass->typeEntry()->docModifications());
- if (classDoc.isEmpty())
- qCWarning(lcShibokenDoc, "%s", qPrintable(msgCannotFindDocumentation(doxyFilePath, "class", metaClass->name(), classQuery)));
- metaClass->setDocumentation(classDoc);
-
- //Functions Documentation
- const AbstractMetaFunctionList &funcs = DocParser::documentableFunctions(metaClass);
- for (AbstractMetaFunction *func : funcs) {
- QString query = QLatin1String("/doxygen/compounddef/sectiondef");
- // properties
- if (func->isPropertyReader() || func->isPropertyWriter()
- || func->isPropertyResetter()) {
- query += QLatin1String("[@kind=\"property\"]/memberdef/name[text()=\"")
- + func->propertySpec()->name() + QLatin1String("\"]");
- isProperty = true;
- } else { // normal methods
- QString kind = getSectionKindAttr(func);
- query += QLatin1String("[@kind=\"") + kind
- + QLatin1String("-func\"]/memberdef/name[text()=\"")
- + func->originalName() + QLatin1String("\"]");
-
- if (func->arguments().isEmpty()) {
- QString args = func->isConstant() ? QLatin1String("() const ") : QLatin1String("()");
- query += QLatin1String("/../argsstring[text()=\"") + args + QLatin1String("\"]");
- } else {
- int i = 1;
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (AbstractMetaArgument *arg : arguments) {
- if (!arg->type()->isPrimitive()) {
- query += QLatin1String("/../param[") + QString::number(i)
- + QLatin1String("]/type/ref[text()=\"")
- + arg->type()->name() + QLatin1String("\"]/../..");
- } else {
- query += QLatin1String("/../param[") + QString::number(i)
- + QLatin1String("]/type[text()=\"")
- + arg->type()->name() + QLatin1String("\"]/..");
- }
- ++i;
- }
- }
- }
- if (!isProperty) {
- query += QLatin1String("/../detaileddescription");
- } else {
- query = QLatin1Char('(') + query;
- query += QLatin1String("/../detaileddescription)[1]");
- }
- QString doc = getDocumentation(xquery, query, DocModificationList());
- if (doc.isEmpty()) {
- qCWarning(lcShibokenDoc, "%s",
- qPrintable(msgCannotFindDocumentation(doxyFilePath, metaClass, func, query)));
- }
- func->setDocumentation(doc);
- isProperty = false;
- }
-
- //Fields
- const AbstractMetaFieldList &fields = metaClass->fields();
- for (AbstractMetaField *field : fields) {
- if (field->isPrivate())
- return;
-
- QString query = QLatin1String("/doxygen/compounddef/sectiondef/memberdef/name[text()=\"")
- + field->name() + QLatin1String("\"]/../detaileddescription");
- QString doc = getDocumentation(xquery, query, DocModificationList());
- if (doc.isEmpty()) {
- qCWarning(lcShibokenDoc, "%s",
- qPrintable(msgCannotFindDocumentation(doxyFilePath, metaClass, field, query)));
- }
- field->setDocumentation(doc);
- }
-
- //Enums
- const AbstractMetaEnumList &enums = metaClass->enums();
- for (AbstractMetaEnum *meta_enum : enums) {
- QString query = QLatin1String("/doxygen/compounddef/sectiondef/memberdef[@kind=\"enum\"]/name[text()=\"")
- + meta_enum->name() + QLatin1String("\"]/..");
- QString doc = getDocumentation(xquery, query, DocModificationList());
- if (doc.isEmpty()) {
- qCWarning(lcShibokenDoc, "%s",
- qPrintable(msgCannotFindDocumentation(doxyFilePath, metaClass, meta_enum, query)));
- }
- meta_enum->setDocumentation(doc);
- }
-
-}
-
-Documentation DoxygenParser::retrieveModuleDocumentation(const QString& name){
-
- QString sourceFile = documentationDataDirectory() + QLatin1String("/indexpage.xml");
-
- if (!QFile::exists(sourceFile)) {
- qCWarning(lcShibokenDoc).noquote().nospace()
- << "Can't find doxygen XML file for module " << name << ", tried: "
- << QDir::toNativeSeparators(sourceFile);
- return Documentation();
- }
-
- QString errorMessage;
- XQueryPtr xquery = XQuery::create(sourceFile, &errorMessage);
- if (xquery.isNull()) {
- qCWarning(lcShibokenDoc, "%s", qPrintable(errorMessage));
- return {};
- }
-
- // Module documentation
- QString query = QLatin1String("/doxygen/compounddef/detaileddescription");
- return Documentation(getDocumentation(xquery, query, DocModificationList()));
-}
-
diff --git a/sources/shiboken2/ApiExtractor/doxygenparser.h b/sources/shiboken2/ApiExtractor/doxygenparser.h
deleted file mode 100644
index ada64ac18..000000000
--- a/sources/shiboken2/ApiExtractor/doxygenparser.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DOXYGENPARSER_H
-#define DOXYGENPARSER_H
-
-#include "docparser.h"
-
-class DoxygenParser : public DocParser
-{
-public:
- DoxygenParser() = default;
- void fillDocumentation(AbstractMetaClass *metaClass) override;
- Documentation retrieveModuleDocumentation() override;
- Documentation retrieveModuleDocumentation(const QString& name) override;
-};
-
-#endif // DOXYGENPARSER_H
diff --git a/sources/shiboken2/ApiExtractor/fileout.cpp b/sources/shiboken2/ApiExtractor/fileout.cpp
deleted file mode 100644
index 10a8f6be8..000000000
--- a/sources/shiboken2/ApiExtractor/fileout.cpp
+++ /dev/null
@@ -1,249 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "fileout.h"
-#include "messages.h"
-#include "reporthandler.h"
-
-#include <QtCore/QTextCodec>
-#include <QtCore/QFileInfo>
-#include <QtCore/QDir>
-#include <QtCore/QDebug>
-
-#include <cstdio>
-
-bool FileOut::dummy = false;
-bool FileOut::diff = false;
-
-#ifdef Q_OS_LINUX
-static const char colorDelete[] = "\033[31m";
-static const char colorAdd[] = "\033[32m";
-static const char colorInfo[] = "\033[36m";
-static const char colorReset[] = "\033[0m";
-#else
-static const char colorDelete[] = "";
-static const char colorAdd[] = "";
-static const char colorInfo[] = "";
-static const char colorReset[] = "";
-#endif
-
-FileOut::FileOut(QString n) :
- name(std::move(n)),
- stream(&tmp),
- isDone(false)
-{
-}
-
-FileOut::~FileOut()
-{
- if (!isDone)
- done();
-}
-
-static QVector<int> lcsLength(const QByteArrayList &a, const QByteArrayList &b)
-{
- const int height = a.size() + 1;
- const int width = b.size() + 1;
-
- QVector<int> res(width * height, 0);
-
- for (int row = 1; row < height; row++) {
- for (int col = 1; col < width; col++) {
- if (a[row-1] == b[col-1])
- res[width * row + col] = res[width * (row-1) + col-1] + 1;
- else
- res[width * row + col] = qMax(res[width * row + col-1],
- res[width * (row-1) + col]);
- }
- }
- return res;
-}
-
-enum Type {
- Add,
- Delete,
- Unchanged
-};
-
-struct Unit
-{
- Type type;
- int start;
- int end;
-
- void print(const QByteArrayList &a, const QByteArrayList &b) const;
-};
-
-void Unit::print(const QByteArrayList &a, const QByteArrayList &b) const
-{
- switch (type) {
- case Unchanged:
- if ((end - start) > 9) {
- for (int i = start; i <= start + 2; i++)
- std::printf(" %s\n", a.at(i).constData());
- std::printf("%s=\n= %d more lines\n=%s\n",
- colorInfo, end - start - 6, colorReset);
- for (int i = end - 2; i <= end; i++)
- std::printf(" %s\n", a.at(i).constData());
- } else {
- for (int i = start; i <= end; i++)
- std::printf(" %s\n", a.at(i).constData());
- }
- break;
- case Add:
- std::fputs(colorAdd, stdout);
- for (int i = start; i <= end; i++)
- std::printf("+ %s\n", b.at(i).constData());
- std::fputs(colorReset, stdout);
- break;
- case Delete:
- std::fputs(colorDelete, stdout);
- for (int i = start; i <= end; i++)
- std::printf("- %s\n", a.at(i).constData());
- std::fputs(colorReset, stdout);
- break;
- }
-}
-
-static void unitAppend(Type type, int pos, QVector<Unit> *units)
-{
- if (!units->isEmpty() && units->last().type == type)
- units->last().end = pos;
- else
- units->append(Unit{type, pos, pos});
-}
-
-static QVector<Unit> diffHelper(const QVector<int> &lcs,
- const QByteArrayList &a, const QByteArrayList &b,
- int row, int col)
-{
- if (row > 0 && col > 0 && a.at(row - 1) == b.at(col - 1)) {
- QVector<Unit> result = diffHelper(lcs, a, b, row - 1, col - 1);
- unitAppend(Unchanged, row - 1, &result);
- return result;
- }
-
- const int width = b.size() + 1;
- if (col > 0
- && (row == 0 || lcs.at(width * row + col -1 ) >= lcs.at(width * (row - 1) + col))) {
- QVector<Unit> result = diffHelper(lcs, a, b, row, col - 1);
- unitAppend(Add, col - 1, &result);
- return result;
- }
- if (row > 0
- && (col == 0 || lcs.at(width * row + col-1) < lcs.at(width * (row - 1) + col))) {
- QVector<Unit> result = diffHelper(lcs, a, b, row - 1, col);
- unitAppend(Delete, row - 1, &result);
- return result;
- }
- return QVector<Unit>{};
-}
-
-static void diff(const QByteArrayList &a, const QByteArrayList &b)
-{
- const QVector<Unit> res = diffHelper(lcsLength(a, b), a, b, a.size(), b.size());
- for (const Unit &unit : res)
- unit.print(a, b);
-}
-
-FileOut::State FileOut::done()
-{
- QString errorMessage;
- const State result = done(&errorMessage);
- if (result == Failure)
- qCWarning(lcShiboken, "%s", qPrintable(errorMessage));
- return result;
-}
-
-FileOut::State FileOut::done(QString *errorMessage)
-{
- Q_ASSERT(!isDone);
- if (name.isEmpty())
- return Failure;
-
- isDone = true;
- bool fileEqual = false;
- QFile fileRead(name);
- QFileInfo info(fileRead);
- stream.flush();
- QByteArray original;
- if (info.exists() && (diff || (info.size() == tmp.size()))) {
- if (!fileRead.open(QIODevice::ReadOnly)) {
- *errorMessage = msgCannotOpenForReading(fileRead);
- return Failure;
- }
-
- original = fileRead.readAll();
- fileRead.close();
- fileEqual = (original == tmp);
- }
-
- if (fileEqual)
- return Unchanged;
-
- if (!FileOut::dummy) {
- QDir dir(info.absolutePath());
- if (!dir.mkpath(dir.absolutePath())) {
- *errorMessage = QStringLiteral("unable to create directory '%1'")
- .arg(QDir::toNativeSeparators(dir.absolutePath()));
- return Failure;
- }
-
- QFile fileWrite(name);
- if (!fileWrite.open(QIODevice::WriteOnly)) {
- *errorMessage = msgCannotOpenForWriting(fileWrite);
- return Failure;
- }
- QTextCodec *codec = QTextCodec::codecForName("UTF-8");
- stream.setCodec(codec);
- stream.setDevice(&fileWrite);
- stream << tmp;
- }
- if (diff) {
- std::printf("%sFile: %s%s\n", colorInfo, qPrintable(name), colorReset);
- ::diff(original.split('\n'), tmp.split('\n'));
- std::printf("\n");
- }
-
- return Success;
-}
-
-void FileOut::touchFile(const QString &filePath)
-{
- QFile toucher(filePath);
- qint64 size = toucher.size();
- if (!toucher.open(QIODevice::ReadWrite)) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("Failed to touch file '%1'")
- .arg(QDir::toNativeSeparators(filePath));
- return;
- }
- toucher.resize(size+1);
- toucher.resize(size);
- toucher.close();
-}
diff --git a/sources/shiboken2/ApiExtractor/fileout.h b/sources/shiboken2/ApiExtractor/fileout.h
deleted file mode 100644
index b1011c4d6..000000000
--- a/sources/shiboken2/ApiExtractor/fileout.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef FILEOUT_H
-#define FILEOUT_H
-
-#include <QtCore/QObject>
-#include <QtCore/QTextStream>
-
-QT_FORWARD_DECLARE_CLASS(QFile)
-
-class FileOut : public QObject
-{
-private:
- QByteArray tmp;
- QString name;
-
-public:
- Q_DISABLE_COPY(FileOut)
-
- enum State { Failure, Unchanged, Success };
-
- explicit FileOut(QString name);
- ~FileOut();
-
- QString filePath() const { return name; }
-
- State done();
- State done(QString *errorMessage);
-
- void touch() { touchFile(name); }
-
- static void touchFile(const QString &filePath);
-
- QTextStream stream;
-
- static bool dummy;
- static bool diff;
-
-private:
- bool isDone;
-};
-
-#endif // FILEOUT_H
diff --git a/sources/shiboken2/ApiExtractor/graph.cpp b/sources/shiboken2/ApiExtractor/graph.cpp
deleted file mode 100644
index 53e20ebba..000000000
--- a/sources/shiboken2/ApiExtractor/graph.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "graph.h"
-#include <QVector>
-#include <QDebug>
-#include <QSet>
-#include <iterator>
-#include <algorithm>
-#include <iostream>
-#include <QFile>
-
-struct Graph::GraphPrivate
-{
- enum Color { WHITE, GRAY, BLACK };
- using Edges = QVector<QSet<int> >;
-
- Edges edges;
-
- GraphPrivate(int numNodes) : edges(numNodes)
- {
- }
-
- void dfsVisit(int node, Graph::Indexes &result, QVector<Color> &colors) const
- {
- colors[node] = GRAY;
- for (const auto &c : edges.at(node)) {
- if (colors[c] == WHITE)
- dfsVisit(c, result, colors);
- else if (colors[c] == GRAY) // This is not a DAG!
- return;
- }
- colors[node] = BLACK;
- result.append(node);
- }
-};
-
-Graph::Graph(int numNodes) : m_d(new GraphPrivate(numNodes))
-{
-}
-
-Graph::~Graph()
-{
- delete m_d;
-}
-
-int Graph::nodeCount() const
-{
- return m_d->edges.size();
-}
-
-Graph::Indexes Graph::topologicalSort() const
-{
- const int nodeCount = Graph::nodeCount();
- Indexes result;
- result.reserve(nodeCount);
-
- QVector<GraphPrivate::Color> colors(nodeCount, GraphPrivate::WHITE);
-
- for (int i = 0; i < nodeCount; ++i) {
- if (colors[i] == GraphPrivate::WHITE)
- m_d->dfsVisit(i, result, colors);
- }
-
- if (result.size() == nodeCount)
- std::reverse(result.begin(), result.end());
- else
- result.clear(); // Not a DAG!
- return result;
-}
-
-bool Graph::containsEdge(int from, int to)
-{
- return m_d->edges[from].contains(to);
-}
-
-void Graph::addEdge(int from, int to)
-{
- Q_ASSERT(to < m_d->edges.size());
- m_d->edges[from].insert(to);
-}
-
-void Graph::removeEdge(int from, int to)
-{
- m_d->edges[from].remove(to);
-}
-
-void Graph::dump() const
-{
- for (int i = 0; i < m_d->edges.size(); ++i) {
- std::cout << i << " -> ";
- std::copy(m_d->edges[i].begin(), m_d->edges[i].end(), std::ostream_iterator<int>(std::cout, " "));
- std::cout << std::endl;
- }
-}
-
-void Graph::dumpDot(const QHash< int, QString >& nodeNames, const QString& fileName) const
-{
- QFile output(fileName);
- if (!output.open(QIODevice::WriteOnly))
- return;
- QTextStream s(&output);
- s << "digraph D {\n";
- for (int i = 0; i < m_d->edges.size(); ++i) {
- for (auto it = m_d->edges[i].cbegin(), end = m_d->edges[i].cend(); it != end; ++it)
- s << '"' << nodeNames[i] << "\" -> \"" << nodeNames[*it] << "\"\n";
- }
- s << "}\n";
-}
diff --git a/sources/shiboken2/ApiExtractor/graph.h b/sources/shiboken2/ApiExtractor/graph.h
deleted file mode 100644
index 5dc8e21ea..000000000
--- a/sources/shiboken2/ApiExtractor/graph.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef GRAPH_H
-#define GRAPH_H
-
-#include <QVector>
-#include <QHash>
-#include <QString>
-
-/// A graph that can have their nodes topologically sorted.
-class Graph
-{
-public:
- Q_DISABLE_COPY(Graph)
-
- using Indexes = QVector<int>;
-
- /// Create a new graph with \p numNodes nodes.
- Graph(int numNodes);
- ~Graph();
-
- /// Returns the numbed of nodes in this graph.
- int nodeCount() const;
- /// Returns true if the graph contains the edge from -> to
- bool containsEdge(int from, int to);
- /// Adds an edge to this graph.
- void addEdge(int from, int to);
- /// Removes an edge out of this graph.
- void removeEdge(int from, int to);
- /// Print this graph to stdout.
- void dump() const;
- /**
- * Dumps a dot graph to a file named \p filename.
- * \param nodeNames map used to translate node ids to human readable text.
- * \param fileName file name where the output should be written.
- */
- void dumpDot(const QHash<int, QString>& nodeNames, const QString& fileName) const;
-
- /**
- * Topologically sort this graph.
- * \return A collection with all nodes topologically sorted or an empty collection if a cyclic
- * dependency was found.
- */
- Indexes topologicalSort() const;
-private:
-
- struct GraphPrivate;
- GraphPrivate* m_d;
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/header_paths.h b/sources/shiboken2/ApiExtractor/header_paths.h
deleted file mode 100644
index c9b5144c8..000000000
--- a/sources/shiboken2/ApiExtractor/header_paths.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef HEADER_PATHS_H
-#define HEADER_PATHS_H
-
-#include <QByteArray>
-#include <QVector>
-#include <QString>
-
-enum class HeaderType
-{
- Standard,
- System, // -isystem
- Framework, // macOS framework path
- FrameworkSystem // macOS framework system path
-};
-
-class HeaderPath {
-public:
- QByteArray path;
- HeaderType type;
-
- static QByteArray includeOption(const HeaderPath &p)
- {
- QByteArray option;
- switch (p.type) {
- case HeaderType::Standard:
- option = QByteArrayLiteral("-I");
- break;
- case HeaderType::System:
- option = QByteArrayLiteral("-isystem");
- break;
- case HeaderType::Framework:
- option = QByteArrayLiteral("-F");
- break;
- case HeaderType::FrameworkSystem:
- option = QByteArrayLiteral("-iframework");
- break;
- }
- return option + p.path;
- }
-};
-
-using HeaderPaths = QVector<HeaderPath>;
-
-#endif // HEADER_PATHS_H
diff --git a/sources/shiboken2/ApiExtractor/icecc.cmake b/sources/shiboken2/ApiExtractor/icecc.cmake
deleted file mode 100644
index b2bf071aa..000000000
--- a/sources/shiboken2/ApiExtractor/icecc.cmake
+++ /dev/null
@@ -1,11 +0,0 @@
-include (CMakeForceCompiler)
-option(ENABLE_ICECC "Enable icecc checking, for distributed compilation")
-if (ENABLE_ICECC)
- find_program(ICECC icecc)
- if (ICECC)
- message(STATUS "icecc found! Distributed compilation for all!! huhuhu.")
- cmake_force_cxx_compiler(${ICECC} icecc)
- else(ICECC)
- message(FATAL_ERROR "icecc NOT found! re-run cmake without -DENABLE_ICECC")
- endif(ICECC)
-endif(ENABLE_ICECC)
diff --git a/sources/shiboken2/ApiExtractor/include.cpp b/sources/shiboken2/ApiExtractor/include.cpp
deleted file mode 100644
index 6c2cce3a9..000000000
--- a/sources/shiboken2/ApiExtractor/include.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "include.h"
-#include <QDebug>
-#include <QDir>
-#include <QTextStream>
-#include <QHash>
-
-QString Include::toString() const
-{
- if (m_type == IncludePath)
- return QLatin1String("#include <") + m_name + QLatin1Char('>');
- if (m_type == LocalPath)
- return QLatin1String("#include \"") + m_name + QLatin1Char('"');
- return QLatin1String("import ") + m_name + QLatin1Char(';');
-}
-
-QtCompatHashFunctionType qHash(const Include& inc)
-{
- return qHash(inc.m_name);
-}
-
-QTextStream& operator<<(QTextStream& out, const Include& include)
-{
- if (include.isValid())
- out << include.toString() << Qt::endl;
- return out;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const Include &i)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "Include(";
- if (i.isValid())
- d << "type=" << i.type() << ", file=\"" << QDir::toNativeSeparators(i.name()) << '"';
- else
- d << "invalid";
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
diff --git a/sources/shiboken2/ApiExtractor/include.h b/sources/shiboken2/ApiExtractor/include.h
deleted file mode 100644
index 2219fba55..000000000
--- a/sources/shiboken2/ApiExtractor/include.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef INCLUDE_H
-#define INCLUDE_H
-
-#include <qtcompat.h>
-
-#include <QString>
-#include <QVector>
-
-QT_BEGIN_NAMESPACE
-class QTextStream;
-QT_END_NAMESPACE
-
-class Include
-{
-public:
- enum IncludeType {
- IncludePath,
- LocalPath,
- TargetLangImport,
- InvalidInclude
- };
-
- Include() = default;
- Include(IncludeType t, const QString &nam) : m_type(t), m_name(nam) {};
-
- bool isValid() const
- {
- return !m_name.isEmpty();
- }
-
- IncludeType type() const
- {
- return m_type;
- }
-
- QString name() const
- {
- return m_name;
- }
-
- QString toString() const;
-
- bool operator<(const Include& other) const
- {
- return m_name < other.m_name;
- }
-
- bool operator==(const Include& other) const
- {
- return m_type == other.m_type && m_name == other.m_name;
- }
-
- friend QtCompatHashFunctionType qHash(const Include&);
- private:
- IncludeType m_type = IncludePath;
- QString m_name;
-};
-
-QtCompatHashFunctionType qHash(const Include& inc);
-QTextStream& operator<<(QTextStream& out, const Include& include);
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const Include &i);
-#endif
-
-using IncludeList = QVector<Include>;
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/merge.xsl b/sources/shiboken2/ApiExtractor/merge.xsl
deleted file mode 100644
index c6cab5a42..000000000
--- a/sources/shiboken2/ApiExtractor/merge.xsl
+++ /dev/null
@@ -1,82 +0,0 @@
-<?xml version="1.0"?>
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
- version="1.0">
- <xsl:output method="xml" indent="yes"/>
- <xsl:param name="lang" />
- <xsl:param name="source" />
-
- <xsl:template match="processing-instruction()" />
-
- <xsl:template match="/typesystem">
- <xsl:copy>
- <xsl:for-each select="@*">
- <xsl:copy>
- <xsl:value-of select="." />
- </xsl:copy>
- </xsl:for-each>
-
- <xsl:for-each select="document($source)/typesystem/@*">
- <xsl:copy>
- <xsl:value-of select="." />
- </xsl:copy>
- </xsl:for-each>
-
- <xsl:variable name="other" select="document($source)/typesystem/*[not(self::object-type | self::value-type | self::interface-type | self::namespace-type)]" />
- <xsl:if test="$other">
- <xsl:choose>
- <xsl:when test="$lang != ''">
- <xsl:element name="language">
- <xsl:attribute name="name" ><xsl:value-of select="$lang" /></xsl:attribute>
- <xsl:copy-of select="$other" />
- </xsl:element>
- </xsl:when>
- <xsl:otherwise>
- <xsl:copy-of select="$other" />
- </xsl:otherwise>
- </xsl:choose>
- </xsl:if>
-
- <xsl:apply-templates select="node()" />
-
- </xsl:copy>
- </xsl:template>
-
-
-
- <xsl:template match="/typesystem/*[self::object-type | self::value-type | self::interface-type | self::namespace-type]">
- <xsl:variable name="name" select="name()" />
- <xsl:copy>
- <xsl:for-each select="@*">
- <xsl:copy>
- <xsl:value-of select="." />
- </xsl:copy>
- </xsl:for-each>
-
- <xsl:apply-templates select="node()" />
-
- <xsl:variable name="other" select="document($source)/typesystem/*[name() = $name][@name = current()/@name]" />
- <xsl:if test="$other">
- <xsl:choose>
- <xsl:when test="$lang != ''">
- <xsl:element name="language">
- <xsl:attribute name="name" ><xsl:value-of select="$lang" /></xsl:attribute>
- <xsl:copy-of select="$other/node()" />
- </xsl:element>
- </xsl:when>
- <xsl:otherwise>
- <xsl:copy-of select="$other/node()" />
- </xsl:otherwise>
- </xsl:choose>
- </xsl:if>
- </xsl:copy>
- </xsl:template>
-
- <!-- Plain identity transform. -->
- <xsl:template match="@*|node()">
- <xsl:copy>
- <xsl:apply-templates select="@*"/>
- <xsl:apply-templates select="node()"/>
- </xsl:copy>
- </xsl:template>
-
-</xsl:stylesheet>
diff --git a/sources/shiboken2/ApiExtractor/messages.cpp b/sources/shiboken2/ApiExtractor/messages.cpp
deleted file mode 100644
index 0e905c9a0..000000000
--- a/sources/shiboken2/ApiExtractor/messages.cpp
+++ /dev/null
@@ -1,575 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "messages.h"
-#include "abstractmetalang.h"
-#include "typedatabase.h"
-#include "typesystem.h"
-#include <codemodel.h>
-
-#include <QtCore/QCoreApplication>
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QStringList>
-#include <QtCore/QXmlStreamReader>
-
-static inline QString colonColon() { return QStringLiteral("::"); }
-
-// abstractmetabuilder.cpp
-
-QString msgNoFunctionForModification(const QString &signature,
- const QString &originalSignature,
- const QString &className,
- const QStringList &possibleSignatures,
- const AbstractMetaFunctionList &allFunctions)
-{
- QString result;
- QTextStream str(&result);
- str << "signature '" << signature << '\'';
- if (!originalSignature.isEmpty() && originalSignature != signature)
- str << " (specified as '" << originalSignature << "')";
- str << " for function modification in '"
- << className << "' not found.";
- if (!possibleSignatures.isEmpty()) {
- str << "\n Possible candidates:\n";
- for (const auto &s : possibleSignatures)
- str << " " << s << '\n';
- } else if (!allFunctions.isEmpty()) {
- str << "\n No candidates were found. Member functions:\n";
- const int maxCount = qMin(10, allFunctions.size());
- for (int f = 0; f < maxCount; ++f)
- str << " " << allFunctions.at(f)->minimalSignature() << '\n';
- if (maxCount < allFunctions.size())
- str << " ...\n";
- }
- return result;
-}
-
-template <class Stream>
-static void msgFormatEnumType(Stream &str,
- const EnumModelItem &enumItem,
- const QString &className)
-{
- switch (enumItem->enumKind()) {
- case CEnum:
- str << "Enum '" << enumItem->qualifiedName().join(colonColon()) << '\'';
- break;
- case AnonymousEnum: {
- const EnumeratorList &values = enumItem->enumerators();
- str << "Anonymous enum (";
- switch (values.size()) {
- case 0:
- break;
- case 1:
- str << values.constFirst()->name();
- break;
- case 2:
- str << values.at(0)->name() << ", " << values.at(1)->name();
- break;
- default:
- str << values.at(0)->name() << ", ... , "
- << values.at(values.size() - 1)->name();
- break;
- }
- str << ')';
- }
- break;
- case EnumClass:
- str << "Scoped enum '" << enumItem->qualifiedName().join(colonColon()) << '\'';
- break;
- }
- if (!className.isEmpty())
- str << " (class: " << className << ')';
-}
-
-QString msgAddedFunctionInvalidArgType(const QString &addedFuncName,
- const QString &typeName,
- int pos, const QString &why)
-{
- QString result;
- QTextStream str(&result);
- str << "Unable to translate type \"" << typeName << "\" of argument "
- << pos << " of added function \"" << addedFuncName << "\": " << why;
- return result;
-}
-
-QString msgAddedFunctionInvalidReturnType(const QString &addedFuncName,
- const QString &typeName, const QString &why)
-{
- QString result;
- QTextStream str(&result);
- str << "Unable to translate return type \"" << typeName
- << "\" of added function \"" << addedFuncName << "\": "
- << why;
- return result;
-}
-
-QString msgNoEnumTypeEntry(const EnumModelItem &enumItem,
- const QString &className)
-{
- QString result;
- QTextStream str(&result);
- msgFormatEnumType(str, enumItem, className);
- str << " does not have a type entry";
- return result;
-}
-
-QString msgNoEnumTypeConflict(const EnumModelItem &enumItem,
- const QString &className,
- const TypeEntry *t)
-{
- QString result;
- QDebug debug(&result); // Use the debug operator for TypeEntry::Type
- debug.noquote();
- debug.nospace();
- msgFormatEnumType(debug, enumItem, className);
- debug << " is not an enum (type: " << t->type() << ')';
- return result;
-}
-
-QString msgAmbiguousVaryingTypesFound(const QString &qualifiedName, const TypeEntries &te)
-{
- QString result = QLatin1String("Ambiguous types of varying types found for \"") + qualifiedName
- + QLatin1String("\": ");
- QDebug(&result) << te;
- return result;
-}
-
-QString msgAmbiguousTypesFound(const QString &qualifiedName, const TypeEntries &te)
-{
- QString result = QLatin1String("Ambiguous types found for \"") + qualifiedName
- + QLatin1String("\": ");
- QDebug(&result) << te;
- return result;
-}
-
-QString msgUnmatchedParameterType(const ArgumentModelItem &arg, int n,
- const QString &why)
-{
- QString result;
- QTextStream str(&result);
- str << "unmatched type '" << arg->type().toString() << "' in parameter #"
- << (n + 1);
- if (!arg->name().isEmpty())
- str << " \"" << arg->name() << '"';
- str << ": " << why;
- return result;
-}
-
-QString msgUnmatchedReturnType(const FunctionModelItem &functionItem,
- const QString &why)
-{
- return QLatin1String("unmatched return type '")
- + functionItem->type().toString()
- + QLatin1String("': ") + why;
-}
-
-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;
-}
-
-QString msgCannotResolveEntity(const QString &name, const QString &reason)
-{
- return QLatin1String("Cannot resolve entity \"") + name
- + QLatin1String("\": ") + reason;
-}
-
-QString msgCannotSetArrayUsage(const QString &function, int i, const QString &reason)
-{
- return function + QLatin1String(": Cannot use parameter ")
- + QString::number(i + 1) + QLatin1String(" as an array: ") + reason;
-}
-
-QString msgUnableToTranslateType(const QString &t, const QString &why)
-{
- return QLatin1String("Unable to translate type \"")
- + t + QLatin1String("\": ") + why;
-}
-
-QString msgUnableToTranslateType(const TypeInfo &typeInfo,
- const QString &why)
-{
- return msgUnableToTranslateType(typeInfo.toString(), why);
-}
-
-QString msgCannotFindTypeEntry(const QString &t)
-{
- return QLatin1String("Cannot find type entry for \"") + t + QLatin1String("\".");
-}
-
-QString msgCannotFindTypeEntryForSmartPointer(const QString &t, const QString &smartPointerType)
-{
- return QLatin1String("Cannot find type entry \"") + t
- + QLatin1String("\" for instantiation of \"") + smartPointerType + QLatin1String("\".");
-}
-
-QString msgInvalidSmartPointerType(const TypeInfo &i)
-{
- return QLatin1String("Invalid smart pointer type \"") + i.toString() + QLatin1String("\".");
-}
-
-QString msgCannotFindSmartPointerInstantion(const TypeInfo &i)
-{
- return QLatin1String("Cannot find instantiation of smart pointer type for \"")
- + i.toString() + QLatin1String("\".");
-}
-
-QString msgCannotTranslateTemplateArgument(int i,
- const TypeInfo &typeInfo,
- const QString &why)
-{
- QString result;
- QTextStream(&result) << "Unable to translate template argument "
- << (i + 1) << typeInfo.toString() << ": " << why;
- return result;
-}
-
-QString msgDisallowThread(const AbstractMetaFunction *f)
-{
- QString result;
- QTextStream str(&result);
- str <<"Disallowing threads for ";
- if (auto c = f->declaringClass())
- str << c->name() << "::";
- str << f->name() << "().";
- return result;
-}
-
-QString msgNamespaceToBeExtendedNotFound(const QString &namespaceName, const QString &packageName)
-{
- return QLatin1String("The namespace '") + namespaceName
- + QLatin1String("' to be extended cannot be found in package ")
- + packageName + QLatin1Char('.');
-}
-
-// docparser.cpp
-
-QString msgCannotFindDocumentation(const QString &fileName,
- const char *what, const QString &name,
- const QString &query)
-{
- QString result;
- QTextStream(&result) << "Cannot find documentation for " << what
- << ' ' << name << " in:\n " << QDir::toNativeSeparators(fileName)
- << "\n using query:\n " << query;
- return result;
-}
-
-QString msgCannotFindDocumentation(const QString &fileName,
- const AbstractMetaClass *metaClass,
- const AbstractMetaFunction *function,
- const QString &query)
-{
- const QString name = metaClass->name() + QLatin1String("::")
- + function->minimalSignature();
- return msgCannotFindDocumentation(fileName, "function", name, query);
-}
-
-QString msgCannotFindDocumentation(const QString &fileName,
- const AbstractMetaClass *metaClass,
- const AbstractMetaEnum *e,
- const QString &query)
-{
- return msgCannotFindDocumentation(fileName, "enum",
- metaClass->name() + QLatin1String("::") + e->name(),
- query);
-}
-
-QString msgCannotFindDocumentation(const QString &fileName,
- const AbstractMetaClass *metaClass,
- const AbstractMetaField *f,
- const QString &query)
-{
- return msgCannotFindDocumentation(fileName, "field",
- metaClass->name() + QLatin1String("::") + f->name(),
- query);
-}
-
-QString msgXpathDocModificationError(const DocModificationList& mods,
- const QString &what)
-{
- QString result;
- QTextStream str(&result);
- str << "Error when applying modifications (";
- for (const DocModification &mod : mods) {
- if (mod.mode() == TypeSystem::DocModificationXPathReplace) {
- str << '"' << mod.xpath() << "\" -> \"";
- const QString simplified = mod.code().simplified();
- if (simplified.size() > 20)
- str << simplified.leftRef(20) << "...";
- else
- str << simplified;
- str << '"';
- }
- }
- str << "): " << what;
- return result;
-}
-
-// fileout.cpp
-
-QString msgCannotOpenForReading(const QFile &f)
-{
- return QStringLiteral("Failed to open file '%1' for reading: %2")
- .arg(QDir::toNativeSeparators(f.fileName()), f.errorString());
-}
-
-QString msgCannotOpenForWriting(const QFile &f)
-{
- return QStringLiteral("Failed to open file '%1' for writing: %2")
- .arg(QDir::toNativeSeparators(f.fileName()), f.errorString());
-}
-
-// generator.cpp
-
-QString msgCannotUseEnumAsInt(const QString &name)
-{
- return QLatin1String("Cannot convert the protected scoped enum \"") + name
- + QLatin1String("\" to type int when generating wrappers for the protected hack. "
- "Compilation errors may occur when used as a function argument.");
-}
-
-QString msgConversionTypesDiffer(const QString &varType, const QString &conversionType)
-{
- QString result;
- QTextStream str(&result);
- str << "Types of receiver variable ('" << varType
- << "') and %%CONVERTTOCPP type system variable ('" << conversionType
- << "') differ";
- QString strippedVarType = varType;
- QString strippedConversionType = conversionType;
- TypeInfo::stripQualifiers(&strippedVarType);
- TypeInfo::stripQualifiers(&strippedConversionType);
- if (strippedVarType == strippedConversionType)
- str << " in qualifiers. Please make sure the type is a distinct token";
- str << '.';
- return result;
-}
-
-QString msgCannotFindSmartPointer(const QString &instantiationType,
- const AbstractMetaClassList &pointers)
-{
- QString result;
- QTextStream str(&result);
- str << "Unable to find smart pointer type for " << instantiationType << " (known types:";
- for (auto t : pointers) {
- auto typeEntry = t->typeEntry();
- str << ' ' << typeEntry->targetLangName() << '/' << typeEntry->qualifiedCppName();
- }
- str << ").";
- return result;
-}
-
-// main.cpp
-
-QString msgLeftOverArguments(const QMap<QString, QString> &remainingArgs)
-{
- QString message;
- QTextStream str(&message);
- str << "shiboken: Called with wrong arguments:";
- for (auto it = remainingArgs.cbegin(), end = remainingArgs.cend(); it != end; ++it) {
- str << ' ' << it.key();
- if (!it.value().isEmpty())
- str << ' ' << it.value();
- }
- str << "\nCommand line: " << QCoreApplication::arguments().join(QLatin1Char(' '));
- return message;
-}
-
-QString msgInvalidVersion(const QString &package, const QString &version)
-{
- return QLatin1String("Invalid version \"") + version
- + QLatin1String("\" specified for package ") + package + QLatin1Char('.');
-}
-
-QString msgCyclicDependency(const QString &funcName, const QString &graphName,
- const QVector<const AbstractMetaFunction *> &involvedConversions)
-{
- QString result;
- QTextStream str(&result);
- str << "Cyclic dependency found on overloaddata for \"" << funcName
- << "\" method! The graph boy saved the graph at \""
- << QDir::toNativeSeparators(graphName) << "\".";
- if (const int count = involvedConversions.size()) {
- str << " Implicit conversions (" << count << "): ";
- for (int i = 0; i < count; ++i) {
- if (i)
- str << ", \"";
- str << involvedConversions.at(i)->signature() << '"';
- if (const AbstractMetaClass *c = involvedConversions.at(i)->implementingClass())
- str << '(' << c->name() << ')';
- }
- }
- return result;
-}
-
-// shibokengenerator.cpp
-
-QString msgUnknownOperator(const AbstractMetaFunction* func)
-{
- QString result = QLatin1String("Unknown operator: \"") + func->originalName()
- + QLatin1Char('"');
- if (const AbstractMetaClass *c = func->implementingClass())
- result += QLatin1String(" in class: ") + c->name();
- return result;
-}
-
-QString msgWrongIndex(const char *varName, const QString &capture,
- const AbstractMetaFunction *func)
-{
- QString result;
- QTextStream str(&result);
- str << "Wrong index for " << varName << " variable (" << capture << ") on ";
- if (const AbstractMetaClass *c = func->implementingClass())
- str << c->name() << "::";
- str << func->signature();
- return result;
-}
-
-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;
-}
-
-QString msgCannotBuildMetaType(const QString &s)
-{
- return QLatin1String("Unable to build meta type for \"")
- + s + QLatin1String("\": ");
-}
-
-QString msgCouldNotFindMinimalConstructor(const QString &where, const QString &type)
-{
- return where + QLatin1String(": Could not find a minimal constructor for type '")
- + type + QLatin1String("'. This will result in a compilation error.");
-}
-
-// typedatabase.cpp
-
-QString msgRejectReason(const TypeRejection &r, const QString &needle)
-{
- QString result;
- QTextStream str(&result);
- switch (r.matchType) {
- case TypeRejection::ExcludeClass:
- str << " matches class exclusion \"" << r.className.pattern() << '"';
- break;
- case TypeRejection::Function:
- case TypeRejection::Field:
- case TypeRejection::Enum:
- str << " matches class \"" << r.className.pattern() << "\" and \""
- << r.pattern.pattern() << '"';
- break;
- case TypeRejection::ArgumentType:
- case TypeRejection::ReturnType:
- str << " matches class \"" << r.className.pattern() << "\" and \""
- << needle << "\" matches \"" << r.pattern.pattern() << '"';
- break;
- case TypeRejection::Invalid:
- break;
- }
- return result;
-}
-
-// typesystem.cpp
-
-QString msgCannotFindNamespaceToExtend(const QString &name,
- const QStringRef &extendsPackage)
-{
- return QLatin1String("Cannot find namespace ") + name
- + QLatin1String(" in package ") + extendsPackage;
-}
-
-QString msgExtendingNamespaceRequiresPattern(const QString &name)
-{
- return QLatin1String("Namespace ") + name
- + QLatin1String(" requires a file pattern since it extends another namespace.");
-}
-
-QString msgInvalidRegularExpression(const QString &pattern, const QString &why)
-{
- return QLatin1String("Invalid pattern \"") + pattern + QLatin1String("\": ") + why;
-}
-
-QString msgNoRootTypeSystemEntry()
-{
- return QLatin1String("Type system entry appears out of order, there does not seem to be a root type system element.");
-}
-
-QString msgIncorrectlyNestedName(const QString &name)
-{
- return QLatin1String("Nesting types by specifying '::' is no longer supported (")
- + name + QLatin1String(").");
-}
-
-// qtdocgenerator.cpp
-
-QString msgTagWarning(const QXmlStreamReader &reader, const QString &context,
- const QString &tag, const QString &message)
-{
- QString result;
- QTextStream str(&result);
- str << "While handling <";
- const QStringRef currentTag = reader.name();
- if (currentTag.isEmpty())
- str << tag;
- else
- str << currentTag;
- str << "> in " << context << ", line "<< reader.lineNumber()
- << ": " << message;
- return result;
-}
-
-QString msgFallbackWarning(const QXmlStreamReader &reader, const QString &context,
- const QString &tag, const QString &location,
- const QString &identifier, const QString &fallback)
-{
- QString message = QLatin1String("Falling back to \"")
- + QDir::toNativeSeparators(fallback) + QLatin1String("\" for \"")
- + location + QLatin1Char('"');
- if (!identifier.isEmpty())
- message += QLatin1String(" [") + identifier + QLatin1Char(']');
- return msgTagWarning(reader, context, tag, message);
-}
diff --git a/sources/shiboken2/ApiExtractor/messages.h b/sources/shiboken2/ApiExtractor/messages.h
deleted file mode 100644
index 3934c35b3..000000000
--- a/sources/shiboken2/ApiExtractor/messages.h
+++ /dev/null
@@ -1,176 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MESSAGES_H
-#define MESSAGES_H
-
-#include "abstractmetalang_typedefs.h"
-#include "parser/codemodel_fwd.h"
-#include "typesystem_typedefs.h"
-
-#include <QtCore/QMap>
-#include <QtCore/QString>
-#include <QtCore/QVector>
-
-class TypeEntry;
-class TypeInfo;
-struct TypeRejection;
-
-QT_FORWARD_DECLARE_CLASS(QDir)
-QT_FORWARD_DECLARE_CLASS(QFile)
-QT_FORWARD_DECLARE_CLASS(QXmlStreamReader)
-
-QString msgAddedFunctionInvalidArgType(const QString &addedFuncName,
- const QString &typeName,
- int pos, const QString &why);
-
-QString msgAddedFunctionInvalidReturnType(const QString &addedFuncName,
- const QString &typeName, const QString &why);
-
-QString msgNoFunctionForModification(const QString &signature,
- const QString &originalSignature,
- const QString &className,
- const QStringList &possibleSignatures,
- const AbstractMetaFunctionList &allFunctions);
-
-QString msgNoEnumTypeEntry(const EnumModelItem &enumItem,
- const QString &className);
-
-
-QString msgNoEnumTypeConflict(const EnumModelItem &enumItem,
- const QString &className,
- const TypeEntry *t);
-
-QString msgAmbiguousVaryingTypesFound(const QString &qualifiedName, const TypeEntries &te);
-QString msgAmbiguousTypesFound(const QString &qualifiedName, const TypeEntries &te);
-
-QString msgUnmatchedParameterType(const ArgumentModelItem &arg, int n,
- const QString &why);
-
-QString msgUnmatchedReturnType(const FunctionModelItem &functionItem,
- const QString &why);
-
-QString msgSkippingFunction(const FunctionModelItem &functionItem,
- const QString &signature, const QString &why);
-
-QString msgCannotResolveEntity(const QString &name, const QString &reason);
-
-QString msgCannotSetArrayUsage(const QString &function, int i, const QString &reason);
-
-QString msgUnableToTranslateType(const QString &t, const QString &why);
-
-QString msgUnableToTranslateType(const TypeInfo &typeInfo,
- const QString &why);
-
-QString msgCannotFindTypeEntry(const QString &t);
-
-QString msgCannotFindTypeEntryForSmartPointer(const QString &t, const QString &smartPointerType);
-QString msgInvalidSmartPointerType(const TypeInfo &i);
-QString msgCannotFindSmartPointerInstantion(const TypeInfo &i);
-
-QString msgCannotTranslateTemplateArgument(int i,
- const TypeInfo &typeInfo,
- const QString &why);
-
-QString msgDisallowThread(const AbstractMetaFunction *f);
-
-QString msgNamespaceToBeExtendedNotFound(const QString &namespaceName, const QString &packageName);
-
-QString msgCannotFindDocumentation(const QString &fileName,
- const char *what, const QString &name,
- const QString &query);
-
-QString msgCannotFindDocumentation(const QString &fileName,
- const AbstractMetaClass *metaClass,
- const AbstractMetaFunction *function,
- const QString &query);
-
-QString msgCannotFindDocumentation(const QString &fileName,
- const AbstractMetaClass *metaClass,
- const AbstractMetaEnum *e,
- const QString &query);
-
-QString msgCannotFindDocumentation(const QString &fileName,
- const AbstractMetaClass *metaClass,
- const AbstractMetaField *f,
- const QString &query);
-
-QString msgXpathDocModificationError(const DocModificationList& mods,
- const QString &what);
-
-QString msgCannotOpenForReading(const QFile &f);
-
-QString msgCannotOpenForWriting(const QFile &f);
-
-QString msgCannotUseEnumAsInt(const QString &name);
-
-QString msgConversionTypesDiffer(const QString &varType, const QString &conversionType);
-
-QString msgCannotFindSmartPointer(const QString &instantiationType,
- const AbstractMetaClassList &pointers);
-
-QString msgLeftOverArguments(const QMap<QString, QString> &remainingArgs);
-
-QString msgInvalidVersion(const QString &package, const QString &version);
-
-QString msgCannotFindNamespaceToExtend(const QString &name,
- const QStringRef &extendsPackage);
-
-QString msgExtendingNamespaceRequiresPattern(const QString &name);
-
-QString msgInvalidRegularExpression(const QString &pattern, const QString &why);
-
-QString msgNoRootTypeSystemEntry();
-
-QString msgIncorrectlyNestedName(const QString &name);
-
-QString msgCyclicDependency(const QString &funcName, const QString &graphName,
- const QVector<const AbstractMetaFunction *> &involvedConversions);
-
-QString msgUnknownOperator(const AbstractMetaFunction* func);
-
-QString msgWrongIndex(const char *varName, const QString &capture,
- const AbstractMetaFunction *func);
-
-QString msgCannotFindType(const QString &type, const QString &variable,
- const QString &why);
-
-QString msgCannotBuildMetaType(const QString &s);
-
-QString msgCouldNotFindMinimalConstructor(const QString &where, const QString &type);
-
-QString msgRejectReason(const TypeRejection &r, const QString &needle = QString());
-
-QString msgTagWarning(const QXmlStreamReader &reader, const QString &context,
- const QString &tag, const QString &message);
-
-QString msgFallbackWarning(const QXmlStreamReader &reader, const QString &context,
- const QString &tag, const QString &location,
- const QString &identifier, const QString &fallback);
-
-#endif // MESSAGES_H
diff --git a/sources/shiboken2/ApiExtractor/parser/codemodel.cpp b/sources/shiboken2/ApiExtractor/parser/codemodel.cpp
deleted file mode 100644
index e381ba083..000000000
--- a/sources/shiboken2/ApiExtractor/parser/codemodel.cpp
+++ /dev/null
@@ -1,1551 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "codemodel.h"
-
-#include <clangparser/clangutils.h>
-
-#include <algorithm>
-#include <functional>
-#include <iostream>
-#include <QDebug>
-#include <QDir>
-#include <QtCore/QStack>
-
-// Predicate to find an item by name in a list of QSharedPointer<Item>
-template <class T> class ModelItemNamePredicate
-{
-public:
- explicit ModelItemNamePredicate(const QString &name) : m_name(name) {}
- bool operator()(const QSharedPointer<T> &item) const { return item->name() == m_name; }
-
-private:
- const QString m_name;
-};
-
-template <class T>
-static QSharedPointer<T> findModelItem(const QVector<QSharedPointer<T> > &list, const QString &name)
-{
- const auto it = std::find_if(list.cbegin(), list.cend(), ModelItemNamePredicate<T>(name));
- return it != list.cend() ? *it : QSharedPointer<T>();
-}
-
-// ---------------------------------------------------------------------------
-
-CodeModel::CodeModel() : m_globalNamespace(new _NamespaceModelItem(this))
-{
-}
-
-CodeModel::~CodeModel() = default;
-
-NamespaceModelItem CodeModel::globalNamespace() const
-{
- return m_globalNamespace;
-}
-
-void CodeModel::addFile(const FileModelItem &item)
-{
- m_files.append(item);
-}
-
-FileModelItem CodeModel::findFile(const QString &name) const
-{
- return findModelItem(m_files, name);
-}
-
-static CodeModelItem findRecursion(const ScopeModelItem &scope,
- const QStringList &qualifiedName, int segment = 0)
-{
- const QString &nameSegment = qualifiedName.at(segment);
- if (segment == qualifiedName.size() - 1) { // Leaf item
- if (ClassModelItem cs = scope->findClass(nameSegment))
- return cs;
- if (EnumModelItem es = scope->findEnum(nameSegment))
- return es;
- if (TypeDefModelItem tp = scope->findTypeDef(nameSegment))
- return tp;
- if (TemplateTypeAliasModelItem tta = scope->findTemplateTypeAlias(nameSegment))
- return tta;
- return CodeModelItem();
- }
- if (auto nestedClass = scope->findClass(nameSegment))
- return findRecursion(nestedClass, qualifiedName, segment + 1);
- if (auto namespaceItem = qSharedPointerDynamicCast<_NamespaceModelItem>(scope)) {
- for (const auto &nestedNamespace : namespaceItem->namespaces()) {
- if (nestedNamespace->name() == nameSegment) {
- if (auto item = findRecursion(nestedNamespace, qualifiedName, segment + 1))
- return item;
- }
- }
- }
- return CodeModelItem();
-}
-
-CodeModelItem CodeModel::findItem(const QStringList &qualifiedName, const ScopeModelItem &scope) const
-{
- return findRecursion(scope, qualifiedName);
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const CodeModel *m)
-{
- QDebugStateSaver s(d);
- d.noquote();
- d.nospace();
- d << "CodeModel(";
- if (m) {
- const NamespaceModelItem globalNamespaceP = m->globalNamespace();
- if (globalNamespaceP.data())
- globalNamespaceP->formatDebug(d);
- } else {
- d << '0';
- }
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-TypeInfo TypeInfo::combine(const TypeInfo &__lhs, const TypeInfo &__rhs)
-{
- TypeInfo __result = __lhs;
-
- __result.setConstant(__result.isConstant() || __rhs.isConstant());
- __result.setVolatile(__result.isVolatile() || __rhs.isVolatile());
- if (__rhs.referenceType() > __result.referenceType())
- __result.setReferenceType(__rhs.referenceType());
- __result.m_indirections.append(__rhs.m_indirections);
- __result.setArrayElements(__result.arrayElements() + __rhs.arrayElements());
- __result.m_instantiations.append(__rhs.m_instantiations);
-
- return __result;
-}
-
-bool TypeInfo::isVoid() const
-{
- return m_indirections.isEmpty() && m_referenceType == NoReference
- && m_arguments.isEmpty() && m_arrayElements.isEmpty()
- && m_instantiations.isEmpty()
- && m_qualifiedName.size() == 1
- && m_qualifiedName.constFirst() == QLatin1String("void");
-}
-
-TypeInfo TypeInfo::resolveType(TypeInfo const &__type, const ScopeModelItem &__scope)
-{
- CodeModel *__model = __scope->model();
- Q_ASSERT(__model != nullptr);
-
- return TypeInfo::resolveType(__model->findItem(__type.qualifiedName(), __scope), __type, __scope);
-}
-
-TypeInfo TypeInfo::resolveType(CodeModelItem __item, TypeInfo const &__type, const ScopeModelItem &__scope)
-{
- // Copy the type and replace with the proper qualified name. This
- // only makes sence to do if we're actually getting a resolved
- // type with a namespace. We only get this if the returned type
- // has more than 2 entries in the qualified name... This test
- // could be improved by returning if the type was found or not.
- TypeInfo otherType(__type);
- if (__item && __item->qualifiedName().size() > 1) {
- otherType.setQualifiedName(__item->qualifiedName());
- }
-
- if (TypeDefModelItem __typedef = qSharedPointerDynamicCast<_TypeDefModelItem>(__item)) {
- const TypeInfo combined = TypeInfo::combine(__typedef->type(), otherType);
- const CodeModelItem nextItem = __scope->model()->findItem(combined.qualifiedName(), __scope);
- if (!nextItem)
- return combined;
- // PYSIDE-362, prevent recursion on opaque structs like
- // typedef struct xcb_connection_t xcb_connection_t;
- if (nextItem.data() ==__item.data()) {
- std::cerr << "** WARNING Bailing out recursion of " << __FUNCTION__
- << "() on " << qPrintable(__type.qualifiedName().join(QLatin1String("::")))
- << std::endl;
- return otherType;
- }
- return resolveType(nextItem, combined, __scope);
- }
-
- if (TemplateTypeAliasModelItem templateTypeAlias = qSharedPointerDynamicCast<_TemplateTypeAliasModelItem>(__item)) {
-
- TypeInfo combined = TypeInfo::combine(templateTypeAlias->type(), otherType);
- // For the alias "template<typename T> using QList = QVector<T>" with
- // other="QList<int>", replace the instantiations to obtain "QVector<int>".
- auto aliasInstantiations = templateTypeAlias->type().instantiations();
- auto concreteInstantiations = otherType.instantiations();
- const int count = qMin(aliasInstantiations.size(), concreteInstantiations.size());
- for (int i = 0; i < count; ++i)
- aliasInstantiations[i] = concreteInstantiations[i];
- combined.setInstantiations(aliasInstantiations);
- const CodeModelItem nextItem = __scope->model()->findItem(combined.qualifiedName(), __scope);
- if (!nextItem)
- return combined;
- return resolveType(nextItem, combined, __scope);
- }
-
- return otherType;
-}
-
-// Handler for clang::parseTemplateArgumentList() that populates
-// TypeInfo::m_instantiations
-class TypeInfoTemplateArgumentHandler
-{
-public:
- explicit TypeInfoTemplateArgumentHandler(TypeInfo *t)
- {
- m_parseStack.append(t);
- }
-
- void operator()(int level, const QStringRef &name)
- {
- if (level > m_parseStack.size()) {
- Q_ASSERT(!top()->m_instantiations.isEmpty());
- m_parseStack.push(&top()->m_instantiations.back());
- }
- while (level < m_parseStack.size())
- m_parseStack.pop();
- TypeInfo instantiation;
- instantiation.setQualifiedName(qualifiedName(name));
- top()->addInstantiation(instantiation);
- }
-
-private:
- TypeInfo *top() const { return m_parseStack.back(); }
-
- static QStringList qualifiedName(const QStringRef &name)
- {
- QStringList result;
- const QVector<QStringRef> nameParts = name.split(QLatin1String("::"));
- result.reserve(nameParts.size());
- for (const QStringRef &p : nameParts)
- result.append(p.toString());
- return result;
- }
-
- QStack<TypeInfo *> m_parseStack;
-};
-
-QPair<int, int> TypeInfo::parseTemplateArgumentList(const QString &l, int from)
-{
- return clang::parseTemplateArgumentList(l, clang::TemplateArgumentHandler(TypeInfoTemplateArgumentHandler(this)), from);
-}
-
-QString TypeInfo::toString() const
-{
- QString tmp;
- if (isConstant())
- tmp += QLatin1String("const ");
-
- if (isVolatile())
- tmp += QLatin1String("volatile ");
-
- tmp += m_qualifiedName.join(QLatin1String("::"));
-
- if (const int instantiationCount = m_instantiations.size()) {
- tmp += QLatin1Char('<');
- for (int i = 0; i < instantiationCount; ++i) {
- if (i)
- tmp += QLatin1String(", ");
- tmp += m_instantiations.at(i).toString();
- }
- if (tmp.endsWith(QLatin1Char('>')))
- tmp += QLatin1Char(' ');
- tmp += QLatin1Char('>');
- }
-
- for (Indirection i : m_indirections)
- tmp.append(indirectionKeyword(i));
-
- switch (referenceType()) {
- case NoReference:
- break;
- case LValueReference:
- tmp += QLatin1Char('&');
- break;
- case RValueReference:
- tmp += QLatin1String("&&");
- break;
- }
-
- if (isFunctionPointer()) {
- tmp += QLatin1String(" (*)(");
- for (int i = 0; i < m_arguments.count(); ++i) {
- if (i != 0)
- tmp += QLatin1String(", ");
-
- tmp += m_arguments.at(i).toString();
- }
- tmp += QLatin1Char(')');
- }
-
- for (const QString &elt : m_arrayElements) {
- tmp += QLatin1Char('[');
- tmp += elt;
- tmp += QLatin1Char(']');
- }
-
- return tmp;
-}
-
-bool TypeInfo::operator==(const TypeInfo &other) const
-{
- if (arrayElements().count() != other.arrayElements().count())
- return false;
-
-#if defined (RXX_CHECK_ARRAY_ELEMENTS) // ### it'll break
- for (int i = 0; i < arrayElements().count(); ++i) {
- QString elt1 = arrayElements().at(i).trimmed();
- QString elt2 = other.arrayElements().at(i).trimmed();
-
- if (elt1 != elt2)
- return false;
- }
-#endif
-
- return flags == other.flags
- && m_qualifiedName == other.m_qualifiedName
- && (!m_functionPointer || m_arguments == other.m_arguments)
- && m_instantiations == other.m_instantiations;
-}
-
-QString TypeInfo::indirectionKeyword(Indirection i)
-{
- return i == Indirection::Pointer
- ? QStringLiteral("*") : QStringLiteral("*const");
-}
-
-static inline QString constQualifier() { return QStringLiteral("const"); }
-static inline QString volatileQualifier() { return QStringLiteral("volatile"); }
-
-bool TypeInfo::stripLeadingConst(QString *s)
-{
- return stripLeadingQualifier(constQualifier(), s);
-}
-
-bool TypeInfo::stripLeadingVolatile(QString *s)
-{
- return stripLeadingQualifier(volatileQualifier(), s);
-}
-
-bool TypeInfo::stripLeadingQualifier(const QString &qualifier, QString *s)
-{
- // "const int x"
- const int qualifierSize = qualifier.size();
- if (s->size() < qualifierSize + 1 || !s->startsWith(qualifier)
- || !s->at(qualifierSize).isSpace()) {
- return false;
- }
- s->remove(0, qualifierSize + 1);
- while (!s->isEmpty() && s->at(0).isSpace())
- s->remove(0, 1);
- return true;
-}
-
-// Strip all const/volatile/*/&
-void TypeInfo::stripQualifiers(QString *s)
-{
- stripLeadingConst(s);
- stripLeadingVolatile(s);
- while (s->endsWith(QLatin1Char('&')) || s->endsWith(QLatin1Char('*'))
- || s->endsWith(QLatin1Char(' '))) {
- s->chop(1);
- }
-}
-
-// Helper functionality to simplify a raw standard type as returned by
-// clang_getCanonicalType() for g++ standard containers from
-// "std::__cxx11::list<int, std::allocator<int> >" or
-// "std::__1::list<int, std::allocator<int> >" -> "std::list<int>".
-
-bool TypeInfo::isStdType() const
-{
- return m_qualifiedName.size() > 1
- && m_qualifiedName.constFirst() == QLatin1String("std");
-}
-
-static inline bool discardStdType(const QString &name)
-{
- return name == QLatin1String("allocator") || name == QLatin1String("less");
-}
-
-void TypeInfo::simplifyStdType()
-{
- if (isStdType()) {
- if (m_qualifiedName.at(1).startsWith(QLatin1String("__")))
- m_qualifiedName.removeAt(1);
- for (int t = m_instantiations.size() - 1; t >= 0; --t) {
- if (m_instantiations.at(t).isStdType()) {
- if (discardStdType(m_instantiations.at(t).m_qualifiedName.constLast()))
- m_instantiations.removeAt(t);
- else
- m_instantiations[t].simplifyStdType();
- }
- }
- }
-}
-
-void TypeInfo::formatTypeSystemSignature(QTextStream &str) const
-{
- if (m_constant)
- str << "const ";
- str << m_qualifiedName.join(QLatin1String("::"));
- switch (m_referenceType) {
- case NoReference:
- break;
- case LValueReference:
- str << '&';
- break;
- case RValueReference:
- str << "&&";
- break;
- }
- for (auto i : m_indirections) {
- switch (i) {
- case Indirection::Pointer:
- str << '*';
- break;
- case Indirection::ConstPointer:
- str << "* const";
- break;
- }
- }
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-template <class It>
-void formatSequence(QDebug &d, It i1, It i2, const char *separator=", ")
-{
- for (It i = i1; i != i2; ++i) {
- if (i != i1)
- d << separator;
- d << *i;
- }
-}
-
-void TypeInfo::formatDebug(QDebug &d) const
-{
- d << '"';
- formatSequence(d, m_qualifiedName.begin(), m_qualifiedName.end(), "\", \"");
- d << '"';
- if (m_constant)
- d << ", [const]";
- if (m_volatile)
- d << ", [volatile]";
- if (!m_indirections.isEmpty()) {
- d << ", indirections=";
- for (auto i : m_indirections)
- d << ' ' << TypeInfo::indirectionKeyword(i);
- }
- switch (m_referenceType) {
- case NoReference:
- break;
- case LValueReference:
- d << ", [ref]";
- break;
- case RValueReference:
- d << ", [rvalref]";
- break;
- }
- if (!m_instantiations.isEmpty()) {
- d << ", template<";
- formatSequence(d, m_instantiations.begin(), m_instantiations.end());
- d << '>';
- }
- if (m_functionPointer) {
- d << ", function ptr(";
- formatSequence(d, m_arguments.begin(), m_arguments.end());
- d << ')';
- }
- if (!m_arrayElements.isEmpty()) {
- d << ", array[" << m_arrayElements.size() << "][";
- formatSequence(d, m_arrayElements.begin(), m_arrayElements.end());
- d << ']';
- }
-}
-
-QDebug operator<<(QDebug d, const TypeInfo &t)
-{
- QDebugStateSaver s(d);
-#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
- const int verbosity = d.verbosity();
-#else
- const int verbosity = 0;
-#endif
- d.noquote();
- d.nospace();
- d << "TypeInfo(";
- if (verbosity > 2)
- t.formatDebug(d);
- else
- d << t.toString();
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-_CodeModelItem::_CodeModelItem(CodeModel *model, int kind)
- : m_model(model),
- m_kind(kind),
- m_startLine(0),
- m_startColumn(0),
- m_endLine(0),
- m_endColumn(0)
-{
-}
-
-_CodeModelItem::_CodeModelItem(CodeModel *model, const QString &name, int kind)
- : m_model(model),
- m_kind(kind),
- m_startLine(0),
- m_startColumn(0),
- m_endLine(0),
- m_endColumn(0),
- m_name(name)
-{
-}
-
-_CodeModelItem::~_CodeModelItem() = default;
-
-int _CodeModelItem::kind() const
-{
- return m_kind;
-}
-
-QStringList _CodeModelItem::qualifiedName() const
-{
- QStringList q = scope();
-
- if (!name().isEmpty())
- q += name();
-
- return q;
-}
-
-QString _CodeModelItem::name() const
-{
- return m_name;
-}
-
-void _CodeModelItem::setName(const QString &name)
-{
- m_name = name;
-}
-
-QStringList _CodeModelItem::scope() const
-{
- return m_scope;
-}
-
-void _CodeModelItem::setScope(const QStringList &scope)
-{
- m_scope = scope;
-}
-
-QString _CodeModelItem::fileName() const
-{
- return m_fileName;
-}
-
-void _CodeModelItem::setFileName(const QString &fileName)
-{
- m_fileName = fileName;
-}
-
-FileModelItem _CodeModelItem::file() const
-{
- return model()->findFile(fileName());
-}
-
-void _CodeModelItem::getStartPosition(int *line, int *column)
-{
- *line = m_startLine;
- *column = m_startColumn;
-}
-
-void _CodeModelItem::setStartPosition(int line, int column)
-{
- m_startLine = line;
- m_startColumn = column;
-}
-
-void _CodeModelItem::getEndPosition(int *line, int *column)
-{
- *line = m_endLine;
- *column = m_endColumn;
-}
-
-void _CodeModelItem::setEndPosition(int line, int column)
-{
- m_endLine = line;
- m_endColumn = column;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-template <class It>
-static void formatPtrSequence(QDebug &d, It i1, It i2, const char *separator=", ")
-{
- for (It i = i1; i != i2; ++i) {
- if (i != i1)
- d << separator;
- d << i->data();
- }
-}
-
-void _CodeModelItem::formatKind(QDebug &d, int k)
-{
- switch (k) {
- case Kind_Argument:
- d << "ArgumentModelItem";
- break;
- case Kind_Class:
- d << "ClassModelItem";
- break;
- case Kind_Enum:
- d << "EnumModelItem";
- break;
- case Kind_Enumerator:
- d << "EnumeratorModelItem";
- break;
- case Kind_File:
- d << "FileModelItem";
- break;
- case Kind_Function:
- d << "FunctionModelItem";
- break;
- case Kind_Member:
- d << "MemberModelItem";
- break;
- case Kind_Namespace:
- d << "NamespaceModelItem";
- break;
- case Kind_Variable:
- d << "VariableModelItem";
- break;
- case Kind_Scope:
- d << "ScopeModelItem";
- break;
- case Kind_TemplateParameter:
- d << "TemplateParameter";
- break;
- case Kind_TypeDef:
- d << "TypeDefModelItem";
- break;
- case Kind_TemplateTypeAlias:
- d << "TemplateTypeAliasModelItem";
- break;
- default:
- d << "CodeModelItem";
- break;
- }
-}
-
-void _CodeModelItem::formatDebug(QDebug &d) const
-{
- d << "(\"" << name() << '"';
- if (!m_scope.isEmpty()) {
- d << ", scope=";
- formatSequence(d, m_scope.cbegin(), m_scope.cend(), "::");
- }
- if (!m_fileName.isEmpty()) {
- d << ", file=\"" << QDir::toNativeSeparators(m_fileName);
- if (m_startLine > 0)
- d << ':' << m_startLine;
- d << '"';
- }
-}
-
-QDebug operator<<(QDebug d, const _CodeModelItem *t)
-{
- QDebugStateSaver s(d);
- d.noquote();
- d.nospace();
- if (!t) {
- d << "CodeModelItem(0)";
- return d;
- }
- _CodeModelItem::formatKind(d, t->kind());
- t->formatDebug(d);
- switch (t->kind()) {
- case _CodeModelItem::Kind_Class:
- d << " /* class " << t->name() << " */";
- break;
- case _CodeModelItem::Kind_Namespace:
- d << " /* namespace " << t->name() << " */";
- break;
- }
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-_ClassModelItem::~_ClassModelItem() = default;
-
-TemplateParameterList _ClassModelItem::templateParameters() const
-{
- return m_templateParameters;
-}
-
-void _ClassModelItem::setTemplateParameters(const TemplateParameterList &templateParameters)
-{
- m_templateParameters = templateParameters;
-}
-
-void _ClassModelItem::addBaseClass(const QString &name, CodeModel::AccessPolicy accessPolicy)
-{
- _ClassModelItem::BaseClass baseClass;
- baseClass.name = name;
- baseClass.accessPolicy = accessPolicy;
- m_baseClasses.append(baseClass);
-}
-
-bool _ClassModelItem::extendsClass(const QString &name) const
-{
- for (const BaseClass &bc : m_baseClasses) {
- if (bc.name == name)
- return true;
- }
- return false;
-}
-
-void _ClassModelItem::setClassType(CodeModel::ClassType type)
-{
- m_classType = type;
-}
-
-CodeModel::ClassType _ClassModelItem::classType() const
-{
- return m_classType;
-}
-
-void _ClassModelItem::addPropertyDeclaration(const QString &propertyDeclaration)
-{
- m_propertyDeclarations << propertyDeclaration;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-template <class List>
-static void formatModelItemList(QDebug &d, const char *prefix, const List &l,
- const char *separator = ", ")
-{
- if (const int size = l.size()) {
- d << prefix << '[' << size << "](";
- for (int i = 0; i < size; ++i) {
- if (i)
- d << separator;
- l.at(i)->formatDebug(d);
- }
- d << ')';
- }
-}
-
-void _ClassModelItem::formatDebug(QDebug &d) const
-{
- _ScopeModelItem::formatDebug(d);
- if (!m_baseClasses.isEmpty()) {
- if (m_final)
- d << " [final]";
- d << ", inherits=";
- d << ", inherits=";
- for (int i = 0, size = m_baseClasses.size(); i < size; ++i) {
- if (i)
- d << ", ";
- d << m_baseClasses.at(i).name << " (" << m_baseClasses.at(i).accessPolicy << ')';
- }
- }
- formatModelItemList(d, ", templateParameters=", m_templateParameters);
- formatScopeItemsDebug(d);
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-FunctionModelItem _ScopeModelItem::declaredFunction(const FunctionModelItem &item)
-{
- for (const FunctionModelItem &fun : qAsConst(m_functions)) {
- if (fun->name() == item->name() && fun->isSimilar(item))
- return fun;
-
- }
- return FunctionModelItem();
-}
-
-_ScopeModelItem::~_ScopeModelItem() = default;
-
-void _ScopeModelItem::addEnumsDeclaration(const QString &enumsDeclaration)
-{
- m_enumsDeclarations << enumsDeclaration;
-}
-
-void _ScopeModelItem::addClass(const ClassModelItem &item)
-{
- m_classes.append(item);
-}
-
-void _ScopeModelItem::addFunction(const FunctionModelItem &item)
-{
- m_functions.append(item);
-}
-
-void _ScopeModelItem::addVariable(const VariableModelItem &item)
-{
- m_variables.append(item);
-}
-
-void _ScopeModelItem::addTypeDef(const TypeDefModelItem &item)
-{
- m_typeDefs.append(item);
-}
-
-void _ScopeModelItem::addTemplateTypeAlias(const TemplateTypeAliasModelItem &item)
-{
- m_templateTypeAliases.append(item);
-}
-
-void _ScopeModelItem::addEnum(const EnumModelItem &item)
-{
- m_enums.append(item);
-}
-
-void _ScopeModelItem::appendScope(const _ScopeModelItem &other)
-{
- m_classes += other.m_classes;
- m_enums += other.m_enums;
- m_typeDefs += other.m_typeDefs;
- m_templateTypeAliases += other.m_templateTypeAliases;
- m_variables += other.m_variables;
- m_functions += other.m_functions;
- m_enumsDeclarations += other.m_enumsDeclarations;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-template <class Hash>
-static void formatScopeHash(QDebug &d, const char *prefix, const Hash &h,
- const char *separator = ", ",
- bool trailingNewLine = false)
-{
- if (!h.isEmpty()) {
- d << prefix << '[' << h.size() << "](";
- const auto begin = h.cbegin();
- for (auto it = begin, end = h.cend(); it != end; ++it) { // Omit the names as they are repeated
- if (it != begin)
- d << separator;
- d << it.value().data();
- }
- d << ')';
- if (trailingNewLine)
- d << '\n';
- }
-}
-
-template <class List>
-static void formatScopeList(QDebug &d, const char *prefix, const List &l,
- const char *separator = ", ",
- bool trailingNewLine = false)
-{
- if (!l.isEmpty()) {
- d << prefix << '[' << l.size() << "](";
- formatPtrSequence(d, l.begin(), l.end(), separator);
- d << ')';
- if (trailingNewLine)
- d << '\n';
- }
-}
-
-void _ScopeModelItem::formatScopeItemsDebug(QDebug &d) const
-{
- formatScopeList(d, ", classes=", m_classes, "\n", true);
- formatScopeList(d, ", enums=", m_enums, "\n", true);
- formatScopeList(d, ", aliases=", m_typeDefs, "\n", true);
- formatScopeList(d, ", template type aliases=", m_templateTypeAliases, "\n", true);
- formatScopeList(d, ", functions=", m_functions, "\n", true);
- formatScopeList(d, ", variables=", m_variables);
-}
-
-void _ScopeModelItem::formatDebug(QDebug &d) const
-{
- _CodeModelItem::formatDebug(d);
- formatScopeItemsDebug(d);
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-namespace {
-// Predicate to match a non-template class name against the class list.
-// "Vector" should match "Vector" as well as "Vector<T>" (as seen for methods
-// from within the class "Vector").
-class ClassNamePredicate
-{
-public:
- explicit ClassNamePredicate(const QString &name) : m_name(name) {}
- bool operator()(const ClassModelItem &item) const
- {
- const QString &itemName = item->name();
- if (!itemName.startsWith(m_name))
- return false;
- return itemName.size() == m_name.size() || itemName.at(m_name.size()) == QLatin1Char('<');
- }
-
-private:
- const QString m_name;
-};
-} // namespace
-
-ClassModelItem _ScopeModelItem::findClass(const QString &name) const
-{
- // A fully qualified template is matched by name only
- const ClassList::const_iterator it = name.contains(QLatin1Char('<'))
- ? std::find_if(m_classes.begin(), m_classes.end(), ModelItemNamePredicate<_ClassModelItem>(name))
- : std::find_if(m_classes.begin(), m_classes.end(), ClassNamePredicate(name));
- return it != m_classes.end() ? *it : ClassModelItem();
-}
-
-VariableModelItem _ScopeModelItem::findVariable(const QString &name) const
-{
- return findModelItem(m_variables, name);
-}
-
-TypeDefModelItem _ScopeModelItem::findTypeDef(const QString &name) const
-{
- return findModelItem(m_typeDefs, name);
-}
-
-TemplateTypeAliasModelItem _ScopeModelItem::findTemplateTypeAlias(const QString &name) const
-{
- return findModelItem(m_templateTypeAliases, name);
-}
-
-EnumModelItem _ScopeModelItem::findEnum(const QString &name) const
-{
- return findModelItem(m_enums, name);
-}
-
-FunctionList _ScopeModelItem::findFunctions(const QString &name) const
-{
- FunctionList result;
- for (const FunctionModelItem &func : m_functions) {
- if (func->name() == name)
- result.append(func);
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-_NamespaceModelItem::~_NamespaceModelItem()
-{
-}
-
-void _NamespaceModelItem::addNamespace(NamespaceModelItem item)
-{
- m_namespaces.append(item);
-}
-
-NamespaceModelItem _NamespaceModelItem::findNamespace(const QString &name) const
-{
- return findModelItem(m_namespaces, name);
-}
-
-_FileModelItem::~_FileModelItem() = default;
-
-void _NamespaceModelItem::appendNamespace(const _NamespaceModelItem &other)
-{
- appendScope(other);
- m_namespaces += other.m_namespaces;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _NamespaceModelItem::formatDebug(QDebug &d) const
-{
- _ScopeModelItem::formatDebug(d);
- switch (m_type) {
- case NamespaceType::Default:
- break;
- case NamespaceType::Anonymous:
- d << ", anonymous";
- break;
- case NamespaceType::Inline:
- d << ", inline";
- break;
- }
- formatScopeList(d, ", namespaces=", m_namespaces);
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-_ArgumentModelItem::~_ArgumentModelItem()
-{
-}
-
-TypeInfo _ArgumentModelItem::type() const
-{
- return m_type;
-}
-
-void _ArgumentModelItem::setType(const TypeInfo &type)
-{
- m_type = type;
-}
-
-bool _ArgumentModelItem::defaultValue() const
-{
- return m_defaultValue;
-}
-
-void _ArgumentModelItem::setDefaultValue(bool defaultValue)
-{
- m_defaultValue = defaultValue;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _ArgumentModelItem::formatDebug(QDebug &d) const
-{
- _CodeModelItem::formatDebug(d);
- d << ", type=" << m_type;
- if (m_defaultValue)
- d << ", defaultValue=\"" << m_defaultValueExpression << '"';
-}
-#endif // !QT_NO_DEBUG_STREAM
-// ---------------------------------------------------------------------------
-_FunctionModelItem::~_FunctionModelItem() = default;
-
-bool _FunctionModelItem::isSimilar(const FunctionModelItem &other) const
-{
- if (name() != other->name())
- return false;
-
- if (isConstant() != other->isConstant())
- return false;
-
- if (isVariadics() != other->isVariadics())
- return false;
-
- if (arguments().count() != other->arguments().count())
- return false;
-
- // ### check the template parameters
-
- for (int i = 0; i < arguments().count(); ++i) {
- ArgumentModelItem arg1 = arguments().at(i);
- ArgumentModelItem arg2 = other->arguments().at(i);
-
- if (arg1->type() != arg2->type())
- return false;
- }
-
- return true;
-}
-
-ArgumentList _FunctionModelItem::arguments() const
-{
- return m_arguments;
-}
-
-void _FunctionModelItem::addArgument(const ArgumentModelItem& item)
-{
- m_arguments.append(item);
-}
-
-CodeModel::FunctionType _FunctionModelItem::functionType() const
-{
- return m_functionType;
-}
-
-void _FunctionModelItem::setFunctionType(CodeModel::FunctionType functionType)
-{
- m_functionType = functionType;
-}
-
-bool _FunctionModelItem::isVariadics() const
-{
- return m_isVariadics;
-}
-
-void _FunctionModelItem::setVariadics(bool isVariadics)
-{
- m_isVariadics = isVariadics;
-}
-
-bool _FunctionModelItem::isNoExcept() const
-{
- return m_exceptionSpecification == ExceptionSpecification::NoExcept;
-}
-
-ExceptionSpecification _FunctionModelItem::exceptionSpecification() const
-{
- return m_exceptionSpecification;
-}
-
-void _FunctionModelItem::setExceptionSpecification(ExceptionSpecification e)
-{
- m_exceptionSpecification = e;
-}
-
-bool _FunctionModelItem::isDeleted() const
-{
- return m_isDeleted;
-}
-
-void _FunctionModelItem::setDeleted(bool d)
-{
- m_isDeleted = d;
-}
-
-bool _FunctionModelItem::isDeprecated() const
-{
- return m_isDeprecated;
-}
-
-void _FunctionModelItem::setDeprecated(bool d)
-{
- m_isDeprecated = d;
-}
-
-bool _FunctionModelItem::isVirtual() const
-{
- return m_isVirtual;
-}
-
-void _FunctionModelItem::setVirtual(bool isVirtual)
-{
- m_isVirtual = isVirtual;
-}
-
-bool _FunctionModelItem::isInline() const
-{
- return m_isInline;
-}
-
-bool _FunctionModelItem::isOverride() const
-{
- return m_isOverride;
-}
-
-void _FunctionModelItem::setOverride(bool o)
-{
- m_isOverride = o;
-}
-
-bool _FunctionModelItem::isFinal() const
-{
- return m_isFinal;
-}
-
-void _FunctionModelItem::setFinal(bool f)
-{
- m_isFinal = f;
-}
-
-void _FunctionModelItem::setInline(bool isInline)
-{
- m_isInline = isInline;
-}
-
-bool _FunctionModelItem::isExplicit() const
-{
- return m_isExplicit;
-}
-
-void _FunctionModelItem::setExplicit(bool isExplicit)
-{
- m_isExplicit = isExplicit;
-}
-
-bool _FunctionModelItem::isAbstract() const
-{
- return m_isAbstract;
-}
-
-void _FunctionModelItem::setAbstract(bool isAbstract)
-{
- m_isAbstract = isAbstract;
-}
-
-// Qt
-bool _FunctionModelItem::isInvokable() const
-{
- return m_isInvokable;
-}
-
-void _FunctionModelItem::setInvokable(bool isInvokable)
-{
- m_isInvokable = isInvokable;
-}
-
-QString _FunctionModelItem::typeSystemSignature() const // For dumping out type system files
-{
- QString result;
- QTextStream str(&result);
- str << name() << '(';
- for (int a = 0, size = m_arguments.size(); a < size; ++a) {
- if (a)
- str << ',';
- m_arguments.at(a)->type().formatTypeSystemSignature(str);
- }
- str << ')';
- return result;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _FunctionModelItem::formatDebug(QDebug &d) const
-{
- _MemberModelItem::formatDebug(d);
- d << ", type=" << m_functionType << ", exspec=" << int(m_exceptionSpecification);
- if (m_isDeleted)
- d << " [deleted!]";
- if (m_isInline)
- d << " [inline]";
- if (m_isVirtual)
- d << " [virtual]";
- if (m_isOverride)
- d << " [override]";
- if (m_isDeprecated)
- d << " [deprecated]";
- if (m_isFinal)
- d << " [final]";
- if (m_isAbstract)
- d << " [abstract]";
- if (m_isExplicit)
- d << " [explicit]";
- if (m_isInvokable)
- d << " [invokable]";
- formatModelItemList(d, ", arguments=", m_arguments);
- if (m_isVariadics)
- d << ",...";
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-TypeInfo _TypeDefModelItem::type() const
-{
- return m_type;
-}
-
-void _TypeDefModelItem::setType(const TypeInfo &type)
-{
- m_type = type;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _TypeDefModelItem::formatDebug(QDebug &d) const
-{
- _CodeModelItem::formatDebug(d);
- d << ", type=" << m_type;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-
-_TemplateTypeAliasModelItem::_TemplateTypeAliasModelItem(CodeModel *model, int kind)
- : _CodeModelItem(model, kind) {}
-
-_TemplateTypeAliasModelItem::_TemplateTypeAliasModelItem(CodeModel *model, const QString &name, int kind)
- : _CodeModelItem(model, name, kind) {}
-
-TemplateParameterList _TemplateTypeAliasModelItem::templateParameters() const
-{
- return m_templateParameters;
-}
-
-void _TemplateTypeAliasModelItem::addTemplateParameter(const TemplateParameterModelItem &templateParameter)
-{
- m_templateParameters.append(templateParameter);
-}
-
-TypeInfo _TemplateTypeAliasModelItem::type() const
-{
- return m_type;
-}
-
-void _TemplateTypeAliasModelItem::setType(const TypeInfo &type)
-{
- m_type = type;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _TemplateTypeAliasModelItem::formatDebug(QDebug &d) const
-{
- _CodeModelItem::formatDebug(d);
- d << ", <";
- for (int i = 0, count = m_templateParameters.size(); i < count; ++i) {
- if (i)
- d << ", ";
- d << m_templateParameters.at(i)->name();
- }
- d << ">, type=" << m_type;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-CodeModel::AccessPolicy _EnumModelItem::accessPolicy() const
-{
- return m_accessPolicy;
-}
-
-_EnumModelItem::~_EnumModelItem() = default;
-
-void _EnumModelItem::setAccessPolicy(CodeModel::AccessPolicy accessPolicy)
-{
- m_accessPolicy = accessPolicy;
-}
-
-EnumeratorList _EnumModelItem::enumerators() const
-{
- return m_enumerators;
-}
-
-void _EnumModelItem::addEnumerator(const EnumeratorModelItem &item)
-{
- m_enumerators.append(item);
-}
-
-bool _EnumModelItem::isSigned() const
-{
- return m_signed;
-}
-
-void _EnumModelItem::setSigned(bool s)
-{
- m_signed = s;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _EnumModelItem::formatDebug(QDebug &d) const
-{
- _CodeModelItem::formatDebug(d);
- switch (m_enumKind) {
- case CEnum:
- break;
- case AnonymousEnum:
- d << " (anonymous)";
- break;
- case EnumClass:
- d << " (class)";
- break;
- }
- if (!m_signed)
- d << " (unsigned)";
- formatModelItemList(d, ", enumerators=", m_enumerators);
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-_EnumeratorModelItem::~_EnumeratorModelItem() = default;
-
-QString _EnumeratorModelItem::stringValue() const
-{
- return m_stringValue;
-}
-
-void _EnumeratorModelItem::setStringValue(const QString &value)
-{
- m_stringValue = value;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _EnumeratorModelItem::formatDebug(QDebug &d) const
-{
- _CodeModelItem::formatDebug(d);
- d << ", value=" << m_value << ", stringValue=\"" << m_stringValue << '"';
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-_TemplateParameterModelItem::~_TemplateParameterModelItem() = default;
-
-TypeInfo _TemplateParameterModelItem::type() const
-{
- return m_type;
-}
-
-void _TemplateParameterModelItem::setType(const TypeInfo &type)
-{
- m_type = type;
-}
-
-bool _TemplateParameterModelItem::defaultValue() const
-{
- return m_defaultValue;
-}
-
-void _TemplateParameterModelItem::setDefaultValue(bool defaultValue)
-{
- m_defaultValue = defaultValue;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _TemplateParameterModelItem::formatDebug(QDebug &d) const
-{
- _CodeModelItem::formatDebug(d);
- d << ", type=" << m_type;
- if (m_defaultValue)
- d << " [defaultValue]";
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// ---------------------------------------------------------------------------
-TypeInfo _MemberModelItem::type() const
-{
- return m_type;
-}
-
-void _MemberModelItem::setType(const TypeInfo &type)
-{
- m_type = type;
-}
-
-CodeModel::AccessPolicy _MemberModelItem::accessPolicy() const
-{
- return m_accessPolicy;
-}
-
-_MemberModelItem::~_MemberModelItem() = default;
-
-void _MemberModelItem::setAccessPolicy(CodeModel::AccessPolicy accessPolicy)
-{
- m_accessPolicy = accessPolicy;
-}
-
-bool _MemberModelItem::isStatic() const
-{
- return m_isStatic;
-}
-
-void _MemberModelItem::setStatic(bool isStatic)
-{
- m_isStatic = isStatic;
-}
-
-bool _MemberModelItem::isConstant() const
-{
- return m_isConstant;
-}
-
-void _MemberModelItem::setConstant(bool isConstant)
-{
- m_isConstant = isConstant;
-}
-
-bool _MemberModelItem::isVolatile() const
-{
- return m_isVolatile;
-}
-
-void _MemberModelItem::setVolatile(bool isVolatile)
-{
- m_isVolatile = isVolatile;
-}
-
-bool _MemberModelItem::isAuto() const
-{
- return m_isAuto;
-}
-
-void _MemberModelItem::setAuto(bool isAuto)
-{
- m_isAuto = isAuto;
-}
-
-bool _MemberModelItem::isFriend() const
-{
- return m_isFriend;
-}
-
-void _MemberModelItem::setFriend(bool isFriend)
-{
- m_isFriend = isFriend;
-}
-
-bool _MemberModelItem::isRegister() const
-{
- return m_isRegister;
-}
-
-void _MemberModelItem::setRegister(bool isRegister)
-{
- m_isRegister = isRegister;
-}
-
-bool _MemberModelItem::isExtern() const
-{
- return m_isExtern;
-}
-
-void _MemberModelItem::setExtern(bool isExtern)
-{
- m_isExtern = isExtern;
-}
-
-bool _MemberModelItem::isMutable() const
-{
- return m_isMutable;
-}
-
-void _MemberModelItem::setMutable(bool isMutable)
-{
- m_isMutable = isMutable;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void _MemberModelItem::formatDebug(QDebug &d) const
-{
- _CodeModelItem::formatDebug(d);
- switch (m_accessPolicy) {
- case CodeModel::Public:
- d << ", public";
- break;
- case CodeModel::Protected:
- d << ", protected";
- break;
- case CodeModel::Private:
- d << ", private";
- break;
- }
- d << ", type=";
- if (m_isConstant)
- d << "const ";
- if (m_isVolatile)
- d << "volatile ";
- if (m_isStatic)
- d << "static ";
- if (m_isAuto)
- d << "auto ";
- if (m_isFriend)
- d << "friend ";
- if (m_isRegister)
- d << "register ";
- if (m_isExtern)
- d << "extern ";
- if (m_isMutable)
- d << "mutable ";
- d << m_type;
- formatScopeList(d, ", templateParameters", m_templateParameters);
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-// kate: space-indent on; indent-width 2; replace-tabs on;
diff --git a/sources/shiboken2/ApiExtractor/parser/codemodel.h b/sources/shiboken2/ApiExtractor/parser/codemodel.h
deleted file mode 100644
index 5bbd9ed3e..000000000
--- a/sources/shiboken2/ApiExtractor/parser/codemodel.h
+++ /dev/null
@@ -1,804 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef CODEMODEL_H
-#define CODEMODEL_H
-
-#include "codemodel_fwd.h"
-#include "codemodel_enums.h"
-#include "enumvalue.h"
-
-#include <QtCore/QHash>
-#include <QtCore/QPair>
-#include <QtCore/QSet>
-#include <QtCore/QString>
-#include <QtCore/QStringList>
-#include <QtCore/QVector>
-
-QT_FORWARD_DECLARE_CLASS(QDebug)
-
-#define DECLARE_MODEL_NODE(k) \
- enum { __node_kind = Kind_##k };
-
-class CodeModel
-{
-public:
- Q_DISABLE_COPY(CodeModel)
-
- enum AccessPolicy {
- Public,
- Protected,
- Private
- };
-
- enum FunctionType {
- Normal,
- Constructor,
- CopyConstructor,
- MoveConstructor,
- Destructor,
- Signal,
- Slot
- };
-
- enum ClassType {
- Class,
- Struct,
- Union
- };
-
-public:
- CodeModel();
- virtual ~CodeModel();
-
- FileList files() const { return m_files; }
- NamespaceModelItem globalNamespace() const;
-
- void addFile(const FileModelItem &item);
- FileModelItem findFile(const QString &name) const;
-
- CodeModelItem findItem(const QStringList &qualifiedName, const ScopeModelItem &scope) const;
-
-private:
- FileList m_files;
- NamespaceModelItem m_globalNamespace;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const CodeModel *m);
-#endif
-
-class TypeInfo
-{
- friend class TypeParser;
-public:
- using Indirections = QVector<Indirection>;
-
- TypeInfo() : flags(0), m_referenceType(NoReference) {}
-
- QStringList qualifiedName() const
- {
- return m_qualifiedName;
- }
-
- void setQualifiedName(const QStringList &qualified_name)
- {
- m_qualifiedName = qualified_name;
- }
-
- bool isVoid() const;
-
- bool isConstant() const
- {
- return m_constant;
- }
-
- void setConstant(bool is)
- {
- m_constant = is;
- }
-
- bool isVolatile() const
- {
- return m_volatile;
- }
-
- void setVolatile(bool is)
- {
- m_volatile = is;
- }
-
- ReferenceType referenceType() const { return m_referenceType; }
- void setReferenceType(ReferenceType r) { m_referenceType = r; }
-
- Indirections indirectionsV() const { return m_indirections; }
- void setIndirectionsV(const Indirections &i) { m_indirections = i; }
- void addIndirection(Indirection i) { m_indirections.append(i); }
-
- // "Legacy", rename?
- int indirections() const { return m_indirections.size(); }
-
- void setIndirections(int indirections)
- {
- m_indirections = Indirections(indirections, Indirection::Pointer);
- }
-
- bool isFunctionPointer() const
- {
- return m_functionPointer;
- }
- void setFunctionPointer(bool is)
- {
- m_functionPointer = is;
- }
-
- QStringList arrayElements() const
- {
- return m_arrayElements;
- }
- void setArrayElements(const QStringList &arrayElements)
- {
- m_arrayElements = arrayElements;
- }
-
- void addArrayElement(const QString &a) { m_arrayElements.append(a); }
-
- QVector<TypeInfo> arguments() const { return m_arguments; }
-
- void setArguments(const QVector<TypeInfo> &arguments);
-
- void addArgument(const TypeInfo &arg)
- {
- m_arguments.append(arg);
- }
-
- QVector<TypeInfo> instantiations() const { return m_instantiations; }
- void setInstantiations(const QVector<TypeInfo> &i) { m_instantiations = i; }
- void addInstantiation(const TypeInfo &i) { m_instantiations.append(i); }
- void clearInstantiations() { m_instantiations.clear(); }
-
- bool isStdType() const;
-
- QPair<int, int> parseTemplateArgumentList(const QString &l, int from = 0);
-
- bool operator==(const TypeInfo &other) const;
-
- bool operator!=(const TypeInfo &other) const
- {
- return !(*this == other);
- }
-
- // ### arrays and templates??
-
- QString toString() const;
-
- static TypeInfo combine(const TypeInfo &__lhs, const TypeInfo &__rhs);
- static TypeInfo resolveType(TypeInfo const &__type, const ScopeModelItem &__scope);
-
- void formatTypeSystemSignature(QTextStream &str) const;
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const;
-#endif
-
- static QString indirectionKeyword(Indirection i);
-
- static bool stripLeadingConst(QString *s);
- static bool stripLeadingVolatile(QString *s);
- static bool stripLeadingQualifier(const QString &qualifier, QString *s);
- static void stripQualifiers(QString *s);
-
- void simplifyStdType();
-
-private:
- friend class TypeInfoTemplateArgumentHandler;
-
- static TypeInfo resolveType(CodeModelItem item, TypeInfo const &__type, const ScopeModelItem &__scope);
-
- QStringList m_qualifiedName;
- QStringList m_arrayElements;
- QVector<TypeInfo> m_arguments;
- QVector<TypeInfo> m_instantiations;
- Indirections m_indirections;
-
- union {
- uint flags;
-
- struct {
- uint m_constant: 1;
- uint m_volatile: 1;
- uint m_functionPointer: 1;
- uint m_padding: 29;
- };
- };
-
- ReferenceType m_referenceType;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const TypeInfo &t);
-#endif
-
-class _CodeModelItem
-{
- Q_DISABLE_COPY(_CodeModelItem)
-public:
- enum Kind {
- /* These are bit-flags resembling inheritance */
- Kind_Scope = 0x1,
- Kind_Namespace = 0x2 | Kind_Scope,
- Kind_Member = 0x4,
- Kind_Function = 0x8 | Kind_Member,
- KindMask = 0xf,
-
- /* These are for classes that are not inherited from */
- FirstKind = 0x8,
- Kind_Argument = 1 << FirstKind,
- Kind_Class = 2 << FirstKind | Kind_Scope,
- Kind_Enum = 3 << FirstKind,
- Kind_Enumerator = 4 << FirstKind,
- Kind_File = 5 << FirstKind | Kind_Namespace,
- Kind_TemplateParameter = 7 << FirstKind,
- Kind_TypeDef = 8 << FirstKind,
- Kind_TemplateTypeAlias = 9 << FirstKind,
- Kind_Variable = 10 << FirstKind | Kind_Member
- };
-
-public:
- virtual ~_CodeModelItem();
-
- int kind() const;
-
- QStringList qualifiedName() const;
-
- QString name() const;
- void setName(const QString &name);
-
- QStringList scope() const;
- void setScope(const QStringList &scope);
-
- QString fileName() const;
- void setFileName(const QString &fileName);
-
- FileModelItem file() const;
-
- void getStartPosition(int *line, int *column);
- int startLine() const { return m_startLine; }
- void setStartPosition(int line, int column);
-
- void getEndPosition(int *line, int *column);
- void setEndPosition(int line, int column);
-
- inline CodeModel *model() const { return m_model; }
-
-#ifndef QT_NO_DEBUG_STREAM
- static void formatKind(QDebug &d, int k);
- virtual void formatDebug(QDebug &d) const;
-#endif
-
-protected:
- explicit _CodeModelItem(CodeModel *model, int kind);
- explicit _CodeModelItem(CodeModel *model, const QString &name, int kind);
-
-private:
- CodeModel *m_model;
- int m_kind;
- int m_startLine;
- int m_startColumn;
- int m_endLine;
- int m_endColumn;
- QString m_name;
- QString m_fileName;
- QStringList m_scope;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const _CodeModelItem *t);
-#endif
-
-class _ScopeModelItem: public _CodeModelItem
-{
-public:
- DECLARE_MODEL_NODE(Scope)
-
- ~_ScopeModelItem();
-
- ClassList classes() const { return m_classes; }
- EnumList enums() const { return m_enums; }
- inline FunctionList functions() const { return m_functions; }
- TypeDefList typeDefs() const { return m_typeDefs; }
- TemplateTypeAliasList templateTypeAliases() const { return m_templateTypeAliases; }
- VariableList variables() const { return m_variables; }
-
- void addClass(const ClassModelItem &item);
- void addEnum(const EnumModelItem &item);
- void addFunction(const FunctionModelItem &item);
- void addTypeDef(const TypeDefModelItem &item);
- void addTemplateTypeAlias(const TemplateTypeAliasModelItem &item);
- void addVariable(const VariableModelItem &item);
-
- ClassModelItem findClass(const QString &name) const;
- EnumModelItem findEnum(const QString &name) const;
- FunctionList findFunctions(const QString &name) const;
- TypeDefModelItem findTypeDef(const QString &name) const;
- TemplateTypeAliasModelItem findTemplateTypeAlias(const QString &name) const;
- VariableModelItem findVariable(const QString &name) const;
-
- void addEnumsDeclaration(const QString &enumsDeclaration);
- QStringList enumsDeclarations() const { return m_enumsDeclarations; }
-
- FunctionModelItem declaredFunction(const FunctionModelItem &item);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-protected:
- explicit _ScopeModelItem(CodeModel *model, int kind = __node_kind)
- : _CodeModelItem(model, kind) {}
- explicit _ScopeModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _CodeModelItem(model, name, kind) {}
-
- void appendScope(const _ScopeModelItem &other);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatScopeItemsDebug(QDebug &d) const;
-#endif
-
-private:
- ClassList m_classes;
- EnumList m_enums;
- TypeDefList m_typeDefs;
- TemplateTypeAliasList m_templateTypeAliases;
- VariableList m_variables;
- FunctionList m_functions;
-
-private:
- QStringList m_enumsDeclarations;
-};
-
-class _ClassModelItem: public _ScopeModelItem
-{
-public:
- DECLARE_MODEL_NODE(Class)
-
- struct BaseClass
- {
- QString name;
- CodeModel::AccessPolicy accessPolicy = CodeModel::Public;
- };
-
- explicit _ClassModelItem(CodeModel *model, int kind = __node_kind)
- : _ScopeModelItem(model, kind), m_classType(CodeModel::Class) {}
- explicit _ClassModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _ScopeModelItem(model, name, kind), m_classType(CodeModel::Class) {}
- ~_ClassModelItem();
-
- QVector<BaseClass> baseClasses() const { return m_baseClasses; }
-
- void addBaseClass(const QString &name, CodeModel::AccessPolicy accessPolicy);
-
- TemplateParameterList templateParameters() const;
- void setTemplateParameters(const TemplateParameterList &templateParameters);
-
- bool extendsClass(const QString &name) const;
-
- void setClassType(CodeModel::ClassType type);
- CodeModel::ClassType classType() const;
-
- void addPropertyDeclaration(const QString &propertyDeclaration);
- QStringList propertyDeclarations() const { return m_propertyDeclarations; }
-
- bool isFinal() const { return m_final; }
- void setFinal(bool f) { m_final = f; }
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- QVector<BaseClass> m_baseClasses;
- TemplateParameterList m_templateParameters;
- CodeModel::ClassType m_classType;
-
- QStringList m_propertyDeclarations;
- bool m_final = false;
-};
-
-class _NamespaceModelItem: public _ScopeModelItem
-{
-public:
- DECLARE_MODEL_NODE(Namespace)
-
- explicit _NamespaceModelItem(CodeModel *model, int kind = __node_kind)
- : _ScopeModelItem(model, kind) {}
- explicit _NamespaceModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _ScopeModelItem(model, name, kind) {}
- ~_NamespaceModelItem();
-
- const NamespaceList &namespaces() const { return m_namespaces; }
-
- NamespaceType type() const { return m_type; }
- void setType(NamespaceType t) { m_type = t; }
-
- void addNamespace(NamespaceModelItem item);
-
- NamespaceModelItem findNamespace(const QString &name) const;
-
- void appendNamespace(const _NamespaceModelItem &other);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- NamespaceList m_namespaces;
- NamespaceType m_type = NamespaceType::Default;
-};
-
-class _FileModelItem: public _NamespaceModelItem
-{
-public:
- DECLARE_MODEL_NODE(File)
-
- explicit _FileModelItem(CodeModel *model, int kind = __node_kind)
- : _NamespaceModelItem(model, kind) {}
- explicit _FileModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _NamespaceModelItem(model, name, kind) {}
- ~_FileModelItem();
-};
-
-class _ArgumentModelItem: public _CodeModelItem
-{
-public:
- DECLARE_MODEL_NODE(Argument)
-
- explicit _ArgumentModelItem(CodeModel *model, int kind = __node_kind)
- : _CodeModelItem(model, kind), m_defaultValue(false) {}
- explicit _ArgumentModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _CodeModelItem(model, name, kind), m_defaultValue(false) {}
- ~_ArgumentModelItem();
-
- TypeInfo type() const;
- void setType(const TypeInfo &type);
-
- bool defaultValue() const;
- void setDefaultValue(bool defaultValue);
-
- QString defaultValueExpression() const { return m_defaultValueExpression; }
- void setDefaultValueExpression(const QString &expr) { m_defaultValueExpression = expr; }
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- TypeInfo m_type;
- QString m_defaultValueExpression;
- bool m_defaultValue;
-};
-
-class _MemberModelItem: public _CodeModelItem
-{
-public:
- DECLARE_MODEL_NODE(Member)
-
- explicit _MemberModelItem(CodeModel *model, int kind = __node_kind)
- : _CodeModelItem(model, kind), m_accessPolicy(CodeModel::Public), m_flags(0) {}
- explicit _MemberModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _CodeModelItem(model, name, kind), m_accessPolicy(CodeModel::Public), m_flags(0) {}
- ~_MemberModelItem();
-
- bool isConstant() const;
- void setConstant(bool isConstant);
-
- bool isVolatile() const;
- void setVolatile(bool isVolatile);
-
- bool isStatic() const;
- void setStatic(bool isStatic);
-
- bool isAuto() const;
- void setAuto(bool isAuto);
-
- bool isFriend() const;
- void setFriend(bool isFriend);
-
- bool isRegister() const;
- void setRegister(bool isRegister);
-
- bool isExtern() const;
- void setExtern(bool isExtern);
-
- bool isMutable() const;
- void setMutable(bool isMutable);
-
- CodeModel::AccessPolicy accessPolicy() const;
- void setAccessPolicy(CodeModel::AccessPolicy accessPolicy);
-
- TemplateParameterList templateParameters() const { return m_templateParameters; }
- void setTemplateParameters(const TemplateParameterList &templateParameters) { m_templateParameters = templateParameters; }
-
- TypeInfo type() const;
- void setType(const TypeInfo &type);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- TemplateParameterList m_templateParameters;
- TypeInfo m_type;
- CodeModel::AccessPolicy m_accessPolicy;
- union {
- struct {
- uint m_isConstant: 1;
- uint m_isVolatile: 1;
- uint m_isStatic: 1;
- uint m_isAuto: 1;
- uint m_isFriend: 1;
- uint m_isRegister: 1;
- uint m_isExtern: 1;
- uint m_isMutable: 1;
- };
- uint m_flags;
- };
-
-};
-
-class _FunctionModelItem: public _MemberModelItem
-{
-public:
- DECLARE_MODEL_NODE(Function)
-
- explicit _FunctionModelItem(CodeModel *model, int kind = __node_kind)
- : _MemberModelItem(model, kind), m_functionType(CodeModel::Normal), m_flags(0) {}
- explicit _FunctionModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _MemberModelItem(model, name, kind), m_functionType(CodeModel::Normal), m_flags(0) {}
- ~_FunctionModelItem();
-
- ArgumentList arguments() const;
-
- void addArgument(const ArgumentModelItem& item);
-
- CodeModel::FunctionType functionType() const;
- void setFunctionType(CodeModel::FunctionType functionType);
-
- bool isDeleted() const;
- void setDeleted(bool d);
-
- bool isDeprecated() const;
- void setDeprecated(bool d);
-
- bool isVirtual() const;
- void setVirtual(bool isVirtual);
-
- bool isOverride() const;
- void setOverride(bool o);
-
- bool isFinal() const;
- void setFinal(bool f);
-
- bool isInline() const;
- void setInline(bool isInline);
-
- bool isExplicit() const;
- void setExplicit(bool isExplicit);
-
- bool isInvokable() const; // Qt
- void setInvokable(bool isInvokable); // Qt
-
- bool isAbstract() const;
- void setAbstract(bool isAbstract);
-
- bool isVariadics() const;
- void setVariadics(bool isVariadics);
-
-
- bool isSimilar(const FunctionModelItem &other) const;
-
- bool isNoExcept() const;
-
- ExceptionSpecification exceptionSpecification() const;
- void setExceptionSpecification(ExceptionSpecification e);
-
- QString typeSystemSignature() const; // For dumping out type system files
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- ArgumentList m_arguments;
- CodeModel::FunctionType m_functionType;
- union {
- struct {
- uint m_isDeleted: 1;
- uint m_isVirtual: 1;
- uint m_isOverride: 1;
- uint m_isFinal: 1;
- uint m_isDeprecated: 1;
- uint m_isInline: 1;
- uint m_isAbstract: 1;
- uint m_isExplicit: 1;
- uint m_isVariadics: 1;
- uint m_isInvokable : 1; // Qt
- };
- uint m_flags;
- };
- ExceptionSpecification m_exceptionSpecification = ExceptionSpecification::Unknown;
-};
-
-class _VariableModelItem: public _MemberModelItem
-{
-public:
- DECLARE_MODEL_NODE(Variable)
-
- explicit _VariableModelItem(CodeModel *model, int kind = __node_kind)
- : _MemberModelItem(model, kind) {}
- explicit _VariableModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _MemberModelItem(model, name, kind) {}
-};
-
-class _TypeDefModelItem: public _CodeModelItem
-{
-public:
- DECLARE_MODEL_NODE(TypeDef)
-
- explicit _TypeDefModelItem(CodeModel *model, int kind = __node_kind)
- : _CodeModelItem(model, kind) {}
- explicit _TypeDefModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _CodeModelItem(model, name, kind) {}
-
- TypeInfo type() const;
- void setType(const TypeInfo &type);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- TypeInfo m_type;
-};
-
-class _TemplateTypeAliasModelItem : public _CodeModelItem
-{
-public:
- DECLARE_MODEL_NODE(TemplateTypeAlias)
-
- explicit _TemplateTypeAliasModelItem(CodeModel *model, int kind = __node_kind);
- explicit _TemplateTypeAliasModelItem(CodeModel *model, const QString &name,
- int kind = __node_kind);
-
- TemplateParameterList templateParameters() const;
- void addTemplateParameter(const TemplateParameterModelItem &templateParameter);
-
- TypeInfo type() const;
- void setType(const TypeInfo &type);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- TemplateParameterList m_templateParameters;
- TypeInfo m_type;
-};
-
-class _EnumModelItem: public _CodeModelItem
-{
-public:
- DECLARE_MODEL_NODE(Enum)
-
- explicit _EnumModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _CodeModelItem(model, name, kind) {}
- explicit _EnumModelItem(CodeModel *model, int kind = __node_kind)
- : _CodeModelItem(model, kind) {}
- ~_EnumModelItem();
-
- CodeModel::AccessPolicy accessPolicy() const;
- void setAccessPolicy(CodeModel::AccessPolicy accessPolicy);
-
- bool hasValues() const { return !m_enumerators.isEmpty(); }
- EnumeratorList enumerators() const;
- void addEnumerator(const EnumeratorModelItem &item);
-
- EnumKind enumKind() const { return m_enumKind; }
- void setEnumKind(EnumKind kind) { m_enumKind = kind; }
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
- bool isSigned() const;
- void setSigned(bool s);
-
-private:
- CodeModel::AccessPolicy m_accessPolicy = CodeModel::Public;
- EnumeratorList m_enumerators;
- EnumKind m_enumKind = CEnum;
- bool m_signed = true;
-};
-
-class _EnumeratorModelItem: public _CodeModelItem
-{
-public:
- DECLARE_MODEL_NODE(Enumerator)
-
- explicit _EnumeratorModelItem(CodeModel *model, int kind = __node_kind)
- : _CodeModelItem(model, kind) {}
- explicit _EnumeratorModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _CodeModelItem(model, name, kind) {}
- ~_EnumeratorModelItem();
-
- QString stringValue() const;
- void setStringValue(const QString &stringValue);
-
- EnumValue value() const { return m_value; }
- void setValue(EnumValue v) { m_value = v; }
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- QString m_stringValue;
- EnumValue m_value;
-};
-
-class _TemplateParameterModelItem: public _CodeModelItem
-{
-public:
- DECLARE_MODEL_NODE(TemplateParameter)
-
- explicit _TemplateParameterModelItem(CodeModel *model, int kind = __node_kind)
- : _CodeModelItem(model, kind), m_defaultValue(false) {}
- explicit _TemplateParameterModelItem(CodeModel *model, const QString &name, int kind = __node_kind)
- : _CodeModelItem(model, name, kind), m_defaultValue(false) {}
- ~_TemplateParameterModelItem();
-
- TypeInfo type() const;
- void setType(const TypeInfo &type);
-
- bool defaultValue() const;
- void setDefaultValue(bool defaultValue);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-private:
- TypeInfo m_type;
- bool m_defaultValue;
-};
-
-#endif // CODEMODEL_H
-
-// kate: space-indent on; indent-width 2; replace-tabs on;
diff --git a/sources/shiboken2/ApiExtractor/parser/codemodel_enums.h b/sources/shiboken2/ApiExtractor/parser/codemodel_enums.h
deleted file mode 100644
index aebd59879..000000000
--- a/sources/shiboken2/ApiExtractor/parser/codemodel_enums.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CODEMODEL_ENUMS_H
-#define CODEMODEL_ENUMS_H
-
-enum ReferenceType {
- NoReference,
- LValueReference,
- RValueReference
-};
-
-enum EnumKind {
- CEnum, // Standard C: enum Foo { value1, value2 }
- AnonymousEnum, // enum { value1, value2 }
- EnumClass // C++ 11 : enum class Foo { value1, value2 }
-};
-
-enum class Indirection
-{
- Pointer, // int *
- ConstPointer // int *const
-};
-
-enum class ExceptionSpecification
-{
- Unknown,
- NoExcept,
- Throws
-};
-
-enum class NamespaceType
-{
- Default,
- Anonymous,
- Inline
-};
-
-#endif // CODEMODEL_ENUMS_H
diff --git a/sources/shiboken2/ApiExtractor/parser/codemodel_fwd.h b/sources/shiboken2/ApiExtractor/parser/codemodel_fwd.h
deleted file mode 100644
index 87fea5cde..000000000
--- a/sources/shiboken2/ApiExtractor/parser/codemodel_fwd.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2002-2005 Roberto Raggi <roberto@kdevelop.org>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef CODEMODEL_FWD_H
-#define CODEMODEL_FWD_H
-
-#include <QtCore/QVector>
-#include <QtCore/QSharedPointer>
-
-// forward declarations
-class CodeModel;
-class _ArgumentModelItem;
-class _ClassModelItem;
-class _CodeModelItem;
-class _EnumModelItem;
-class _EnumeratorModelItem;
-class _FileModelItem;
-class _FunctionModelItem;
-class _NamespaceModelItem;
-class _ScopeModelItem;
-class _TemplateParameterModelItem;
-class _TypeDefModelItem;
-class _TemplateTypeAliasModelItem;
-class _VariableModelItem;
-class _MemberModelItem;
-class TypeInfo;
-
-using ArgumentModelItem = QSharedPointer<_ArgumentModelItem>;
-using ClassModelItem = QSharedPointer<_ClassModelItem>;
-using CodeModelItem = QSharedPointer<_CodeModelItem>;
-using EnumModelItem = QSharedPointer<_EnumModelItem>;
-using EnumeratorModelItem = QSharedPointer<_EnumeratorModelItem>;
-using FileModelItem = QSharedPointer<_FileModelItem>;
-using FunctionModelItem = QSharedPointer<_FunctionModelItem>;
-using NamespaceModelItem = QSharedPointer<_NamespaceModelItem>;
-using ScopeModelItem = QSharedPointer<_ScopeModelItem>;
-using TemplateParameterModelItem = QSharedPointer<_TemplateParameterModelItem>;
-using TypeDefModelItem = QSharedPointer<_TypeDefModelItem>;
-using TemplateTypeAliasModelItem = QSharedPointer<_TemplateTypeAliasModelItem>;
-using VariableModelItem = QSharedPointer<_VariableModelItem>;
-using MemberModelItem = QSharedPointer<_MemberModelItem>;
-
-using ArgumentList = QVector<ArgumentModelItem>;
-using ClassList = QVector<ClassModelItem>;
-using ItemList = QVector<CodeModelItem>;
-using EnumList = QVector<EnumModelItem>;
-using EnumeratorList = QVector<EnumeratorModelItem>;
-using FileList = QVector<FileModelItem>;
-using FunctionList = QVector<FunctionModelItem>;
-using NamespaceList = QVector<NamespaceModelItem>;
-using ScopeList = QVector<ScopeModelItem>;
-using TemplateParameterList = QVector<TemplateParameterModelItem>;
-using TypeDefList = QVector<TypeDefModelItem>;
-using TemplateTypeAliasList = QVector<TemplateTypeAliasModelItem>;
-using VariableList = QVector<VariableModelItem>;
-using MemberList = QVector<MemberModelItem>;
-
-#endif // CODEMODEL_FWD_H
diff --git a/sources/shiboken2/ApiExtractor/parser/enumvalue.cpp b/sources/shiboken2/ApiExtractor/parser/enumvalue.cpp
deleted file mode 100644
index 513bb3532..000000000
--- a/sources/shiboken2/ApiExtractor/parser/enumvalue.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "enumvalue.h"
-
-#include <QtCore/QDebug>
-#include <QtCore/QString>
-#include <QtCore/QTextStream>
-
-QString EnumValue::toString() const
-{
- return m_type == EnumValue::Signed
- ? QString::number(m_value) : QString::number(m_unsignedValue);
-}
-
-void EnumValue::setValue(qint64 v)
-{
- m_value = v;
- m_type = Signed;
-}
-
-void EnumValue::setUnsignedValue(quint64 v)
-{
- m_unsignedValue = v;
- m_type = Unsigned;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d,const EnumValue &v)
-{
- QDebugStateSaver saver(d);
- d.nospace();
- d.noquote();
- d << "EnumValue(";
- if (v.m_type == EnumValue::Signed)
- d << v.m_value;
- else
- d << v.m_unsignedValue << 'u';
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-QTextStream &operator<<(QTextStream &s, const EnumValue &v)
-{
- if (v.m_type == EnumValue::Signed)
- s << v.m_value;
- else
- s << v.m_unsignedValue;
- return s;
-}
diff --git a/sources/shiboken2/ApiExtractor/parser/enumvalue.h b/sources/shiboken2/ApiExtractor/parser/enumvalue.h
deleted file mode 100644
index ea30c39bb..000000000
--- a/sources/shiboken2/ApiExtractor/parser/enumvalue.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ENUMVALUE_H
-#define ENUMVALUE_H
-
-#include <QtCore/QtGlobal>
-
-QT_FORWARD_DECLARE_CLASS(QDebug)
-QT_FORWARD_DECLARE_CLASS(QString)
-QT_FORWARD_DECLARE_CLASS(QTextStream)
-
-class EnumValue
-{
-public:
- enum Type
- {
- Signed,
- Unsigned
- };
-
- QString toString() const;
-
- Type type() { return m_type; }
- qint64 value() const { return m_value; }
- quint64 unsignedValue() const { return m_unsignedValue; }
- bool isNullValue() const { return m_type == Signed ? m_value == 0 : m_unsignedValue == 0u; }
-
- void setValue(qint64 v);
- void setUnsignedValue(quint64 v);
-
-private:
-#ifndef QT_NO_DEBUG_STREAM
- friend QDebug operator<<(QDebug, const EnumValue &);
-#endif
- friend QTextStream &operator<<(QTextStream &, const EnumValue &);
-
- union
- {
- qint64 m_value = 0;
- quint64 m_unsignedValue;
- };
- Type m_type = Signed;
-};
-
-#endif // ENUMVALUE_H
diff --git a/sources/shiboken2/ApiExtractor/qtcompat.h b/sources/shiboken2/ApiExtractor/qtcompat.h
deleted file mode 100644
index 89a1db008..000000000
--- a/sources/shiboken2/ApiExtractor/qtcompat.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTCOMPAT_H
-#define QTCOMPAT_H
-
-#include <QtCore/QtGlobal>
-
-#if QT_VERSION >= 0x060000
-using QtCompatHashFunctionType = size_t;
-#else
-using QtCompatHashFunctionType = uint;
-#endif
-
-#endif // QTCOMPAT_H
diff --git a/sources/shiboken2/ApiExtractor/qtdocparser.cpp b/sources/shiboken2/ApiExtractor/qtdocparser.cpp
deleted file mode 100644
index 512473131..000000000
--- a/sources/shiboken2/ApiExtractor/qtdocparser.cpp
+++ /dev/null
@@ -1,358 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtdocparser.h"
-#include "abstractmetalang.h"
-#include "messages.h"
-#include "reporthandler.h"
-#include "typesystem.h"
-#include "xmlutils.h"
-
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QTextStream>
-#include <QtCore/QXmlStreamAttributes>
-#include <QtCore/QXmlStreamReader>
-#include <QUrl>
-
-Documentation QtDocParser::retrieveModuleDocumentation()
-{
- return retrieveModuleDocumentation(packageName());
-}
-
-static void formatFunctionArgTypeQuery(QTextStream &str, const AbstractMetaArgument *arg)
-{
- const AbstractMetaType *metaType = arg->type();
- if (metaType->isConstant())
- str << "const " ;
- switch (metaType->typeUsagePattern()) {
- case AbstractMetaType::FlagsPattern: {
- // Modify qualified name "QFlags<Qt::AlignmentFlag>" with name "Alignment"
- // to "Qt::Alignment" as seen by qdoc.
- const auto *flagsEntry = static_cast<const FlagsTypeEntry *>(metaType->typeEntry());
- QString name = flagsEntry->qualifiedCppName();
- if (name.endsWith(QLatin1Char('>')) && name.startsWith(QLatin1String("QFlags<"))) {
- const int lastColon = name.lastIndexOf(QLatin1Char(':'));
- if (lastColon != -1) {
- name.replace(lastColon + 1, name.size() - lastColon - 1, metaType->name());
- name.remove(0, 7);
- } else {
- name = metaType->name(); // QFlags<> of enum in global namespace
- }
- }
- str << name;
- }
- break;
- case AbstractMetaType::ContainerPattern: { // QVector<int>
- str << metaType->typeEntry()->qualifiedCppName() << '<';
- const auto instantiations = metaType->instantiations();
- for (int i = 0, size = instantiations.size(); i < size; ++i) {
- if (i)
- str << ", ";
- str << instantiations.at(i)->typeEntry()->qualifiedCppName();
- }
- str << '>';
- }
- break;
- default: // Fully qualify enums (Qt::AlignmentFlag), nested classes, etc.
- str << metaType->typeEntry()->qualifiedCppName();
- break;
- }
-
- if (metaType->referenceType() == LValueReference)
- str << " &";
- else if (metaType->referenceType() == RValueReference)
- str << " &&";
- else if (metaType->indirections())
- 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,
- const XQueryPtr &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)
- return;
-
- const AbstractMetaClass* context = metaClass->enclosingClass();
- while(context) {
- if (context->enclosingClass() == nullptr)
- break;
- context = context->enclosingClass();
- }
-
- QString sourceFileRoot = documentationDataDirectory() + QLatin1Char('/')
- + metaClass->qualifiedCppName().toLower();
- sourceFileRoot.replace(QLatin1String("::"), QLatin1String("-"));
-
- QFileInfo sourceFile(sourceFileRoot + QStringLiteral(".webxml"));
- if (!sourceFile.exists())
- sourceFile.setFile(sourceFileRoot + QStringLiteral(".xml"));
- if (!sourceFile.exists()) {
- qCWarning(lcShibokenDoc).noquote().nospace()
- << "Can't find qdoc file for class " << metaClass->name() << ", tried: "
- << QDir::toNativeSeparators(sourceFile.absoluteFilePath());
- return;
- }
-
- const QString sourceFileName = sourceFile.absoluteFilePath();
- QString errorMessage;
- XQueryPtr xquery = XQuery::create(sourceFileName, &errorMessage);
- if (xquery.isNull()) {
- qCWarning(lcShibokenDoc, "%s", qPrintable(errorMessage));
- return;
- }
-
- QString className = metaClass->name();
-
- // Class/Namespace documentation
- const QString classQuery = QLatin1String("/WebXML/document/")
- + (metaClass->isNamespace() ? QLatin1String("namespace") : QLatin1String("class"))
- + QLatin1String("[@name=\"") + className + QLatin1String("\"]");
- QString query = classQuery + QLatin1String("/description");
-
- DocModificationList signedModifs, classModifs;
- const DocModificationList &mods = metaClass->typeEntry()->docModifications();
- for (const DocModification &docModif : mods) {
- if (docModif.signature().isEmpty())
- classModifs.append(docModif);
- else
- signedModifs.append(docModif);
- }
-
- Documentation doc(getDocumentation(xquery, query, classModifs));
- if (doc.isEmpty())
- qCWarning(lcShibokenDoc, "%s", qPrintable(msgCannotFindDocumentation(sourceFileName, "class", className, query)));
- metaClass->setDocumentation(doc);
-
- //Functions Documentation
- const AbstractMetaFunctionList &funcs = DocParser::documentableFunctions(metaClass);
- for (AbstractMetaFunction *func : funcs) {
- const QString documentation =
- queryFunctionDocumentation(sourceFileName, metaClass, classQuery,
- func, signedModifs, xquery, &errorMessage);
- if (!errorMessage.isEmpty())
- qCWarning(lcShibokenDoc, "%s", qPrintable(errorMessage));
- func->setDocumentation(Documentation(documentation));
- }
-#if 0
- // Fields
- const AbstractMetaFieldList &fields = metaClass->fields();
- for (AbstractMetaField *field : fields) {
- if (field->isPrivate())
- return;
-
- QString query = "/doxygen/compounddef/sectiondef/memberdef/name[text()=\"" + field->name() + "\"]/..";
- Documentation doc = getDocumentation(DocModificationList(), xquery, query);
- field->setDocumentation(doc);
- }
-#endif
- // Enums
- const AbstractMetaEnumList &enums = metaClass->enums();
- for (AbstractMetaEnum *meta_enum : enums) {
- query.clear();
- QTextStream(&query) << classQuery << "/enum[@name=\""
- << meta_enum->name() << "\"]/description";
- doc.setValue(getDocumentation(xquery, query, DocModificationList()));
- if (doc.isEmpty()) {
- qCWarning(lcShibokenDoc, "%s",
- qPrintable(msgCannotFindDocumentation(sourceFileName, metaClass, meta_enum, query)));
- }
- meta_enum->setDocumentation(doc);
- }
-}
-
-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);
- const QString prefix = documentationDataDirectory() + QLatin1Char('/')
- + moduleName.toLower();
- QString sourceFile = prefix + QLatin1String(".xml");
-
- if (!QFile::exists(sourceFile))
- sourceFile = prefix + QLatin1String("-module.webxml");
- if (!QFile::exists(sourceFile)) {
- qCWarning(lcShibokenDoc).noquote().nospace()
- << "Can't find qdoc file for module " << name << ", tried: "
- << QDir::toNativeSeparators(sourceFile);
- return Documentation();
- }
-
- QString errorMessage;
- XQueryPtr xquery = XQuery::create(sourceFile, &errorMessage);
- if (xquery.isNull()) {
- qCWarning(lcShibokenDoc, "%s", qPrintable(errorMessage));
- return {};
- }
-
- // Module documentation
- QString query = QLatin1String("/WebXML/document/module[@name=\"")
- + moduleName + QLatin1String("\"]/description");
- Documentation doc = getDocumentation(xquery, query, DocModificationList());
- if (doc.isEmpty()) {
- qCWarning(lcShibokenDoc, "%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
deleted file mode 100644
index b01139de6..000000000
--- a/sources/shiboken2/ApiExtractor/qtdocparser.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTDOCPARSER_H
-#define QTDOCPARSER_H
-
-#include "docparser.h"
-
-class QtDocParser : public DocParser
-{
-public:
- QtDocParser() = default;
- 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,
- const XQueryPtr &xquery,
- QString *errorMessage);
-};
-
-#endif // QTDOCPARSER_H
-
diff --git a/sources/shiboken2/ApiExtractor/reporthandler.cpp b/sources/shiboken2/ApiExtractor/reporthandler.cpp
deleted file mode 100644
index a489f7548..000000000
--- a/sources/shiboken2/ApiExtractor/reporthandler.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "reporthandler.h"
-#include "typesystem.h"
-#include "typedatabase.h"
-#include <QtCore/QElapsedTimer>
-#include <QtCore/QSet>
-#include <cstring>
-#include <cstdarg>
-#include <cstdio>
-
-#if defined(_WINDOWS) || defined(NOCOLOR)
- #define COLOR_END ""
- #define COLOR_WHITE ""
- #define COLOR_YELLOW ""
- #define COLOR_GREEN ""
-#else
- #define COLOR_END "\033[0m"
- #define COLOR_WHITE "\033[1;37m"
- #define COLOR_YELLOW "\033[1;33m"
- #define COLOR_GREEN "\033[0;32m"
-#endif
-
-static bool m_silent = false;
-static int m_warningCount = 0;
-static int m_suppressedCount = 0;
-static ReportHandler::DebugLevel m_debugLevel = ReportHandler::NoDebug;
-static QSet<QString> m_reportedWarnings;
-static QString m_prefix;
-static bool m_withinProgress = false;
-static int m_step_warning = 0;
-static QElapsedTimer m_timer;
-
-Q_LOGGING_CATEGORY(lcShiboken, "qt.shiboken")
-Q_LOGGING_CATEGORY(lcShibokenDoc, "qt.shiboken.doc")
-
-void ReportHandler::install()
-{
- qInstallMessageHandler(ReportHandler::messageOutput);
- startTimer();
-}
-
-void ReportHandler::startTimer()
-{
- m_timer.start();
-}
-
-ReportHandler::DebugLevel ReportHandler::debugLevel()
-{
- return m_debugLevel;
-}
-
-void ReportHandler::setDebugLevel(ReportHandler::DebugLevel level)
-{
- m_debugLevel = level;
-}
-
-bool ReportHandler::setDebugLevelFromArg(const QString &level)
-{
- bool result = true;
- if (level == QLatin1String("sparse"))
- ReportHandler::setDebugLevel(ReportHandler::SparseDebug);
- else if (level == QLatin1String("medium"))
- ReportHandler::setDebugLevel(ReportHandler::MediumDebug);
- else if (level == QLatin1String("full"))
- ReportHandler::setDebugLevel(ReportHandler::FullDebug);
- else
- result = false;
- return result;
-}
-
-int ReportHandler::suppressedCount()
-{
- return m_suppressedCount;
-}
-
-int ReportHandler::warningCount()
-{
- return m_warningCount;
-}
-
-bool ReportHandler::isSilent()
-{
- return m_silent;
-}
-
-void ReportHandler::setSilent(bool silent)
-{
- m_silent = silent;
-}
-
-void ReportHandler::setPrefix(const QString &p)
-{
- m_prefix = p;
-}
-
-void ReportHandler::messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &text)
-{
- if (type == QtWarningMsg) {
- if (m_silent || m_reportedWarnings.contains(text))
- return;
- const TypeDatabase *db = TypeDatabase::instance();
- if (db && db->isSuppressedWarning(text)) {
- ++m_suppressedCount;
- return;
- }
- ++m_warningCount;
- ++m_step_warning;
- m_reportedWarnings.insert(text);
- }
- QString message = m_prefix;
- if (!message.isEmpty())
- message.append(QLatin1Char(' '));
- message.append(text);
- fprintf(stderr, "%s\n", qPrintable(qFormatLogMessage(type, context, message)));
-}
-
-static QByteArray timeStamp()
-{
- const qint64 elapsed = m_timer.elapsed();
- return elapsed > 5000
- ? QByteArray::number(elapsed / 1000) + 's'
- : QByteArray::number(elapsed) + "ms";
-}
-
-void ReportHandler::startProgress(const QByteArray& str)
-{
- if (m_silent)
- return;
-
- if (m_withinProgress)
- endProgress();
-
- m_withinProgress = true;
- const auto ts = '[' + timeStamp() + ']';
- std::printf("%s %8s %-60s", qPrintable(m_prefix), ts.constData(), str.constData());
- std::fflush(stdout);
-}
-
-void ReportHandler::endProgress()
-{
- if (m_silent)
- return;
-
- m_withinProgress = false;
- const char *endMessage = m_step_warning == 0
- ? "[" COLOR_GREEN "OK" COLOR_END "]\n"
- : "[" COLOR_YELLOW "WARNING" COLOR_END "]\n";
- std::fputs(endMessage, stdout);
- std::fflush(stdout);
- m_step_warning = 0;
-}
-
-QByteArray ReportHandler::doneMessage()
-{
- QByteArray result = "Done, " + m_prefix.toUtf8() + ' ' + timeStamp();
- if (m_warningCount)
- result += ", " + QByteArray::number(m_warningCount) + " warnings";
- if (m_suppressedCount)
- result += " (" + QByteArray::number(m_suppressedCount) + " known issues)";
- return result;
-}
diff --git a/sources/shiboken2/ApiExtractor/reporthandler.h b/sources/shiboken2/ApiExtractor/reporthandler.h
deleted file mode 100644
index 21f0e8933..000000000
--- a/sources/shiboken2/ApiExtractor/reporthandler.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef REPORTHANDLER_H
-#define REPORTHANDLER_H
-
-#include <QLoggingCategory>
-#include <QString>
-
-Q_DECLARE_LOGGING_CATEGORY(lcShiboken)
-Q_DECLARE_LOGGING_CATEGORY(lcShibokenDoc)
-
-class ReportHandler
-{
-public:
- enum DebugLevel { NoDebug, SparseDebug, MediumDebug, FullDebug };
-
- static void install();
- static void startTimer();
-
- static DebugLevel debugLevel();
- static void setDebugLevel(DebugLevel level);
- static bool setDebugLevelFromArg(const QString &);
-
- static int warningCount();
-
- static int suppressedCount();
-
- static void startProgress(const QByteArray &str);
- static void endProgress();
-
- static bool isDebug(DebugLevel level)
- { return debugLevel() >= level; }
-
- static bool isSilent();
- static void setSilent(bool silent);
-
- static void setPrefix(const QString &p);
-
- static QByteArray doneMessage();
-
-private:
- static void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg);
-};
-
-#endif // REPORTHANDLER_H
diff --git a/sources/shiboken2/ApiExtractor/symbols.filter b/sources/shiboken2/ApiExtractor/symbols.filter
deleted file mode 100644
index af6c744dd..000000000
--- a/sources/shiboken2/ApiExtractor/symbols.filter
+++ /dev/null
@@ -1,7 +0,0 @@
-{
-local:
-_ZSt*;
-_ZNSt*;
-_ZNSs*;
-_ZNKSt*;
-};
diff --git a/sources/shiboken2/ApiExtractor/tests/CMakeLists.txt b/sources/shiboken2/ApiExtractor/tests/CMakeLists.txt
deleted file mode 100644
index 97ae0f850..000000000
--- a/sources/shiboken2/ApiExtractor/tests/CMakeLists.txt
+++ /dev/null
@@ -1,63 +0,0 @@
-set(CMAKE_AUTORCC ON)
-
-macro(declare_test testname)
- # gone: qt4_automoc("${testname}.cpp")
- set(SOURCES "${testname}.cpp")
- if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${testname}.h")
- list(APPEND SOURCES "${testname}.h")
- endif ()
- if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${testname}.qrc")
- list(APPEND SOURCES "${testname}.qrc")
- endif ()
-
- add_executable(${testname} ${SOURCES})
- target_include_directories(${testname} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${apiextractor_SOURCE_DIR}
- )
- target_link_libraries(${testname} PRIVATE apiextractor Qt${QT_MAJOR_VERSION}::Test)
- add_test(${testname} ${testname})
- if (INSTALL_TESTS)
- install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${testname}
- DESTINATION share/apiextractor${apiextractor_SUFFIX}/tests)
- endif()
-endmacro(declare_test testname)
-
-declare_test(testabstractmetaclass)
-declare_test(testabstractmetatype)
-declare_test(testaddfunction)
-declare_test(testarrayargument)
-declare_test(testcodeinjection)
-declare_test(testcontainer)
-declare_test(testconversionoperator)
-declare_test(testconversionruletag)
-declare_test(testctorinformation)
-declare_test(testdroptypeentries)
-declare_test(testdtorinformation)
-declare_test(testenum)
-declare_test(testextrainclude)
-declare_test(testfunctiontag)
-declare_test(testimplicitconversions)
-declare_test(testinserttemplate)
-declare_test(testmodifyfunction)
-declare_test(testmultipleinheritance)
-declare_test(testnamespace)
-declare_test(testnestedtypes)
-declare_test(testnumericaltypedef)
-declare_test(testprimitivetypetag)
-declare_test(testrefcounttag)
-declare_test(testreferencetopointer)
-declare_test(testremovefield)
-declare_test(testremoveimplconv)
-declare_test(testremoveoperatormethod)
-declare_test(testresolvetype)
-declare_test(testreverseoperators)
-declare_test(testtemplates)
-declare_test(testtoposort)
-declare_test(testvaluetypedefaultctortag)
-declare_test(testvoidarg)
-declare_test(testtyperevision)
-if (NOT DISABLE_DOCSTRINGS)
- declare_test(testmodifydocumentation)
-endif()
-
diff --git a/sources/shiboken2/ApiExtractor/tests/a.xml b/sources/shiboken2/ApiExtractor/tests/a.xml
deleted file mode 100644
index 3c09d3800..000000000
--- a/sources/shiboken2/ApiExtractor/tests/a.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" ?>
-<!-- Sample for testModifyDocumentation -->
-<WebXML>
- <document>
- <class name="A">
- <description>oi
- <brief>Brief description</brief>
- <para>Paragraph number 1</para>
- <para>Paragraph number 2</para>
- <para>Paragraph number 3</para>
- </description>
- </class>
- </document>
-</WebXML>
diff --git a/sources/shiboken2/ApiExtractor/tests/injectedcode.txt b/sources/shiboken2/ApiExtractor/tests/injectedcode.txt
deleted file mode 100644
index 872898810..000000000
--- a/sources/shiboken2/ApiExtractor/tests/injectedcode.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-// Bla
-// @snippet label
-code line
-// @snippet label
-// Bla
diff --git a/sources/shiboken2/ApiExtractor/tests/testabstractmetaclass.cpp b/sources/shiboken2/ApiExtractor/tests/testabstractmetaclass.cpp
deleted file mode 100644
index f2e15fdb0..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testabstractmetaclass.cpp
+++ /dev/null
@@ -1,591 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testabstractmetaclass.h"
-#include "abstractmetabuilder.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestAbstractMetaClass::testClassName()
-{
- const char* cppCode ="class ClassName {};";
- const char* xmlCode = "<typesystem package=\"Foo\"><value-type name=\"ClassName\"/></typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
- QCOMPARE(classes[0]->name(), QLatin1String("ClassName"));
-}
-
-void TestAbstractMetaClass::testClassNameUnderNamespace()
-{
- const char* cppCode ="namespace Namespace { class ClassName {}; }\n";
- const char* xmlCode = R"XML(
- <typesystem package="Foo">
- <namespace-type name="Namespace">
- <value-type name="ClassName"/>
- </namespace-type>
- </typesystem>)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2); // 1 namespace + 1 class
- if (classes.first()->name() != QLatin1String("ClassName"))
- qSwap(classes[0], classes[1]);
-
- QCOMPARE(classes[0]->name(), QLatin1String("ClassName"));
- QCOMPARE(classes[0]->qualifiedCppName(), QLatin1String("Namespace::ClassName"));
- QCOMPARE(classes[1]->name(), QLatin1String("Namespace"));
- QVERIFY(classes[1]->isNamespace());
-
- // Check ctors info
- QVERIFY(classes[0]->hasConstructors());
- QCOMPARE(classes[0]->functions().size(), 2); // default ctor + copy ctor
-
- AbstractMetaFunctionList ctors = classes[0]->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 2);
- if (ctors.first()->minimalSignature() != QLatin1String("ClassName()"))
- qSwap(ctors[0], ctors[1]);
-
- QCOMPARE(ctors[0]->arguments().size(), 0);
- QCOMPARE(ctors[0]->minimalSignature(), QLatin1String("ClassName()"));
- QCOMPARE(ctors[1]->arguments().size(), 1);
- QCOMPARE(ctors[1]->minimalSignature(), QLatin1String("ClassName(Namespace::ClassName)"));
-
- QVERIFY(!classes[0]->hasPrivateDestructor());
- QVERIFY(classes[0]->hasCloneOperator()); // implicit default copy ctor
- QVERIFY(!classes[0]->hasHashFunction());
-
- // This method is buggy and nobody wants to fix it or needs it fixed :-/
- // QVERIFY(classes[0]->hasNonPrivateConstructor());
-}
-
-static AbstractMetaFunctionList virtualFunctions(const AbstractMetaClass *c)
-{
- AbstractMetaFunctionList result;
- const AbstractMetaFunctionList &functions = c->functions();
- for (AbstractMetaFunction *f : functions) {
- if (f->isVirtual())
- result.append(f);
- }
- return result;
-}
-
-void TestAbstractMetaClass::testVirtualMethods()
-{
- const char cppCode[] =R"CPP(
-class A {
-public:
- virtual int pureVirtual() const = 0;
-};
-class B : public A {};
-class C : public B {
-public:
- int pureVirtual() const override { return 0; }
-};
-class F final : public C {
-public:
- int pureVirtual() const final { return 1; }
-};
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package="Foo">
- <primitive-type name='int'/>
- <object-type name='A'/>
- <object-type name='B'/>
- <object-type name='C'/>
- <object-type name='F'/>
-</typesystem>
-)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 4);
- AbstractMetaClass* a = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- AbstractMetaClass* b = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- AbstractMetaClass* c = AbstractMetaClass::findClass(classes, QLatin1String("C"));
- const AbstractMetaClass *f = AbstractMetaClass::findClass(classes, QLatin1String("F"));
- QVERIFY(f);
-
- AbstractMetaClass* no_class = nullptr;
-
- QCOMPARE(a->baseClass(), no_class);
- QCOMPARE(b->baseClass(), a);
- QCOMPARE(c->baseClass(), b);
- QCOMPARE(f->baseClass(), c);
-
- QCOMPARE(a->functions().size(), 2); // default ctor + the pure virtual method
- QCOMPARE(b->functions().size(), 2);
- QCOMPARE(c->functions().size(), 2);
- QCOMPARE(f->functions().size(), 2);
- QVERIFY(f->attributes() & AbstractMetaAttributes::FinalCppClass);
-
- // implementing class, ownclass, declaringclass
- AbstractMetaFunction* ctorA = a->queryFunctions(AbstractMetaClass::Constructors).first();
- AbstractMetaFunction* ctorB = b->queryFunctions(AbstractMetaClass::Constructors).first();
- AbstractMetaFunction* ctorC = c->queryFunctions(AbstractMetaClass::Constructors).first();
- QVERIFY(ctorA->isConstructor());
- QVERIFY(!ctorA->isVirtual());
- QVERIFY(ctorB->isConstructor());
- QVERIFY(!ctorB->isVirtual());
- QVERIFY(ctorC->isConstructor());
- QVERIFY(!ctorC->isVirtual());
- QCOMPARE(ctorA->implementingClass(), a);
- QCOMPARE(ctorA->ownerClass(), a);
- QCOMPARE(ctorA->declaringClass(), a);
-
- const AbstractMetaFunctionList virtualFunctionsA = virtualFunctions(a);
- const AbstractMetaFunctionList virtualFunctionsB = virtualFunctions(b);
- const AbstractMetaFunctionList virtualFunctionsC = virtualFunctions(c);
- const AbstractMetaFunctionList virtualFunctionsF = virtualFunctions(f);
- QCOMPARE(virtualFunctionsA.size(), 1); // Add a pureVirtualMethods method !?
- QCOMPARE(virtualFunctionsB.size(), 1);
- QCOMPARE(virtualFunctionsC.size(), 1);
- QCOMPARE(virtualFunctionsF.size(), 1);
-
- const AbstractMetaFunction* funcA = virtualFunctionsA.constFirst();
- const AbstractMetaFunction* funcB = virtualFunctionsB.constFirst();
- const AbstractMetaFunction* funcC = virtualFunctionsC.constFirst();
- const AbstractMetaFunction* funcF = virtualFunctionsF.constFirst();
-
- QCOMPARE(funcA->ownerClass(), a);
- QVERIFY(funcC->attributes() & AbstractMetaAttributes::VirtualCppMethod);
- QCOMPARE(funcB->ownerClass(), b);
- QCOMPARE(funcC->ownerClass(), c);
- QVERIFY(funcC->attributes() & AbstractMetaAttributes::OverriddenCppMethod);
- QVERIFY(funcF->attributes() & AbstractMetaAttributes::FinalCppMethod);
-
- QCOMPARE(funcA->declaringClass(), a);
- QCOMPARE(funcB->declaringClass(), a);
- QCOMPARE(funcC->declaringClass(), a);
-
- // The next two tests could return null, because it makes more sense.
- // But we have too many code written relying on this behaviour where
- // implementingClass is equals to declaringClass on pure virtual functions
- QCOMPARE(funcA->implementingClass(), a);
- QCOMPARE(funcB->implementingClass(), a);
- QCOMPARE(funcC->implementingClass(), c);
-}
-
-void TestAbstractMetaClass::testVirtualBase()
-{
- const char cppCode[] =R"CPP(
-class Base {
-public:
- virtual ~Base() = default;
-};
-class Derived : public Base {};
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package="Foo">
- <object-type name='Base'/>
- <object-type name='Derived'/>
-</typesystem>
-)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- auto base = AbstractMetaClass::findClass(classes, QLatin1String("Base"));
- QVERIFY(base);
- QVERIFY(base->isPolymorphic());
- auto derived = AbstractMetaClass::findClass(classes, QLatin1String("Derived"));
- QVERIFY(derived);
- QVERIFY(derived->isPolymorphic());
-}
-
-void TestAbstractMetaClass::testDefaultValues()
-{
- const char* cppCode ="\
- struct A {\n\
- class B {};\n\
- void method(B b = B());\n\
- };\n";
- const char* xmlCode = R"XML(
- <typesystem package="Foo">
- <value-type name='A'>
- <value-type name='B'/>
- </value-type>
- </typesystem>)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QCOMPARE(classA->queryFunctionsByName(QLatin1String("method")).count(), 1);
- AbstractMetaFunction* method = classA->queryFunctionsByName(QLatin1String("method")).first();
- AbstractMetaArgument* arg = method->arguments().first();
- QCOMPARE(arg->defaultValueExpression(), arg->originalDefaultValueExpression());
-}
-
-void TestAbstractMetaClass::testModifiedDefaultValues()
-{
- const char* cppCode ="\
- struct A {\n\
- class B {};\n\
- void method(B b = B());\n\
- };\n";
- const char* xmlCode = R"XML(
- <typesystem package="Foo">
- <value-type name='A'>
- <modify-function signature='method(A::B)'>
- <modify-argument index='1'>
- <replace-default-expression with='Hello'/>
- </modify-argument>
- </modify-function>
- <value-type name='B'/>
- </value-type>
- </typesystem>)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QCOMPARE(classA->queryFunctionsByName(QLatin1String("method")).count(), 1);
- AbstractMetaFunction* method = classA->queryFunctionsByName(QLatin1String("method")).first();
- AbstractMetaArgument* arg = method->arguments().first();
- QCOMPARE(arg->defaultValueExpression(), QLatin1String("Hello"));
- QCOMPARE(arg->originalDefaultValueExpression(), QLatin1String("A::B()"));
-}
-
-void TestAbstractMetaClass::testInnerClassOfAPolymorphicOne()
-{
- const char* cppCode ="\
- struct A {\n\
- class B {};\n\
- virtual void method();\n\
- };\n";
- const char* xmlCode = R"XML(
- <typesystem package="Foo">
- <object-type name='A'>
- <value-type name='B'/>
- </object-type>
- </typesystem>)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QVERIFY(classA->isPolymorphic());
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("A::B"));
- QVERIFY(classB);
- QVERIFY(!classB->isPolymorphic());
-}
-
-void TestAbstractMetaClass::testForwardDeclaredInnerClass()
-{
- const char cppCode[] ="\
- class A {\n\
- class B;\n\
- };\n\
- class A::B {\n\
- public:\n\
- void foo();\n\
- };\n";
- const char xmlCode[] = R"XML(
- <typesystem package="Foo">
- <value-type name='A'>
- <value-type name='B'/>
- </value-type>
- </typesystem>)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("A::B"));
- QVERIFY(classB);
- const AbstractMetaFunction *fooF = classB->findFunction(QLatin1String("foo"));
- QVERIFY(fooF);
-}
-
-void TestAbstractMetaClass::testSpecialFunctions()
-{
- const char cppCode[] ="\
- struct A {\n\
- A();\n\
- A(const A&);\n\
- A &operator=(const A&);\n\
- };\n\
- struct B {\n\
- B();\n\
- B(const B &);\n\
- B &operator=(B);\n\
- };\n";
- const char xmlCode[] = "\
- <typesystem package=\"Foo\">\n\
- <object-type name='A'/>\n\
- <object-type name='B'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
-
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- AbstractMetaFunctionList ctors = classA->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 2);
- QCOMPARE(ctors.first()->functionType(), AbstractMetaFunction::ConstructorFunction);
- QCOMPARE(ctors.at(1)->functionType(), AbstractMetaFunction::CopyConstructorFunction);
- AbstractMetaFunctionList assigmentOps = classA->queryFunctionsByName(QLatin1String("operator="));
- QCOMPARE(assigmentOps.size(), 1);
- QCOMPARE(assigmentOps.first()->functionType(), AbstractMetaFunction::AssignmentOperatorFunction);
-
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
- ctors = classB->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 2);
- QCOMPARE(ctors.first()->functionType(), AbstractMetaFunction::ConstructorFunction);
- QCOMPARE(ctors.at(1)->functionType(), AbstractMetaFunction::CopyConstructorFunction);
- assigmentOps = classA->queryFunctionsByName(QLatin1String("operator="));
- QCOMPARE(assigmentOps.size(), 1);
- QCOMPARE(assigmentOps.first()->functionType(), AbstractMetaFunction::AssignmentOperatorFunction);
-}
-
-void TestAbstractMetaClass::testClassDefaultConstructors()
-{
- const char* cppCode ="\
- struct A {};\n\
- \n\
- struct B {\n\
- B();\n\
- private: \n\
- B(const B&);\n\
- };\n\
- \n\
- struct C {\n\
- C(const C&);\n\
- };\n\
- \n\
- struct D {\n\
- private: \n\
- D(const D&);\n\
- };\n\
- \n\
- struct E {\n\
- private: \n\
- ~E();\n\
- };\n\
- \n\
- struct F {\n\
- F(int, int);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <value-type name='A'/>\n\
- <object-type name='B'/>\n\
- <value-type name='C'/>\n\
- <object-type name='D'/>\n\
- <object-type name='E'/>\n\
- <value-type name='F'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 6);
-
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->functions().size(), 2);
-
- AbstractMetaFunctionList ctors = classA->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 2);
- if (ctors.first()->minimalSignature() != QLatin1String("A()"))
- qSwap(ctors[0], ctors[1]);
-
- QCOMPARE(ctors[0]->arguments().size(), 0);
- QCOMPARE(ctors[0]->minimalSignature(), QLatin1String("A()"));
- QCOMPARE(ctors[1]->arguments().size(), 1);
- QCOMPARE(ctors[1]->minimalSignature(), QLatin1String("A(A)"));
-
- AbstractMetaClass* classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
- QCOMPARE(classB->functions().size(), 2);
- QCOMPARE(classB->functions().first()->minimalSignature(), QLatin1String("B()"));
-
- AbstractMetaClass* classC = AbstractMetaClass::findClass(classes, QLatin1String("C"));
- QVERIFY(classC);
- QCOMPARE(classC->functions().size(), 1);
- QCOMPARE(classC->functions().first()->minimalSignature(), QLatin1String("C(C)"));
-
- AbstractMetaClass* classD = AbstractMetaClass::findClass(classes, QLatin1String("D"));
- QVERIFY(classD);
- QCOMPARE(classD->functions().size(), 1);
- QCOMPARE(classD->functions().first()->minimalSignature(), QLatin1String("D(D)"));
- QVERIFY(classD->functions().first()->isPrivate());
-
- AbstractMetaClass* classE = AbstractMetaClass::findClass(classes, QLatin1String("E"));
- QVERIFY(classE);
- QVERIFY(classE->hasPrivateDestructor());
- QCOMPARE(classE->functions().size(), 0);
-
- AbstractMetaClass* classF = AbstractMetaClass::findClass(classes, QLatin1String("F"));
- QVERIFY(classF);
-
- ctors = classF->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 2);
- if (ctors.first()->minimalSignature() != QLatin1String("F(int,int)"))
- qSwap(ctors[0], ctors[1]);
-
- QCOMPARE(ctors[0]->arguments().size(), 2);
- QCOMPARE(ctors[0]->minimalSignature(), QLatin1String("F(int,int)"));
- QCOMPARE(ctors[1]->arguments().size(), 1);
- QCOMPARE(ctors[1]->minimalSignature(), QLatin1String("F(F)"));
-}
-
-void TestAbstractMetaClass::testClassInheritedDefaultConstructors()
-{
- const char* cppCode ="\
- struct A {\n\
- A();\n\
- private: \n\
- A(const A&);\n\
- };\n\
- struct B : public A {};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <object-type name='A'/>\n\
- <object-type name='B'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
-
- AbstractMetaFunctionList ctors = classA->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 2);
- if (ctors.first()->minimalSignature() != QLatin1String("A()"))
- qSwap(ctors[0], ctors[1]);
-
- QCOMPARE(ctors[0]->arguments().size(), 0);
- QCOMPARE(ctors[0]->minimalSignature(), QLatin1String("A()"));
- QCOMPARE(ctors[1]->arguments().size(), 1);
- QCOMPARE(ctors[1]->minimalSignature(), QLatin1String("A(A)"));
- QVERIFY(ctors[1]->isPrivate());
-
- AbstractMetaClass* classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
-
- ctors = classB->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 1);
- QCOMPARE(ctors.first()->arguments().size(), 0);
- QCOMPARE(ctors.first()->minimalSignature(), QLatin1String("B()"));
-}
-
-void TestAbstractMetaClass::testAbstractClassDefaultConstructors()
-{
- const char* cppCode ="\
- struct A {\n\
- virtual void method() = 0;\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <object-type name='A'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
-
- AbstractMetaFunctionList ctors = classA->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 1);
- QCOMPARE(ctors.first()->arguments().size(), 0);
- QCOMPARE(ctors.first()->minimalSignature(), QLatin1String("A()"));
-}
-
-void TestAbstractMetaClass::testObjectTypesMustNotHaveCopyConstructors()
-{
- const char* cppCode ="struct A {};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <object-type name='A'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
-
- AbstractMetaFunctionList ctors = classA->queryFunctions(AbstractMetaClass::Constructors);
- QCOMPARE(ctors.size(), 1);
- QCOMPARE(ctors.first()->arguments().size(), 0);
- QCOMPARE(ctors.first()->minimalSignature(), QLatin1String("A()"));
-}
-
-void TestAbstractMetaClass::testIsPolymorphic()
-{
- const char* cppCode = "\
- class A\n\
- {\n\
- public:\n\
- A();\n\
- inline bool abc() const {}\n\
- };\n\
- \n\
- class B : public A\n\
- {\n\
- public:\n\
- B();\n\
- inline bool abc() const {}\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='bool'/>\n\
- <value-type name='A'/>\n\
- <value-type name='B'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- AbstractMetaClass* b = AbstractMetaClass::findClass(classes, QLatin1String("A"));
-
- QVERIFY(!b->isPolymorphic());
- AbstractMetaClass* a = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(!a->isPolymorphic());
-}
-
-QTEST_APPLESS_MAIN(TestAbstractMetaClass)
diff --git a/sources/shiboken2/ApiExtractor/tests/testabstractmetaclass.h b/sources/shiboken2/ApiExtractor/tests/testabstractmetaclass.h
deleted file mode 100644
index e19973625..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testabstractmetaclass.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTABSTRACTMETACLASS_H
-#define TESTABSTRACTMETACLASS_H
-
-#include <QObject>
-
-class AbstractMetaBuilder;
-
-class TestAbstractMetaClass : public QObject
-{
- Q_OBJECT
-private slots:
- void testClassName();
- void testClassNameUnderNamespace();
- void testVirtualMethods();
- void testVirtualBase();
- void testDefaultValues();
- void testModifiedDefaultValues();
- void testInnerClassOfAPolymorphicOne();
- void testForwardDeclaredInnerClass();
- void testSpecialFunctions();
- void testClassDefaultConstructors();
- void testClassInheritedDefaultConstructors();
- void testAbstractClassDefaultConstructors();
- void testObjectTypesMustNotHaveCopyConstructors();
- void testIsPolymorphic();
-};
-
-#endif // TESTABSTRACTMETACLASS_H
diff --git a/sources/shiboken2/ApiExtractor/tests/testabstractmetatype.cpp b/sources/shiboken2/ApiExtractor/tests/testabstractmetatype.cpp
deleted file mode 100644
index 63434b3a5..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testabstractmetatype.cpp
+++ /dev/null
@@ -1,247 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testabstractmetatype.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-#include <parser/codemodel.h>
-#include <typeparser.h>
-
-void TestAbstractMetaType::parsing_data()
-{
- QTest::addColumn<QString>("input");
- QTest::addColumn<QString>("output");
- QTest::newRow("primitive")
- << QString::fromLatin1("int") << QString::fromLatin1("int");
- QTest::newRow("ref")
- << QString::fromLatin1("int &") << QString::fromLatin1("int&");
- QTest::newRow("pointer")
- << QString::fromLatin1("int **") << QString::fromLatin1("int**");
- QTest::newRow("const ref")
- << QString::fromLatin1("const int &") << QString::fromLatin1("const int&");
- QTest::newRow("const pointer")
- << QString::fromLatin1("const int **") << QString::fromLatin1("const int**");
- QTest::newRow("const pointer const")
- << QString::fromLatin1("const int *const*") << QString::fromLatin1("const int*const*");
-}
-
-void TestAbstractMetaType::parsing()
-{
- QFETCH(QString, input);
- QFETCH(QString, output);
- QString errorMessage;
- const TypeInfo ti = TypeParser::parse(input, &errorMessage);
- QVERIFY2(errorMessage.isEmpty(), qPrintable(errorMessage));
- const QString actual = ti.toString();
- QCOMPARE(actual, output);
-}
-
-void TestAbstractMetaType::testConstCharPtrType()
-{
- const char* cppCode ="const char* justAtest();\n";
- const char* xmlCode = "<typesystem package=\"Foo\">\n\
- <primitive-type name='char'/>\n\
- <function signature='justAtest()' />\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- QCOMPARE(builder->globalFunctions().size(), 1);
- AbstractMetaFunction* func = builder->globalFunctions().first();
- AbstractMetaType* rtype = func->type();
- // Test properties of const char*
- QVERIFY(rtype);
- QCOMPARE(rtype->package(), QLatin1String("Foo"));
- QCOMPARE(rtype->name(), QLatin1String("char"));
- QVERIFY(rtype->isConstant());
- QVERIFY(!rtype->isArray());
- QVERIFY(!rtype->isContainer());
- QVERIFY(!rtype->isObject());
- QVERIFY(!rtype->isPrimitive()); // const char* differs from char, so it's not considered a primitive type by apiextractor
- QVERIFY(rtype->isNativePointer());
- QCOMPARE(rtype->referenceType(), NoReference);
- QVERIFY(!rtype->isValue());
- QVERIFY(!rtype->isValuePointer());
-}
-
-void TestAbstractMetaType::testApiVersionSupported()
-{
- const char* cppCode ="class foo {}; class foo2 {};\n\
- void justAtest(); void justAtest3();\n";
- const char* xmlCode = "<typesystem package='Foo'>\n\
- <value-type name='foo' since='0.1'/>\n\
- <value-type name='foo2' since='1.0'/>\n\
- <value-type name='foo3' since='1.1'/>\n\
- <function signature='justAtest()' since='0.1'/>\n\
- <function signature='justAtest2()' since='1.1'/>\n\
- <function signature='justAtest3()'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- false, QLatin1String("1.0")));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.size(), 2);
-
-
- AbstractMetaFunctionList functions = builder->globalFunctions();
- QCOMPARE(functions.size(), 2);
-}
-
-
-void TestAbstractMetaType::testApiVersionNotSupported()
-{
- const char* cppCode ="class object {};\n";
- const char* xmlCode = "<typesystem package='Foo'>\n\
- <value-type name='object' since='0.1'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- true, QLatin1String("0.1")));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.size(), 1);
-}
-
-void TestAbstractMetaType::testCharType()
-{
- const char* cppCode ="char justAtest(); class A {};\n";
- const char* xmlCode = "<typesystem package=\"Foo\">\n\
- <primitive-type name='char'/>\n\
- <value-type name='A'/>\n\
- <function signature='justAtest()'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.size(), 1);
- QCOMPARE(classes.first()->package(), QLatin1String("Foo"));
-
- AbstractMetaFunctionList functions = builder->globalFunctions();
- QCOMPARE(functions.size(), 1);
- AbstractMetaFunction* func = functions.first();
- AbstractMetaType* rtype = func->type();
- // Test properties of const char*
- QVERIFY(rtype);
- QCOMPARE(rtype->package(), QLatin1String("Foo"));
- QCOMPARE(rtype->name(), QLatin1String("char"));
- QVERIFY(!rtype->isConstant());
- QVERIFY(!rtype->isArray());
- QVERIFY(!rtype->isContainer());
- QVERIFY(!rtype->isObject());
- QVERIFY(rtype->isPrimitive());
- QVERIFY(!rtype->isNativePointer());
- QCOMPARE(rtype->referenceType(), NoReference);
- QVERIFY(!rtype->isValue());
- QVERIFY(!rtype->isValuePointer());
-}
-
-void TestAbstractMetaType::testTypedef()
-{
- const char* cppCode ="\
- struct A {\n\
- void someMethod();\n\
- };\n\
- typedef A B;\n\
- typedef B C;\n";
- const char* xmlCode = "<typesystem package=\"Foo\">\n\
- <value-type name='C' />\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.size(), 1);
- const AbstractMetaClass *c = AbstractMetaClass::findClass(classes, QLatin1String("C"));
- QVERIFY(c);
- QVERIFY(c->isTypeDef());
-}
-
-void TestAbstractMetaType::testTypedefWithTemplates()
-{
- const char* cppCode ="\
- template<typename T>\n\
- class A {};\n\
- \n\
- class B {};\n\
- typedef A<B> C;\n\
- \n\
- void func(C c);\n";
- const char* xmlCode = "<typesystem package=\"Foo\">\n\
- <container-type name='A' type='list'/>\n\
- <value-type name='B' />\n\
- <function signature='func(A&lt;B&gt;)'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.size(), 1);
- AbstractMetaFunctionList functions = builder->globalFunctions();
- QCOMPARE(functions.count(), 1);
- AbstractMetaFunction* function = functions.first();
- AbstractMetaArgumentList args = function->arguments();
- QCOMPARE(args.count(), 1);
- AbstractMetaArgument* arg = args.first();
- AbstractMetaType* metaType = arg->type();
- QCOMPARE(metaType->cppSignature(), QLatin1String("A<B >"));
-}
-
-
-void TestAbstractMetaType::testObjectTypeUsedAsValue()
-{
- const char* cppCode ="\
- class A {\n\
- void method(A);\n\
- };\n";
- const char* xmlCode = "<typesystem package='Foo'>\n\
- <object-type name='A'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.size(), 1);
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- AbstractMetaFunctionList overloads = classA->queryFunctionsByName(QLatin1String("method"));
- QCOMPARE(overloads.count(), 1);
- AbstractMetaFunction* method = overloads.first();
- QVERIFY(method);
- AbstractMetaArgumentList args = method->arguments();
- QCOMPARE(args.count(), 1);
- AbstractMetaArgument* arg = args.first();
- AbstractMetaType* metaType = arg->type();
- QCOMPARE(metaType->cppSignature(), QLatin1String("A"));
- QVERIFY(metaType->isValue());
- QVERIFY(metaType->typeEntry()->isObject());
-}
-
-QTEST_APPLESS_MAIN(TestAbstractMetaType)
diff --git a/sources/shiboken2/ApiExtractor/tests/testabstractmetatype.h b/sources/shiboken2/ApiExtractor/tests/testabstractmetatype.h
deleted file mode 100644
index b39a27a54..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testabstractmetatype.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTABSTRACTMETATYPE_H
-#define TESTABSTRACTMETATYPE_H
-
-#include <QObject>
-
-class TestAbstractMetaType : public QObject
-{
- Q_OBJECT
-private slots:
- void parsing_data();
- void parsing();
- void testConstCharPtrType();
- void testCharType();
- void testTypedef();
- void testTypedefWithTemplates();
- void testApiVersionSupported();
- void testApiVersionNotSupported();
- void testObjectTypeUsedAsValue();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testaddfunction.cpp b/sources/shiboken2/ApiExtractor/tests/testaddfunction.cpp
deleted file mode 100644
index c50084b8e..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testaddfunction.cpp
+++ /dev/null
@@ -1,467 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testaddfunction.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestAddFunction::testParsingFuncNameAndConstness()
-{
- // generic test...
- const char sig1[] = "func(type1, const type2, const type3* const)";
- AddedFunction f1(QLatin1String(sig1), QLatin1String("void"));
- QCOMPARE(f1.name(), QLatin1String("func"));
- QCOMPARE(f1.arguments().count(), 3);
- AddedFunction::TypeInfo retval = f1.returnType();
- QCOMPARE(retval.name, QLatin1String("void"));
- QCOMPARE(retval.indirections, 0);
- QCOMPARE(retval.isConstant, false);
- QCOMPARE(retval.isReference, false);
-
- // test with a ugly template as argument and other ugly stuff
- const char sig2[] = " _fu__nc_ ( type1, const type2, const Abc<int& , C<char*> * > * *@my_name@, const type3* const ) const ";
- AddedFunction f2(QLatin1String(sig2), QLatin1String("const Abc<int& , C<char*> * > * *"));
- QCOMPARE(f2.name(), QLatin1String("_fu__nc_"));
- const auto &args = f2.arguments();
- QCOMPARE(args.count(), 4);
- retval = f2.returnType();
- QCOMPARE(retval.name, QLatin1String("Abc<int& , C<char*> * >"));
- QCOMPARE(retval.indirections, 2);
- QCOMPARE(retval.isConstant, true);
- QCOMPARE(retval.isReference, false);
- retval = args.at(2).typeInfo;
- QVERIFY(args.at(0).name.isEmpty());
- QVERIFY(args.at(1).name.isEmpty());
- QCOMPARE(args.at(2).name, QLatin1String("my_name"));
- QVERIFY(args.at(3).name.isEmpty());
- QCOMPARE(retval.name, QLatin1String("Abc<int& , C<char*> * >"));
- QCOMPARE(retval.indirections, 2);
- QCOMPARE(retval.isConstant, true);
- QCOMPARE(retval.isReference, false);
-
- // function with no args.
- const char sig3[] = "func()";
- AddedFunction f3(QLatin1String(sig3), QLatin1String("void"));
- QCOMPARE(f3.name(), QLatin1String("func"));
- QCOMPARE(f3.arguments().count(), 0);
-}
-
-void TestAddFunction::testAddFunction()
-{
- const char cppCode[] = R"CPP(
-struct B {};
-struct A {
- void a(int);
-};)CPP";
- const char xmlCode[] = R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <primitive-type name='float'/>
- <value-type name='B'/>
- <value-type name='A'>
- <add-function signature='b(int, float = 4.6, const B&amp;)' return-type='int' access='protected'/>
- <add-function signature='operator()(int)' return-type='int' access='public'/>
- </value-type>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- TypeDatabase* typeDb = TypeDatabase::instance();
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->functions().count(), 5); // default ctor, default copy ctor, func a() and the added functions
-
- auto addedFunc = classA->findFunction(QLatin1String("b"));
- QVERIFY(addedFunc);
- QCOMPARE(addedFunc->visibility(), AbstractMetaFunction::Protected);
- QCOMPARE(addedFunc->functionType(), AbstractMetaFunction::NormalFunction);
- QVERIFY(addedFunc->isUserAdded());
- QCOMPARE(addedFunc->ownerClass(), classA);
- QCOMPARE(addedFunc->implementingClass(), classA);
- QCOMPARE(addedFunc->declaringClass(), classA);
- QVERIFY(!addedFunc->isVirtual());
- QVERIFY(!addedFunc->isSignal());
- QVERIFY(!addedFunc->isSlot());
- QVERIFY(!addedFunc->isStatic());
-
- AbstractMetaType* returnType = addedFunc->type();
- QCOMPARE(returnType->typeEntry(), typeDb->findPrimitiveType(QLatin1String("int")));
- AbstractMetaArgumentList args = addedFunc->arguments();
- QCOMPARE(args.count(), 3);
- QCOMPARE(args[0]->type()->typeEntry(), returnType->typeEntry());
- QCOMPARE(args[1]->defaultValueExpression(), QLatin1String("4.6"));
- QCOMPARE(args[2]->type()->typeEntry(), typeDb->findType(QLatin1String("B")));
-
- auto addedCallOperator = classA->findFunction(QLatin1String("operator()"));
- QVERIFY(addedCallOperator);
-}
-
-void TestAddFunction::testAddFunctionConstructor()
-{
- const char cppCode[] = "struct A { A() {} };\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <value-type name='A'>\n\
- <add-function signature='A(int)'/>\n\
- </value-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->functions().count(), 3); // default and added ctors
- AbstractMetaFunction* addedFunc = classA->functions().last();
- QCOMPARE(addedFunc->visibility(), AbstractMetaFunction::Public);
- QCOMPARE(addedFunc->functionType(), AbstractMetaFunction::ConstructorFunction);
- QCOMPARE(addedFunc->arguments().size(), 1);
- QVERIFY(addedFunc->isUserAdded());
- QVERIFY(!addedFunc->type());
-}
-
-void TestAddFunction::testAddFunctionTagDefaultValues()
-{
- const char cppCode[] = "struct A {};\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'>\n\
- <add-function signature='func()'/>\n\
- </value-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->functions().count(), 3); // default ctor, default copy ctor and the added function
- AbstractMetaFunction* addedFunc = classA->functions().last();
- QCOMPARE(addedFunc->visibility(), AbstractMetaFunction::Public);
- QCOMPARE(addedFunc->functionType(), AbstractMetaFunction::NormalFunction);
- QVERIFY(addedFunc->isUserAdded());
- QVERIFY(!addedFunc->type());
-}
-
-void TestAddFunction::testAddFunctionCodeSnippets()
-{
- const char cppCode[] = "struct A {};\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'>\n\
- <add-function signature='func()'>\n\
- <inject-code class='target' position='end'>Hi!, I am the code.</inject-code>\n\
- </add-function>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- AbstractMetaFunction* addedFunc = classA->functions().last();
- QVERIFY(addedFunc->hasInjectedCode());
-}
-
-void TestAddFunction::testAddFunctionWithoutParenteses()
-{
- const char sig1[] = "func";
- AddedFunction f1(QLatin1String(sig1), QLatin1String("void"));
-
- QCOMPARE(f1.name(), QLatin1String("func"));
- QCOMPARE(f1.arguments().count(), 0);
- QCOMPARE(f1.isConstant(), false);
-
- const char cppCode[] = "struct A {};\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'>\n\
- <add-function signature='func'>\n\
- <inject-code class='target' position='end'>Hi!, I am the code.</inject-code>\n\
- </add-function>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaFunction* addedFunc = classA->findFunction(QLatin1String("func"));
- QVERIFY(addedFunc);
- QVERIFY(addedFunc->hasInjectedCode());
- QCOMPARE(addedFunc->injectedCodeSnips(TypeSystem::CodeSnipPositionAny, TypeSystem::TargetLangCode).count(), 1);
-}
-
-void TestAddFunction::testAddFunctionWithDefaultArgs()
-{
- const char sig1[] = "func";
- AddedFunction f1(QLatin1String(sig1), QLatin1String("void"));
-
- QCOMPARE(f1.name(), QLatin1String("func"));
- QCOMPARE(f1.arguments().count(), 0);
- QCOMPARE(f1.isConstant(), false);
-
- const char cppCode[] = "struct A { };\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <value-type name='A'>\n\
- <add-function signature='func(int, int)'>\n\
- <modify-argument index='2'>\n\
- <replace-default-expression with='2'/>\n\
- </modify-argument>\n\
- </add-function>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaFunction* addedFunc = classA->findFunction(QLatin1String("func"));
- QVERIFY(addedFunc);
- AbstractMetaArgument *arg = addedFunc->arguments()[1];
- QCOMPARE(arg->defaultValueExpression(), QLatin1String("2"));
-}
-
-void TestAddFunction::testAddFunctionAtModuleLevel()
-{
- const char cppCode[] = "struct A { };\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <value-type name='A'/>\n\
- <add-function signature='func(int, int)'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- </add-function>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
-
- TypeDatabase* typeDb = TypeDatabase::instance();
-
- AddedFunctionList addedFuncs = typeDb->findGlobalUserFunctions(QLatin1String("func"));
-
- QCOMPARE(addedFuncs.size(), 1);
-
- const FunctionModificationList mods = addedFuncs.constFirst()->modifications;
-
- QCOMPARE(mods.size(), 1);
- QVERIFY(mods.first().isCodeInjection());
- CodeSnip snip = mods.first().snips.first();
- QCOMPARE(snip.code(), QLatin1String("custom_code();"));
-}
-
-void TestAddFunction::testAddFunctionWithVarargs()
-{
- const char sig1[] = "func(int,char,...)";
- AddedFunction f1( QLatin1String(sig1), QLatin1String("void"));
-
- QCOMPARE(f1.name(), QLatin1String("func"));
- QCOMPARE(f1.arguments().count(), 3);
- QVERIFY(!f1.isConstant());
-
- const char cppCode[] = "struct A {};\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <primitive-type name='char'/>\n\
- <value-type name='A'>\n\
- <add-function signature='func(int,char,...)'/>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaFunction* addedFunc = classA->findFunction(QLatin1String("func"));
- QVERIFY(addedFunc);
- const AbstractMetaArgument* arg = addedFunc->arguments().last();
- QVERIFY(arg->type()->isVarargs());
- QVERIFY(arg->type()->typeEntry()->isVarargs());
-}
-
-void TestAddFunction::testAddStaticFunction()
-{
- const char cppCode[] = "struct A { };\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <value-type name='A'>\n\
- <add-function signature='func(int, int)' static='yes'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- </add-function>\n\
- </value-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaFunction* addedFunc = classA->findFunction(QLatin1String("func"));
- QVERIFY(addedFunc);
- QVERIFY(addedFunc->isStatic());
-}
-
-void TestAddFunction::testAddGlobalFunction()
-{
- const char cppCode[] = "struct A { };struct B {};\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <value-type name='A'/>\n\
- <add-function signature='globalFunc(int, int)' static='yes'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- </add-function>\n\
- <add-function signature='globalFunc2(int, int)' static='yes'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- </add-function>\n\
- <value-type name='B'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaFunctionList globalFuncs = builder->globalFunctions();
- QCOMPARE(globalFuncs.count(), 2);
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(builder->classes(), QLatin1String("B"));
- QVERIFY(classB);
- QVERIFY(!classB->findFunction(QLatin1String("globalFunc")));
- QVERIFY(!classB->findFunction(QLatin1String("globalFunc2")));
- QVERIFY(!globalFuncs[0]->injectedCodeSnips().isEmpty());
- QVERIFY(!globalFuncs[1]->injectedCodeSnips().isEmpty());
-}
-
-void TestAddFunction::testAddFunctionWithApiVersion()
-{
- const char cppCode[] = "";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <add-function signature='globalFunc(int, int)' static='yes' since='1.3'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- </add-function>\n\
- <add-function signature='globalFunc2(int, int)' static='yes' since='0.1'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- </add-function>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- true, QLatin1String("0.1")));
- QVERIFY(!builder.isNull());
- AbstractMetaFunctionList globalFuncs = builder->globalFunctions();
- QCOMPARE(globalFuncs.count(), 1);
-}
-
-void TestAddFunction::testModifyAddedFunction()
-{
- const char cppCode[] = "class Foo { };\n";
- const char xmlCode[] = "\
- <typesystem package='Package'>\n\
- <primitive-type name='float'/>\n\
- <primitive-type name='int'/>\n\
- <value-type name='Foo'>\n\
- <add-function signature='method(float, int)'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- <modify-argument index='2'>\n\
- <replace-default-expression with='0'/>\n\
- <rename to='varName'/>\n\
- </modify-argument>\n\
- </add-function>\n\
- </value-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- AbstractMetaClass* foo = AbstractMetaClass::findClass(classes, QLatin1String("Foo"));
- const AbstractMetaFunction* method = foo->findFunction(QLatin1String("method"));
- QCOMPARE(method->arguments().size(), 2);
- AbstractMetaArgument* arg = method->arguments().at(1);
- QCOMPARE(arg->defaultValueExpression(), QLatin1String("0"));
- QCOMPARE(arg->name(), QLatin1String("varName"));
- QCOMPARE(method->argumentName(2), QLatin1String("varName"));
-}
-
-void TestAddFunction::testAddFunctionOnTypedef()
-{
- const char cppCode[] = "template<class T> class Foo { }; typedef Foo<int> FooInt;\n";
- const char xmlCode[] = "\
- <typesystem package='Package'>\n\
- <custom-type name='PySequence'/>\n\
- <primitive-type name='int'/>\n\
- <value-type name='FooInt'>\n\
- <add-function signature='FooInt(PySequence)'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- </add-function>\n\
- <add-function signature='method()'>\n\
- <inject-code class='target' position='beginning'>custom_code();</inject-code>\n\
- </add-function>\n\
- </value-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- AbstractMetaClass* foo = AbstractMetaClass::findClass(classes, QLatin1String("FooInt"));
- QVERIFY(foo);
- QVERIFY(foo->hasNonPrivateConstructor());
- const AbstractMetaFunctionList &lst = foo->queryFunctions(AbstractMetaClass::Constructors);
- for (const AbstractMetaFunction *f : lst)
- QVERIFY(f->signature().startsWith(f->name()));
- QCOMPARE(lst.size(), 2);
- const AbstractMetaFunction* method = foo->findFunction(QLatin1String("method"));
- QVERIFY(method);
-}
-
-void TestAddFunction::testAddFunctionWithTemplateArg()
-{
- const char cppCode[] = "template<class T> class Foo { };\n";
- const char xmlCode[] = "\
- <typesystem package='Package'>\n\
- <primitive-type name='int'/>\n\
- <container-type name='Foo' type='list'/>\n\
- <add-function signature='func(Foo&lt;int>)'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- QCOMPARE(builder->globalFunctions().size(), 1);
- AbstractMetaFunction* func = builder->globalFunctions().first();
- AbstractMetaArgument* arg = func->arguments().first();
- QCOMPARE(arg->type()->instantiations().count(), 1);
-}
-
-QTEST_APPLESS_MAIN(TestAddFunction)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testaddfunction.h b/sources/shiboken2/ApiExtractor/tests/testaddfunction.h
deleted file mode 100644
index d95f0ecfe..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testaddfunction.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTADDFUNCTION_H
-#define TESTADDFUNCTION_H
-#include <QObject>
-
-class TestAddFunction : public QObject
-{
- Q_OBJECT
-private slots:
- void testParsingFuncNameAndConstness();
- void testAddFunction();
- void testAddFunctionConstructor();
- void testAddFunctionTagDefaultValues();
- void testAddFunctionCodeSnippets();
- void testAddFunctionWithoutParenteses();
- void testAddFunctionWithDefaultArgs();
- void testAddFunctionAtModuleLevel();
- void testAddFunctionWithVarargs();
- void testAddStaticFunction();
- void testAddGlobalFunction();
- void testAddFunctionWithApiVersion();
- void testModifyAddedFunction();
- void testAddFunctionOnTypedef();
- void testAddFunctionWithTemplateArg();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testarrayargument.cpp b/sources/shiboken2/ApiExtractor/tests/testarrayargument.cpp
deleted file mode 100644
index a8b9a2eff..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testarrayargument.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testarrayargument.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestArrayArgument::testArrayArgumentWithSizeDefinedByInteger()
-{
- const char* cppCode ="\
- struct A {\n\
- enum SomeEnum { Value0, Value1, NValues };\n\
- void method(double[3]);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='double'/>\n\
- <object-type name='A'>\n\
- <enum-type name='SomeEnum'/>\n\
- </object-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("A"));
- QVERIFY(classA);
-
- const AbstractMetaArgument* arg = classA->functions().last()->arguments().first();
- QVERIFY(arg->type()->isArray());
- QCOMPARE(arg->type()->arrayElementCount(), 3);
- QCOMPARE(arg->type()->arrayElementType()->name(), QLatin1String("double"));
-}
-
-static QString functionMinimalSignature(const AbstractMetaClass *c, const QString &name)
-{
- const AbstractMetaFunction *f = c->findFunction(name);
- return f ? f->minimalSignature() : QString();
-}
-
-void TestArrayArgument::testArraySignature()
-{
- const char cppCode[] ="\
- struct A {\n\
- void mi1(int arg[5]);\n\
- void mi1c(const int arg[5]);\n\
- void mi1cu(const int arg[]);\n\
- void mc1cu(const char arg[]);\n\
- void mc1cup(const char *arg[]);\n\
- void muc2(unsigned char *arg[2][3]);\n\
- void mc2c(const char *arg[5][6]);\n\
- void mc2cu(const char arg[][2]);\n\
- };\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='char'/>\n\
- <primitive-type name='unsigned char'/>\n\
- <primitive-type name='int'/>\n\
- <object-type name='A'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("A"));
- QCOMPARE(functionMinimalSignature(classA, QLatin1String("mi1")),
- QLatin1String("mi1(int[5])"));
- QCOMPARE(functionMinimalSignature(classA, QLatin1String("mi1c")),
- QLatin1String("mi1c(const int[5])"));
- QCOMPARE(functionMinimalSignature(classA, QLatin1String("mi1cu")),
- QLatin1String("mi1cu(const int[])"));
- QCOMPARE(functionMinimalSignature(classA, QLatin1String("mc1cu")),
- QLatin1String("mc1cu(const char*)"));
- QCOMPARE(functionMinimalSignature(classA, QLatin1String("mc1cup")),
- QLatin1String("mc1cup(const char*[])"));
- QCOMPARE(functionMinimalSignature(classA, QLatin1String("muc2")),
- QLatin1String("muc2(unsigned char*[2][3])"));
- QCOMPARE(functionMinimalSignature(classA, QLatin1String("mc2c")),
- QLatin1String("mc2c(const char*[5][6])"));
- QCOMPARE(functionMinimalSignature(classA, QLatin1String("mc2cu")),
- QLatin1String("mc2cu(const char[][2])"));
-}
-
-void TestArrayArgument::testArrayArgumentWithSizeDefinedByEnumValue()
-{
- const char* cppCode ="\
- struct A {\n\
- enum SomeEnum { Value0, Value1, NValues };\n\
- void method(double[NValues]);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='double'/>\n\
- <object-type name='A'>\n\
- <enum-type name='SomeEnum'/>\n\
- </object-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("A"));
- QVERIFY(classA);
-
- AbstractMetaEnum* someEnum = classA->findEnum(QLatin1String("SomeEnum"));
- QVERIFY(someEnum);
- AbstractMetaEnumValue *nvalues = classA->findEnumValue(QLatin1String("NValues"));
- QVERIFY(nvalues);
-
- const AbstractMetaArgument* arg = classA->functions().last()->arguments().first();
- QVERIFY(arg->type()->isArray());
- QCOMPARE(arg->type()->arrayElementCount(), nvalues->value().value());
- QCOMPARE(arg->type()->arrayElementType()->name(), QLatin1String("double"));
-};
-
-void TestArrayArgument::testArrayArgumentWithSizeDefinedByEnumValueFromGlobalEnum()
-{
- const char* cppCode ="\
- enum SomeEnum { Value0, Value1, NValues };\n\
- struct A {\n\
- void method(double[NValues]);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='double'/>\n\
- <enum-type name='SomeEnum'/>\n\
- <object-type name='A'>\n\
- </object-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("A"));
- QVERIFY(classA);
-
- AbstractMetaEnum* someEnum = builder->globalEnums().first();
- QVERIFY(someEnum);
- const AbstractMetaEnumValue *nvalues = someEnum->findEnumValue(QLatin1String("NValues"));
- QVERIFY(nvalues);
-
- const AbstractMetaArgument* arg = classA->functions().last()->arguments().first();
- QVERIFY(arg->type()->isArray());
- QCOMPARE(arg->type()->arrayElementCount(), nvalues->value().value());
- QCOMPARE(arg->type()->arrayElementType()->name(), QLatin1String("double"));
-};
-
-QTEST_APPLESS_MAIN(TestArrayArgument)
diff --git a/sources/shiboken2/ApiExtractor/tests/testarrayargument.h b/sources/shiboken2/ApiExtractor/tests/testarrayargument.h
deleted file mode 100644
index 2e58ae6ee..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testarrayargument.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTARRAYARGUMENT_H
-#define TESTARRAYARGUMENT_H
-#include <QObject>
-
-class TestArrayArgument : public QObject
-{
- Q_OBJECT
-private slots:
- void testArrayArgumentWithSizeDefinedByInteger();
- void testArraySignature();
- void testArrayArgumentWithSizeDefinedByEnumValue();
- void testArrayArgumentWithSizeDefinedByEnumValueFromGlobalEnum();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testcodeinjection.cpp b/sources/shiboken2/ApiExtractor/tests/testcodeinjection.cpp
deleted file mode 100644
index aeca2d3f4..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testcodeinjection.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testcodeinjection.h"
-#include <QFileInfo>
-#include <QDir>
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestCodeInjections::testReadFile_data()
-{
- QTest::addColumn<QString>("filePath");
- QTest::addColumn<QString>("snippet");
- QTest::addColumn<QString>("expected");
-
- QTest::newRow("utf8")
- << QString::fromLatin1(":/utf8code.txt")
- << QString()
- << QString::fromUtf8("\xC3\xA1\xC3\xA9\xC3\xAD\xC3\xB3\xC3\xBA");
-
- QTest::newRow("snippet")
- << QString::fromLatin1(":/injectedcode.txt")
- << QString::fromLatin1("label")
- << QString::fromLatin1("code line");
-}
-
-void TestCodeInjections::testReadFile()
-{
- QFETCH(QString, filePath);
- QFETCH(QString, snippet);
- QFETCH(QString, expected);
-
- const char* cppCode ="struct A {};\n";
- int argc = 0;
- char *argv[] = {nullptr};
- QCoreApplication app(argc, argv);
-
- QString attribute = QLatin1String("file='") + filePath + QLatin1Char('\'');
- if (!snippet.isEmpty())
- attribute += QLatin1String(" snippet='") + snippet + QLatin1Char('\'');
-
- QString xmlCode = QLatin1String("\
- <typesystem package=\"Foo\">\n\
- <value-type name='A'>\n\
- <conversion-rule ") + attribute + QLatin1String("/>\n\
- <inject-code class='target' ") + attribute + QLatin1String("/>\n\
- <value-type name='B'/>\n\
- </value-type>\n\
- </typesystem>\n");
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode.toLocal8Bit().constData()));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QCOMPARE(classA->typeEntry()->codeSnips().count(), 1);
- QString code = classA->typeEntry()->codeSnips().first().code();
- QVERIFY(code.indexOf(expected) != -1);
- code = classA->typeEntry()->conversionRule();
- QVERIFY(code.indexOf(expected) != -1);
-}
-
-void TestCodeInjections::testInjectWithValidApiVersion()
-{
- const char* cppCode ="struct A {};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'>\n\
- <inject-code class='target' since='1.0'>\n\
- test Inject code\n\
- </inject-code>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- true, QLatin1String("1.0")));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QCOMPARE(classA->typeEntry()->codeSnips().count(), 1);
-}
-
-void TestCodeInjections::testInjectWithInvalidApiVersion()
-{
- const char* cppCode ="struct A {};\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <value-type name='A'>\n\
- <inject-code class='target' since='1.0'>\n\
- test Inject code\n\
- </inject-code>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- true, QLatin1String("0.1")));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QCOMPARE(classA->typeEntry()->codeSnips().count(), 0);
-}
-
-
-
-QTEST_APPLESS_MAIN(TestCodeInjections)
diff --git a/sources/shiboken2/ApiExtractor/tests/testcodeinjection.h b/sources/shiboken2/ApiExtractor/tests/testcodeinjection.h
deleted file mode 100644
index 1ac873970..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testcodeinjection.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTCODEINJECTIONS_H
-#define TESTCODEINJECTIONS_H
-
-#include <QObject>
-
-class AbstractMetaBuilder;
-
-class TestCodeInjections : public QObject
-{
- Q_OBJECT
-private slots:
- void testReadFile_data();
- void testReadFile();
- void testInjectWithValidApiVersion();
- void testInjectWithInvalidApiVersion();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testcodeinjection.qrc b/sources/shiboken2/ApiExtractor/tests/testcodeinjection.qrc
deleted file mode 100644
index fd7616bd2..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testcodeinjection.qrc
+++ /dev/null
@@ -1,6 +0,0 @@
-<RCC>
- <qresource>
- <file>utf8code.txt</file>
- <file>injectedcode.txt</file>
- </qresource>
-</RCC>
diff --git a/sources/shiboken2/ApiExtractor/tests/testcontainer.cpp b/sources/shiboken2/ApiExtractor/tests/testcontainer.cpp
deleted file mode 100644
index aaa72238c..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testcontainer.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testcontainer.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestContainer::testContainerType()
-{
- const char* cppCode ="\
- namespace std {\n\
- template<class T>\n\
- class list {\n\
- T get(int x) { return 0; }\n\
- };\n\
- }\n\
- class A : public std::list<int> {\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <namespace-type name='std' generate='no' />\n\
- <container-type name='std::list' type='list' />\n\
- <object-type name='A'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, true));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- //search for class A
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- auto baseContainer = classA->typeEntry()->baseContainerType();
- QVERIFY(baseContainer);
- QCOMPARE(reinterpret_cast<const ContainerTypeEntry*>(baseContainer)->containerKind(),
- ContainerTypeEntry::ListContainer);
-}
-
-void TestContainer::testListOfValueType()
-{
- const char* cppCode ="\
- namespace std {\n\
- template<class T>\n\
- class list {\n\
- T get(int x) { return 0; }\n\
- };\n\
- }\n\
- class ValueType {};\n\
- class A : public std::list<ValueType> {\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <namespace-type name='std' generate='no'/>\n\
- <container-type name='std::list' type='list'/>\n\
- <value-type name='ValueType'/>\n\
- <value-type name='A'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, true));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 3);
-
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->templateBaseClassInstantiations().count(), 1);
- const AbstractMetaType* templateInstanceType = classA->templateBaseClassInstantiations().first();
- QVERIFY(templateInstanceType);
-
- QCOMPARE(templateInstanceType->indirections(), 0);
- QVERIFY(!templateInstanceType->typeEntry()->isObject());
- QVERIFY(templateInstanceType->typeEntry()->isValue());
- QCOMPARE(templateInstanceType->referenceType(), NoReference);
- QVERIFY(!templateInstanceType->isObject());
- QVERIFY(!templateInstanceType->isValuePointer());
- QVERIFY(templateInstanceType->isValue());
-}
-
-QTEST_APPLESS_MAIN(TestContainer)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testcontainer.h b/sources/shiboken2/ApiExtractor/tests/testcontainer.h
deleted file mode 100644
index 44e6636aa..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testcontainer.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTCONTAINER_H
-#define TESTCONTAINER_H
-#include <QObject>
-
-class TestContainer : public QObject
-{
- Q_OBJECT
-private slots:
- void testContainerType();
- void testListOfValueType();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testconversionoperator.cpp b/sources/shiboken2/ApiExtractor/tests/testconversionoperator.cpp
deleted file mode 100644
index 142c783a4..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testconversionoperator.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testconversionoperator.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestConversionOperator::testConversionOperator()
-{
- const char cppCode[] = "\
- struct A {\n\
- };\n\
- struct B {\n\
- operator A() const;\n\
- };\n\
- struct C {\n\
- operator A() const;\n\
- };\n";
- const char xmlCode[] = "\
- <typesystem package=\"Foo\">\n\
- <value-type name='A'/>\n\
- <value-type name='B'/>\n\
- <value-type name='C'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- const AbstractMetaClass *classC = AbstractMetaClass::findClass(classes, QLatin1String("C"));
- QVERIFY(classA);
- QVERIFY(classB);
- QVERIFY(classC);
- QCOMPARE(classA->functions().count(), 2);
- QCOMPARE(classB->functions().count(), 3);
- QCOMPARE(classC->functions().count(), 3);
- QCOMPARE(classA->externalConversionOperators().count(), 2);
-
- AbstractMetaFunction *convOp = nullptr;
- for (AbstractMetaFunction *func : classB->functions()) {
- if (func->isConversionOperator()) {
- convOp = func;
- break;
- }
- }
- QVERIFY(convOp);
- QVERIFY(classA->externalConversionOperators().contains(convOp));
-}
-
-void TestConversionOperator::testConversionOperatorOfDiscardedClass()
-{
- const char cppCode[] = "\
- struct A {\n\
- };\n\
- struct B {\n\
- operator A() const;\n\
- };\n";
- const char xmlCode[] = "\
- <typesystem package=\"Foo\">\n\
- <value-type name='A' />\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->externalConversionOperators().count(), 0);
-}
-
-void TestConversionOperator::testRemovedConversionOperator()
-{
- const char cppCode[] = "\
- struct A {\n\
- };\n\
- struct B {\n\
- operator A() const;\n\
- };\n";
- const char xmlCode[] = "\
- <typesystem package=\"Foo\">\n\
- <value-type name='A' />\n\
- <value-type name='B'>\n\
- <modify-function signature='operator A() const' remove='all'/>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classA);
- QVERIFY(classB);
- QCOMPARE(classA->functions().count(), 2);
- QCOMPARE(classB->functions().count(), 3);
- QCOMPARE(classA->externalConversionOperators().count(), 0);
- QCOMPARE(classA->implicitConversions().count(), 0);
-}
-
-void TestConversionOperator::testConversionOperatorReturningReference()
-{
- const char cppCode[] = "\
- struct A {};\n\
- struct B {\n\
- operator A&() const;\n\
- };\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'/>\n\
- <value-type name='B'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classA);
- QVERIFY(classB);
- QCOMPARE(classA->functions().count(), 2);
- QCOMPARE(classB->functions().count(), 3);
- QCOMPARE(classA->externalConversionOperators().count(), 1);
- QCOMPARE(classA->externalConversionOperators().first()->type()->cppSignature(), QLatin1String("A"));
- QCOMPARE(classA->externalConversionOperators().first()->ownerClass()->name(), QLatin1String("B"));
- QCOMPARE(classA->implicitConversions().count(), 1);
- QCOMPARE(classA->implicitConversions().first()->type()->cppSignature(), QLatin1String("A"));
- QCOMPARE(classA->implicitConversions().first()->ownerClass()->name(), QLatin1String("B"));
-}
-
-void TestConversionOperator::testConversionOperatorReturningConstReference()
-{
- const char cppCode[] = "\
- struct A {};\n\
- struct B {\n\
- operator const A&() const;\n\
- };\n";
- const char xmlCode[] = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'/>\n\
- <value-type name='B'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classA);
- QVERIFY(classB);
- QCOMPARE(classA->functions().count(), 2);
- QCOMPARE(classB->functions().count(), 3);
- QCOMPARE(classA->externalConversionOperators().count(), 1);
- QCOMPARE(classA->externalConversionOperators().first()->type()->cppSignature(), QLatin1String("A"));
- QCOMPARE(classA->externalConversionOperators().first()->ownerClass()->name(), QLatin1String("B"));
- QCOMPARE(classA->implicitConversions().count(), 1);
- QCOMPARE(classA->implicitConversions().first()->type()->cppSignature(), QLatin1String("A"));
- QCOMPARE(classA->implicitConversions().first()->ownerClass()->name(), QLatin1String("B"));
-}
-
-QTEST_APPLESS_MAIN(TestConversionOperator)
diff --git a/sources/shiboken2/ApiExtractor/tests/testconversionoperator.h b/sources/shiboken2/ApiExtractor/tests/testconversionoperator.h
deleted file mode 100644
index b571a57a0..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testconversionoperator.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTCONVERSIONOPERATOR_H
-#define TESTCONVERSIONOPERATOR_H
-#include <QObject>
-
-class TestConversionOperator : public QObject
-{
- Q_OBJECT
-private slots:
- void testConversionOperator();
- void testConversionOperatorOfDiscardedClass();
- void testRemovedConversionOperator();
- void testConversionOperatorReturningReference();
- void testConversionOperatorReturningConstReference();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testconversionruletag.cpp b/sources/shiboken2/ApiExtractor/tests/testconversionruletag.cpp
deleted file mode 100644
index aa2bec5d6..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testconversionruletag.cpp
+++ /dev/null
@@ -1,250 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testconversionruletag.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-#include <QFile>
-#include <QTemporaryFile>
-
-void TestConversionRuleTag::testConversionRuleTagWithFile()
-{
- // temp file used later
- const char conversionData[] = "Hi! I'm a conversion rule.";
- QTemporaryFile file;
- file.open();
- QCOMPARE(file.write(conversionData), qint64(sizeof(conversionData)-1));
- file.close();
-
- const char cppCode[] = "struct A {};\n";
- QString xmlCode = QLatin1String("\
- <typesystem package='Foo'>\n\
- <value-type name='A'>\n\
- <conversion-rule file='") + file.fileName() + QLatin1String("'/>\n\
- </value-type>\n\
- </typesystem>\n");
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode.toLocal8Bit().data()));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const ComplexTypeEntry* typeEntry = classA->typeEntry();
- QVERIFY(typeEntry->hasConversionRule());
- QCOMPARE(typeEntry->conversionRule(), QLatin1String(conversionData));
-}
-
-void TestConversionRuleTag::testConversionRuleTagReplace()
-{
- const char cppCode[] = "\
- struct A {\n\
- A();\n\
- A(const char*, int);\n\
- };\n\
- struct B {\n\
- A createA();\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <primitive-type name='char'/>\n\
- <primitive-type name='A'>\n\
- <conversion-rule>\n\
- <native-to-target>\n\
- DoThis();\n\
- return ConvertFromCppToPython(%IN);\n\
- </native-to-target>\n\
- <target-to-native>\n\
- <add-conversion type='TargetNone' check='%IN == Target_None'>\n\
- DoThat();\n\
- DoSomething();\n\
- %OUT = A();\n\
- </add-conversion>\n\
- <add-conversion type='B' check='CheckIfInputObjectIsB(%IN)'>\n\
- %OUT = %IN.createA();\n\
- </add-conversion>\n\
- <add-conversion type='String' check='String_Check(%IN)'>\n\
- %OUT = new A(String_AsString(%IN), String_GetSize(%IN));\n\
- </add-conversion>\n\
- </target-to-native>\n\
- </conversion-rule>\n\
- </primitive-type>\n\
- <value-type name='B'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- TypeDatabase* typeDb = TypeDatabase::instance();
- PrimitiveTypeEntry* typeA = typeDb->findPrimitiveType(QLatin1String("A"));
- QVERIFY(typeA);
-
- CustomConversion* conversion = typeA->customConversion();
- QVERIFY(conversion);
-
- QCOMPARE(typeA, conversion->ownerType());
- QCOMPARE(conversion->nativeToTargetConversion().simplified(),
- QLatin1String("DoThis(); return ConvertFromCppToPython(%IN);"));
-
- QVERIFY(conversion->replaceOriginalTargetToNativeConversions());
- QVERIFY(conversion->hasTargetToNativeConversions());
- QCOMPARE(conversion->targetToNativeConversions().size(), 3);
-
- CustomConversion::TargetToNativeConversion* toNative = conversion->targetToNativeConversions().at(0);
- QVERIFY(toNative);
- QCOMPARE(toNative->sourceTypeName(), QLatin1String("TargetNone"));
- QVERIFY(toNative->isCustomType());
- QCOMPARE(toNative->sourceType(), nullptr);
- QCOMPARE(toNative->sourceTypeCheck(), QLatin1String("%IN == Target_None"));
- QCOMPARE(toNative->conversion().simplified(),
- QLatin1String("DoThat(); DoSomething(); %OUT = A();"));
-
- toNative = conversion->targetToNativeConversions().at(1);
- QVERIFY(toNative);
- QCOMPARE(toNative->sourceTypeName(), QLatin1String("B"));
- QVERIFY(!toNative->isCustomType());
- TypeEntry* typeB = typeDb->findType(QLatin1String("B"));
- QVERIFY(typeB);
- QCOMPARE(toNative->sourceType(), typeB);
- QCOMPARE(toNative->sourceTypeCheck(), QLatin1String("CheckIfInputObjectIsB(%IN)"));
- QCOMPARE(toNative->conversion().trimmed(), QLatin1String("%OUT = %IN.createA();"));
-
- toNative = conversion->targetToNativeConversions().at(2);
- QVERIFY(toNative);
- QCOMPARE(toNative->sourceTypeName(), QLatin1String("String"));
- QVERIFY(toNative->isCustomType());
- QCOMPARE(toNative->sourceType(), nullptr);
- QCOMPARE(toNative->sourceTypeCheck(), QLatin1String("String_Check(%IN)"));
- QCOMPARE(toNative->conversion().trimmed(), QLatin1String("%OUT = new A(String_AsString(%IN), String_GetSize(%IN));"));
-}
-
-void TestConversionRuleTag::testConversionRuleTagAdd()
-{
- const char cppCode[] = "\
- struct Date {\n\
- Date();\n\
- Date(int, int, int);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <value-type name='Date'>\n\
- <conversion-rule>\n\
- <target-to-native replace='no'>\n\
- <add-conversion type='TargetDate' check='TargetDate_Check(%IN)'>\n\
-if (!TargetDateTimeAPI) TargetDateTime_IMPORT;\n\
-%OUT = new Date(TargetDate_Day(%IN), TargetDate_Month(%IN), TargetDate_Year(%IN));\n\
- </add-conversion>\n\
- </target-to-native>\n\
- </conversion-rule>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("Date"));
- QVERIFY(classA);
-
- CustomConversion* conversion = classA->typeEntry()->customConversion();
- QVERIFY(conversion);
-
- QCOMPARE(conversion->nativeToTargetConversion(), QString());
-
- QVERIFY(!conversion->replaceOriginalTargetToNativeConversions());
- QVERIFY(conversion->hasTargetToNativeConversions());
- QCOMPARE(conversion->targetToNativeConversions().size(), 1);
-
- CustomConversion::TargetToNativeConversion* toNative = conversion->targetToNativeConversions().first();
- QVERIFY(toNative);
- QCOMPARE(toNative->sourceTypeName(), QLatin1String("TargetDate"));
- QVERIFY(toNative->isCustomType());
- QCOMPARE(toNative->sourceType(), nullptr);
- QCOMPARE(toNative->sourceTypeCheck(), QLatin1String("TargetDate_Check(%IN)"));
- QCOMPARE(toNative->conversion().trimmed(),
- QLatin1String("if (!TargetDateTimeAPI) TargetDateTime_IMPORT;\n%OUT = new Date(TargetDate_Day(%IN), TargetDate_Month(%IN), TargetDate_Year(%IN));"));
-}
-
-void TestConversionRuleTag::testConversionRuleTagWithInsertTemplate()
-{
- const char cppCode[] = "struct A {};";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <!-- single line -->\n\
- <template name='native_to_target'>return ConvertFromCppToPython(%IN);</template>\n\
- <!-- multi-line -->\n\
- <template name='target_to_native'>\n\
-%OUT = %IN.createA();\n\
- </template>\n\
- <primitive-type name='A'>\n\
- <conversion-rule>\n\
- <native-to-target>\n\
- <insert-template name='native_to_target'/>\n\
- </native-to-target>\n\
- <target-to-native>\n\
- <add-conversion type='TargetType'>\n\
- <insert-template name='target_to_native'/>\n\
- </add-conversion>\n\
- </target-to-native>\n\
- </conversion-rule>\n\
- </primitive-type>\n\
- </typesystem>\n";
-
- const char nativeToTargetExpected[] =
- "// TEMPLATE - native_to_target - START\n"
- "return ConvertFromCppToPython(%IN);\n"
- "// TEMPLATE - native_to_target - END";
-
- const char targetToNativeExpected[] =
- "// TEMPLATE - target_to_native - START\n"
- "%OUT = %IN.createA();\n"
- "// TEMPLATE - target_to_native - END";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- TypeDatabase* typeDb = TypeDatabase::instance();
- PrimitiveTypeEntry* typeA = typeDb->findPrimitiveType(QLatin1String("A"));
- QVERIFY(typeA);
-
- CustomConversion* conversion = typeA->customConversion();
- QVERIFY(conversion);
-
- QCOMPARE(typeA, conversion->ownerType());
- QCOMPARE(conversion->nativeToTargetConversion().trimmed(),
- QLatin1String(nativeToTargetExpected));
-
- QVERIFY(conversion->hasTargetToNativeConversions());
- QCOMPARE(conversion->targetToNativeConversions().size(), 1);
-
- CustomConversion::TargetToNativeConversion* toNative = conversion->targetToNativeConversions().first();
- QVERIFY(toNative);
- QCOMPARE(toNative->conversion().trimmed(),
- QLatin1String(targetToNativeExpected));
-}
-
-QTEST_APPLESS_MAIN(TestConversionRuleTag)
diff --git a/sources/shiboken2/ApiExtractor/tests/testconversionruletag.h b/sources/shiboken2/ApiExtractor/tests/testconversionruletag.h
deleted file mode 100644
index 894bd3d71..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testconversionruletag.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTCONVERSIONRULE_H
-#define TESTCONVERSIONRULE_H
-#include <QObject>
-
-class TestConversionRuleTag : public QObject
-{
- Q_OBJECT
-private slots:
- void testConversionRuleTagWithFile();
- void testConversionRuleTagReplace();
- void testConversionRuleTagAdd();
- void testConversionRuleTagWithInsertTemplate();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testctorinformation.cpp b/sources/shiboken2/ApiExtractor/tests/testctorinformation.cpp
deleted file mode 100644
index 7718d3df6..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testctorinformation.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testctorinformation.h"
-#include "abstractmetabuilder.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestCtorInformation::testCtorIsPrivate()
-{
- const char* cppCode = "class Control { public: Control() {} };\n\
- class Subject { private: Subject() {} };\n\
- class CtorLess { };\n";
- const char* xmlCode = "<typesystem package='Foo'>\n\
- <value-type name='Control'/>\n\
- <object-type name='Subject'/>\n\
- <value-type name='CtorLess'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 3);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Control"))->hasNonPrivateConstructor(), true);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Subject"))->hasNonPrivateConstructor(), false);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("CtorLess"))->hasNonPrivateConstructor(), true);
-}
-
-void TestCtorInformation::testHasNonPrivateCtor()
-{
- const char* cppCode = "template<typename T>\n\
- struct Base { Base(double) {} };\n\
- typedef Base<int> Derived;\n";
- const char* xmlCode = "<typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <primitive-type name='double'/>\n\
- <object-type name='Base' generate='no'/>\n\
- <object-type name='Derived'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- const AbstractMetaClass *base = AbstractMetaClass::findClass(classes, QLatin1String("Base"));
- QCOMPARE(base->hasNonPrivateConstructor(), true);
- const AbstractMetaClass *derived = AbstractMetaClass::findClass(classes, QLatin1String("Derived"));
- QCOMPARE(derived->hasNonPrivateConstructor(), true);
-}
-
-QTEST_APPLESS_MAIN(TestCtorInformation)
diff --git a/sources/shiboken2/ApiExtractor/tests/testctorinformation.h b/sources/shiboken2/ApiExtractor/tests/testctorinformation.h
deleted file mode 100644
index ee655d450..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testctorinformation.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTCTORINFORMATION_H
-#define TESTCTORINFORMATION_H
-
-#include <QObject>
-
-class AbstractMetaBuilder;
-
-class TestCtorInformation: public QObject
-{
- Q_OBJECT
-private slots:
- void testCtorIsPrivate();
- void testHasNonPrivateCtor();
-};
-
-#endif // TESTCTORINFORMATION_H
diff --git a/sources/shiboken2/ApiExtractor/tests/testdroptypeentries.cpp b/sources/shiboken2/ApiExtractor/tests/testdroptypeentries.cpp
deleted file mode 100644
index 6abebb922..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testdroptypeentries.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testdroptypeentries.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-static const char* cppCode ="\
- struct ValueA {};\n\
- struct ValueB {};\n\
- struct ObjectA {};\n\
- struct ObjectB {};\n\
- namespace NamespaceA {\n\
- struct InnerClassA {};\n\
- namespace InnerNamespaceA {}\n\
- }\n\
- namespace NamespaceB {}\n\
- enum EnumA { Value0 };\n\
- enum EnumB { Value1 };\n\
- void funcA();\n\
- void funcB();\n";
-
-static const char* xmlCode = "\
-<typesystem package='Foo'>\n\
- <value-type name='ValueA'/>\n\
- <value-type name='ValueB'/>\n\
- <object-type name='ObjectA'/>\n\
- <object-type name='ObjectB'/>\n\
- <namespace-type name='NamespaceA'>\n\
- <value-type name='InnerClassA'/>\n\
- <namespace-type name='InnerNamespaceA'/>\n\
- </namespace-type>\n\
- <namespace-type name='NamespaceB'/>\n\
- <enum-type name='EnumA'/>\n\
- <enum-type name='EnumB'/>\n\
- <function signature='funcA()'/>\n\
- <function signature='funcB()'/>\n\
-</typesystem>\n";
-
-void TestDropTypeEntries::testDropEntries()
-{
- QStringList droppedEntries(QLatin1String("Foo.ValueB"));
- droppedEntries << QLatin1String("Foo.ObjectB") << QLatin1String("Foo.NamespaceA.InnerClassA");
- droppedEntries << QLatin1String("Foo.NamespaceB") << QLatin1String("Foo.EnumB") << QLatin1String("Foo.funcB()");
- droppedEntries << QLatin1String("Foo.NamespaceA.InnerNamespaceA");
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false,
- QString(), droppedEntries));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("ValueA")));
- QVERIFY(!AbstractMetaClass::findClass(classes, QLatin1String("ValueB")));
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("ObjectA")));
- QVERIFY(!AbstractMetaClass::findClass(classes, QLatin1String("ObjectB")));
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("NamespaceA")));
- QVERIFY(!AbstractMetaClass::findClass(classes, QLatin1String("NamespaceA::InnerClassA")));
- QVERIFY(!AbstractMetaClass::findClass(classes, QLatin1String("NamespaceB")));
-
- AbstractMetaEnumList globalEnums = builder->globalEnums();
- QCOMPARE(globalEnums.count(), 1);
- QCOMPARE(globalEnums.first()->name(), QLatin1String("EnumA"));
-
- TypeDatabase* td = TypeDatabase::instance();
- QVERIFY(td->findType(QLatin1String("funcA")));
- QVERIFY(!td->findType(QLatin1String("funcB")));
-}
-
-void TestDropTypeEntries::testDontDropEntries()
-{
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("ValueA")));
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("ValueB")));
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("ObjectA")));
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("ObjectB")));
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("NamespaceA")));
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("NamespaceA::InnerClassA")));
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("NamespaceB")));
-
- QCOMPARE(builder->globalEnums().size(), 2);
-
- TypeDatabase* td = TypeDatabase::instance();
- QVERIFY(td->findType(QLatin1String("funcA")));
- QVERIFY(td->findType(QLatin1String("funcB")));
-}
-
-static const char* cppCode2 ="\
- struct ValueA {\n\
- void func();\n\
- };\n";
-
-static const char* xmlCode2 = "\
-<typesystem package='Foo'>\n\
- <value-type name='ValueA'>\n\
- <modify-function signature='func()'>\n\
- <remove class='all'/>\n\
- </modify-function>\n\
- </value-type>\n\
-</typesystem>\n";
-
-void TestDropTypeEntries::testDropEntryWithChildTags()
-{
- QStringList droppedEntries(QLatin1String("Foo.ValueA"));
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode2, xmlCode2, false,
- QString(), droppedEntries));
- QVERIFY(!builder.isNull());
- QVERIFY(!AbstractMetaClass::findClass(builder->classes(), QLatin1String("ValueA")));
-}
-
-
-void TestDropTypeEntries::testDontDropEntryWithChildTags()
-{
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode2, xmlCode2, false));
- QVERIFY(!builder.isNull());
- QVERIFY(AbstractMetaClass::findClass(builder->classes(), QLatin1String("ValueA")));
-}
-
-QTEST_APPLESS_MAIN(TestDropTypeEntries)
diff --git a/sources/shiboken2/ApiExtractor/tests/testdroptypeentries.h b/sources/shiboken2/ApiExtractor/tests/testdroptypeentries.h
deleted file mode 100644
index 3023a1120..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testdroptypeentries.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTDROPTYPEENTRIES_H
-#define TESTDROPTYPEENTRIES_H
-
-#include <QObject>
-
-class TestDropTypeEntries : public QObject
-{
- Q_OBJECT
- private slots:
- void testDropEntries();
- void testDontDropEntries();
- void testDropEntryWithChildTags();
- void testDontDropEntryWithChildTags();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testdtorinformation.cpp b/sources/shiboken2/ApiExtractor/tests/testdtorinformation.cpp
deleted file mode 100644
index 0eee8af24..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testdtorinformation.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testdtorinformation.h"
-#include "abstractmetabuilder.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestDtorInformation::testDtorIsPrivate()
-{
- const char* cppCode ="class Control { public: ~Control() {} }; class Subject { private: ~Subject() {} };";
- const char* xmlCode = "<typesystem package=\"Foo\"><value-type name=\"Control\"/><value-type name=\"Subject\"/></typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Control"))->hasPrivateDestructor(), false);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Subject"))->hasPrivateDestructor(), true);
-}
-
-void TestDtorInformation::testDtorIsProtected()
-{
- const char* cppCode ="class Control { public: ~Control() {} }; class Subject { protected: ~Subject() {} };";
- const char* xmlCode = "<typesystem package=\"Foo\"><value-type name=\"Control\"/><value-type name=\"Subject\"/></typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Control"))->hasProtectedDestructor(), false);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Subject"))->hasProtectedDestructor(), true);
-}
-
-void TestDtorInformation::testDtorIsVirtual()
-{
- const char* cppCode ="class Control { public: ~Control() {} }; class Subject { protected: virtual ~Subject() {} };";
- const char* xmlCode = "<typesystem package=\"Foo\"><value-type name=\"Control\"/><value-type name=\"Subject\"/></typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Control"))->hasVirtualDestructor(), false);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Subject"))->hasVirtualDestructor(), true);
-}
-
-void TestDtorInformation::testDtorFromBaseIsVirtual()
-{
- const char* cppCode = R"CPP(class ControlBase { public: ~ControlBase() {} };
-class Control : public ControlBase {};
-class SubjectBase { public: virtual ~SubjectBase() {} };
-class Subject : public SubjectBase {};
-)CPP";
- const char* xmlCode = R"XML(<typesystem package="Foo"><value-type name="ControlBase"/>
-<value-type name="Control"/>"
-<value-type name="SubjectBase"/>"
-<value-type name="Subject"/>
-</typesystem>
-)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 4);
-
- auto klass = AbstractMetaClass::findClass(classes, QLatin1String("ControlBase"));
- QVERIFY(klass);
- QVERIFY(!klass->hasVirtualDestructor());
- klass = AbstractMetaClass::findClass(classes, QLatin1String("Control"));
- QVERIFY(klass);
- QVERIFY(!klass->hasVirtualDestructor());
-
- klass = AbstractMetaClass::findClass(classes, QLatin1String("SubjectBase"));
- QVERIFY(klass);
- QVERIFY(klass->hasVirtualDestructor());
- klass = AbstractMetaClass::findClass(classes, QLatin1String("Subject"));
- QVERIFY(klass);
- QVERIFY(klass->hasVirtualDestructor());
-}
-
-void TestDtorInformation::testClassWithVirtualDtorIsPolymorphic()
-{
- const char* cppCode ="class Control { public: virtual ~Control() {} }; class Subject { protected: virtual ~Subject() {} };";
- const char* xmlCode = "<typesystem package=\"Foo\"><value-type name=\"Control\"/><value-type name=\"Subject\"/></typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Control"))->isPolymorphic(), true);
- QCOMPARE(AbstractMetaClass::findClass(classes, QLatin1String("Subject"))->isPolymorphic(), true);
-}
-
-QTEST_APPLESS_MAIN(TestDtorInformation)
-
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testdtorinformation.h b/sources/shiboken2/ApiExtractor/tests/testdtorinformation.h
deleted file mode 100644
index 0a57dd8d1..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testdtorinformation.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTDTORINFORMATION_H
-#define TESTDTORINFORMATION_H
-
-#include <QObject>
-
-class AbstractMetaBuilder;
-
-class TestDtorInformation: public QObject
-{
- Q_OBJECT
-private slots:
- void testDtorIsPrivate();
- void testDtorIsProtected();
- void testDtorIsVirtual();
- void testDtorFromBaseIsVirtual();
- void testClassWithVirtualDtorIsPolymorphic();
-};
-
-#endif // TESTDTORINFORMATION_H
diff --git a/sources/shiboken2/ApiExtractor/tests/testenum.cpp b/sources/shiboken2/ApiExtractor/tests/testenum.cpp
deleted file mode 100644
index c04a37d9d..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testenum.cpp
+++ /dev/null
@@ -1,435 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testenum.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestEnum::testEnumCppSignature()
-{
- const char* cppCode ="\
- enum GlobalEnum { A, B };\n\
- \n\
- struct A {\n\
- enum ClassEnum { CA, CB };\n\
- void method(ClassEnum);\n\
- };\n\
- void func(A::ClassEnum);\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <enum-type name='GlobalEnum'/>\n\
- <value-type name='A'>\n\
- <enum-type name='ClassEnum'/>\n\
- </value-type>\n\
- <function signature='func(A::ClassEnum)'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
-
- AbstractMetaEnumList globalEnums = builder->globalEnums();
- QCOMPARE(globalEnums.count(), 1);
- QCOMPARE(globalEnums.first()->name(), QLatin1String("GlobalEnum"));
-
- // enum as parameter of a function
- AbstractMetaFunctionList functions = builder->globalFunctions();
- QCOMPARE(functions.count(), 1);
- QCOMPARE(functions.first()->arguments().count(), 1);
- QCOMPARE(functions.first()->arguments().first()->type()->cppSignature(), QLatin1String("A::ClassEnum"));
-
- // enum as parameter of a method
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QCOMPARE(classA->enums().count(), 1);
- AbstractMetaFunctionList funcs = classA->queryFunctionsByName(QLatin1String("method"));
- QVERIFY(!funcs.isEmpty());
- AbstractMetaFunction* method = funcs.first();
- QVERIFY(method);
- AbstractMetaArgument* arg = method->arguments().first();
- QCOMPARE(arg->type()->name(), QLatin1String("ClassEnum"));
- QCOMPARE(arg->type()->cppSignature(), QLatin1String("A::ClassEnum"));
- QCOMPARE(functions.first()->arguments().count(), 1);
- arg = functions.first()->arguments().first();
- QCOMPARE(arg->type()->name(), QLatin1String("ClassEnum"));
- QCOMPARE(arg->type()->cppSignature(), QLatin1String("A::ClassEnum"));
-
- AbstractMetaEnumList classEnums = classA->enums();
- QCOMPARE(classEnums.first()->name(), QLatin1String("ClassEnum"));
- AbstractMetaEnumValue *e = AbstractMetaClass::findEnumValue(classes, QLatin1String("CA"));
- QVERIFY(e);
- e = AbstractMetaClass::findEnumValue(classes, QLatin1String("ClassEnum::CA"));
- QVERIFY(e);
-}
-
-void TestEnum::testEnumWithApiVersion()
-{
- const char* cppCode ="\
- struct A {\n\
- enum ClassEnum { EnumA, EnumB };\n\
- enum ClassEnum2 { EnumC, EnumD };\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <value-type name='A'>\n\
- <enum-type name='ClassEnum' since='0.1'/>\n\
- <enum-type name='ClassEnum2' since='0.2'/>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- true, QLatin1String("0.1")));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
- QCOMPARE(classes[0]->enums().count(), 1);
-}
-
-void TestEnum::testAnonymousEnum()
-{
- const char* cppCode ="\
- enum { Global0, Global1 };\n\
- struct A {\n\
- enum { A0, A1 };\n\
- enum { isThis = true, isThat = false };\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <!-- Uses the first value of the enum to identify it. -->\n\
- <enum-type identified-by-value='Global0'/>\n\
- <value-type name='A'>\n\
- <!-- Uses the second value of the enum to identify it. -->\n\
- <enum-type identified-by-value='A1'/>\n\
- <enum-type identified-by-value='isThis'/>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaEnumList globalEnums = builder->globalEnums();
- QCOMPARE(globalEnums.count(), 1);
- QCOMPARE(globalEnums.first()->typeEntry()->qualifiedCppName(), QLatin1String("Global0"));
- QVERIFY(globalEnums.first()->isAnonymous());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
- QCOMPARE(classes[0]->enums().count(), 2);
-
- AbstractMetaEnum* anonEnumA1 = classes[0]->findEnum(QLatin1String("A1"));
- QVERIFY(anonEnumA1);
- QVERIFY(anonEnumA1->isAnonymous());
- QCOMPARE(anonEnumA1->typeEntry()->qualifiedCppName(), QLatin1String("A::A1"));
-
- AbstractMetaEnumValue* enumValueA0 = anonEnumA1->values().first();
- QCOMPARE(enumValueA0->name(), QLatin1String("A0"));
- QCOMPARE(enumValueA0->value().value(), 0);
- QCOMPARE(enumValueA0->stringValue(), QString());
-
- AbstractMetaEnumValue* enumValueA1 = anonEnumA1->values().last();
- QCOMPARE(enumValueA1->name(), QLatin1String("A1"));
- QCOMPARE(enumValueA1->value().value(), 1);
- QCOMPARE(enumValueA1->stringValue(), QString());
-
- AbstractMetaEnum* anonEnumIsThis = classes[0]->findEnum(QLatin1String("isThis"));
- QVERIFY(anonEnumIsThis);
- QVERIFY(anonEnumIsThis->isAnonymous());
- QCOMPARE(anonEnumIsThis->typeEntry()->qualifiedCppName(), QLatin1String("A::isThis"));
-
- AbstractMetaEnumValue* enumValueIsThis = anonEnumIsThis->values().first();
- QCOMPARE(enumValueIsThis->name(), QLatin1String("isThis"));
- QCOMPARE(enumValueIsThis->value().value(), static_cast<int>(true));
- QCOMPARE(enumValueIsThis->stringValue(), QLatin1String("true"));
-
- AbstractMetaEnumValue* enumValueIsThat = anonEnumIsThis->values().last();
- QCOMPARE(enumValueIsThat->name(), QLatin1String("isThat"));
- QCOMPARE(enumValueIsThat->value().value(), static_cast<int>(false));
- QCOMPARE(enumValueIsThat->stringValue(), QLatin1String("false"));
-}
-
-void TestEnum::testGlobalEnums()
-{
- const char* cppCode ="\
- enum EnumA { A0, A1 };\n\
- enum EnumB { B0 = 2, B1 = 0x4 };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <enum-type name='EnumA'/>\n\
- <enum-type name='EnumB'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaEnumList globalEnums = builder->globalEnums();
- QCOMPARE(globalEnums.count(), 2);
-
- AbstractMetaEnum* enumA = globalEnums.first();
- QCOMPARE(enumA->typeEntry()->qualifiedCppName(), QLatin1String("EnumA"));
-
- AbstractMetaEnumValue* enumValueA0 = enumA->values().first();
- QCOMPARE(enumValueA0->name(), QLatin1String("A0"));
- QCOMPARE(enumValueA0->value().value(), 0);
- QCOMPARE(enumValueA0->stringValue(), QString());
-
- AbstractMetaEnumValue* enumValueA1 = enumA->values().last();
- QCOMPARE(enumValueA1->name(), QLatin1String("A1"));
- QCOMPARE(enumValueA1->value().value(), 1);
- QCOMPARE(enumValueA1->stringValue(), QString());
-
- AbstractMetaEnum* enumB = globalEnums.last();
- QCOMPARE(enumB->typeEntry()->qualifiedCppName(), QLatin1String("EnumB"));
-
- AbstractMetaEnumValue* enumValueB0 = enumB->values().first();
- QCOMPARE(enumValueB0->name(), QLatin1String("B0"));
- QCOMPARE(enumValueB0->value().value(), 2);
- QCOMPARE(enumValueB0->stringValue(), QLatin1String("2"));
-
- AbstractMetaEnumValue* enumValueB1 = enumB->values().last();
- QCOMPARE(enumValueB1->name(), QLatin1String("B1"));
- QCOMPARE(enumValueB1->value().value(), 4);
- QCOMPARE(enumValueB1->stringValue(), QLatin1String("0x4"));
-}
-
-void TestEnum::testEnumValueFromNeighbourEnum()
-{
- const char* cppCode ="\
- namespace A {\n\
- enum EnumA { ValueA0, ValueA1 };\n\
- enum EnumB { ValueB0 = A::ValueA1, ValueB1 = ValueA0 };\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <namespace-type name='A'>\n\
- <enum-type name='EnumA'/>\n\
- <enum-type name='EnumB'/>\n\
- </namespace-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
- QCOMPARE(classes[0]->enums().count(), 2);
-
- AbstractMetaEnum* enumA = classes[0]->findEnum(QLatin1String("EnumA"));
- QVERIFY(enumA);
- QCOMPARE(enumA->typeEntry()->qualifiedCppName(), QLatin1String("A::EnumA"));
-
- AbstractMetaEnumValue* enumValueA0 = enumA->values().first();
- QCOMPARE(enumValueA0->name(), QLatin1String("ValueA0"));
- QCOMPARE(enumValueA0->value().value(), 0);
- QCOMPARE(enumValueA0->stringValue(), QString());
-
- AbstractMetaEnumValue* enumValueA1 = enumA->values().last();
- QCOMPARE(enumValueA1->name(), QLatin1String("ValueA1"));
- QCOMPARE(enumValueA1->value().value(), 1);
- QCOMPARE(enumValueA1->stringValue(), QString());
-
- AbstractMetaEnum* enumB = classes[0]->findEnum(QLatin1String("EnumB"));
- QVERIFY(enumB);
- QCOMPARE(enumB->typeEntry()->qualifiedCppName(), QLatin1String("A::EnumB"));
-
- AbstractMetaEnumValue* enumValueB0 = enumB->values().first();
- QCOMPARE(enumValueB0->name(), QLatin1String("ValueB0"));
- QCOMPARE(enumValueB0->value().value(), 1);
- QCOMPARE(enumValueB0->stringValue(), QLatin1String("A::ValueA1"));
-
- AbstractMetaEnumValue* enumValueB1 = enumB->values().last();
- QCOMPARE(enumValueB1->name(), QLatin1String("ValueB1"));
- QCOMPARE(enumValueB1->value().value(), 0);
- QCOMPARE(enumValueB1->stringValue(), QLatin1String("ValueA0"));
-}
-
-void TestEnum::testEnumValueFromExpression()
-{
- const char* cppCode ="\
- struct A {\n\
- enum EnumA : unsigned {\n\
- ValueA0 = 3u,\n\
- ValueA1 = ~3u,\n\
- ValueA2 = 0xffffffff,\n\
- ValueA3 = 0xf0,\n\
- ValueA4 = 8 |ValueA3,\n\
- ValueA5 = ValueA3|32,\n\
- ValueA6 = ValueA3 >> 1,\n\
- ValueA7 = ValueA3 << 1\n\
- };\n\
- enum EnumB : int {\n\
- ValueB0 = ~3,\n\
- };\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <value-type name='A'>\n\
- <enum-type name='EnumA'/>\n\
- <enum-type name='EnumB'/>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("A"));
- QVERIFY(classA);
-
- AbstractMetaEnum* enumA = classA->findEnum(QLatin1String("EnumA"));
- QVERIFY(enumA);
- QVERIFY(!enumA->isSigned());
- QCOMPARE(enumA->typeEntry()->qualifiedCppName(), QLatin1String("A::EnumA"));
-
- AbstractMetaEnumValue* valueA0 = enumA->values().at(0);
- QCOMPARE(valueA0->name(), QLatin1String("ValueA0"));
- QCOMPARE(valueA0->stringValue(), QLatin1String("3u"));
- QCOMPARE(valueA0->value().unsignedValue(), 3u);
-
- AbstractMetaEnumValue* valueA1 = enumA->values().at(1);
- QCOMPARE(valueA1->name(), QLatin1String("ValueA1"));
- QCOMPARE(valueA1->stringValue(), QLatin1String("~3u"));
- QCOMPARE(valueA1->value().unsignedValue(), ~3u);
-
- AbstractMetaEnumValue* valueA2 = enumA->values().at(2);
- QCOMPARE(valueA2->name(), QLatin1String("ValueA2"));
- QCOMPARE(valueA2->stringValue(), QLatin1String("0xffffffff"));
- QCOMPARE(valueA2->value().unsignedValue(), 0xffffffffu);
-
- AbstractMetaEnumValue* valueA3 = enumA->values().at(3);
- QCOMPARE(valueA3->name(), QLatin1String("ValueA3"));
- QCOMPARE(valueA3->stringValue(), QLatin1String("0xf0"));
- QCOMPARE(valueA3->value().unsignedValue(), 0xf0u);
-
- AbstractMetaEnumValue* valueA4 = enumA->values().at(4);
- QCOMPARE(valueA4->name(), QLatin1String("ValueA4"));
- QCOMPARE(valueA4->stringValue(), QLatin1String("8 |ValueA3"));
- QCOMPARE(valueA4->value().unsignedValue(), 8|0xf0u);
-
- AbstractMetaEnumValue* valueA5 = enumA->values().at(5);
- QCOMPARE(valueA5->name(), QLatin1String("ValueA5"));
- QCOMPARE(valueA5->stringValue(), QLatin1String("ValueA3|32"));
- QCOMPARE(valueA5->value().unsignedValue(), 0xf0u|32);
-
- AbstractMetaEnumValue* valueA6 = enumA->values().at(6);
- QCOMPARE(valueA6->name(), QLatin1String("ValueA6"));
- QCOMPARE(valueA6->stringValue(), QLatin1String("ValueA3 >> 1"));
- QCOMPARE(valueA6->value().unsignedValue(), 0xf0u >> 1);
-
- AbstractMetaEnumValue* valueA7 = enumA->values().at(7);
- QCOMPARE(valueA7->name(), QLatin1String("ValueA7"));
- QCOMPARE(valueA7->stringValue(), QLatin1String("ValueA3 << 1"));
- QCOMPARE(valueA7->value().unsignedValue(), 0xf0u << 1);
-
- const AbstractMetaEnum *enumB = classA->findEnum(QLatin1String("EnumB"));
- QVERIFY(enumB);
- QVERIFY(enumB->isSigned());
- QCOMPARE(enumB->typeEntry()->qualifiedCppName(), QLatin1String("A::EnumB"));
- QCOMPARE(enumB->values().size(), 1);
- const AbstractMetaEnumValue *valueB0 = enumB->values().at(0);
- QCOMPARE(valueB0->name(), QLatin1String("ValueB0"));
- QCOMPARE(valueB0->stringValue(), QLatin1String("~3"));
- QCOMPARE(valueB0->value().value(), ~3);
-}
-
-void TestEnum::testPrivateEnum()
-{
- const char* cppCode ="\
- class A {\n\
- private:\n\
- enum PrivateEnum { Priv0 = 0x0f, Priv1 = 0xf0 };\n\
- public:\n\
- enum PublicEnum { Pub0 = Priv0, Pub1 = A::Priv1 };\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <value-type name='A'>\n\
- <enum-type name='PublicEnum'/>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->enums().count(), 2);
-
- AbstractMetaEnum* privateEnum = classA->findEnum(QLatin1String("PrivateEnum"));
- QVERIFY(privateEnum);
- QVERIFY(privateEnum->isPrivate());
- QCOMPARE(privateEnum->typeEntry()->qualifiedCppName(), QLatin1String("A::PrivateEnum"));
-
- AbstractMetaEnum* publicEnum = classA->findEnum(QLatin1String("PublicEnum"));
- QVERIFY(publicEnum);
- QCOMPARE(publicEnum->typeEntry()->qualifiedCppName(), QLatin1String("A::PublicEnum"));
-
- AbstractMetaEnumValue* pub0 = publicEnum->values().first();
- QCOMPARE(pub0->name(), QLatin1String("Pub0"));
- QCOMPARE(pub0->value().value(), 0x0f);
- QCOMPARE(pub0->stringValue(), QLatin1String("Priv0"));
-
- AbstractMetaEnumValue* pub1 = publicEnum->values().last();
- QCOMPARE(pub1->name(), QLatin1String("Pub1"));
- QCOMPARE(pub1->value().value(), 0xf0);
- QCOMPARE(pub1->stringValue(), QLatin1String("A::Priv1"));
-}
-
-void TestEnum::testTypedefEnum()
-{
- const char* cppCode ="\
- typedef enum EnumA {\n\
- A0,\n\
- A1,\n\
- } EnumA;\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <enum-type name='EnumA'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaEnumList globalEnums = builder->globalEnums();
- QCOMPARE(globalEnums.count(), 1);
-
- AbstractMetaEnum* enumA = globalEnums.first();
- QCOMPARE(enumA->typeEntry()->qualifiedCppName(), QLatin1String("EnumA"));
-
- AbstractMetaEnumValue* enumValueA0 = enumA->values().first();
- QCOMPARE(enumValueA0->name(), QLatin1String("A0"));
- QCOMPARE(enumValueA0->value().value(), 0);
- QCOMPARE(enumValueA0->stringValue(), QLatin1String(""));
-
- AbstractMetaEnumValue* enumValueA1 = enumA->values().last();
- QCOMPARE(enumValueA1->name(), QLatin1String("A1"));
- QCOMPARE(enumValueA1->value().value(), 1);
- QCOMPARE(enumValueA1->stringValue(), QString());
-}
-
-QTEST_APPLESS_MAIN(TestEnum)
diff --git a/sources/shiboken2/ApiExtractor/tests/testenum.h b/sources/shiboken2/ApiExtractor/tests/testenum.h
deleted file mode 100644
index 312551763..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testenum.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTENUM_H
-#define TESTENUM_H
-#include <QObject>
-
-class TestEnum : public QObject
-{
- Q_OBJECT
-private slots:
- void testEnumCppSignature();
- void testEnumWithApiVersion();
- void testAnonymousEnum();
- void testGlobalEnums();
- void testEnumValueFromNeighbourEnum();
- void testEnumValueFromExpression();
- void testPrivateEnum();
- void testTypedefEnum();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testextrainclude.cpp b/sources/shiboken2/ApiExtractor/tests/testextrainclude.cpp
deleted file mode 100644
index 7e5664842..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testextrainclude.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testextrainclude.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestExtraInclude::testClassExtraInclude()
-{
- const char* cppCode ="struct A {};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'>\n\
- <extra-includes>\n\
- <include file-name='header.h' location='global'/>\n\
- </extra-includes>\n\
- </value-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
-
- QVector<Include> includes = classA->typeEntry()->extraIncludes();
- QCOMPARE(includes.count(), 1);
- QCOMPARE(includes.first().name(), QLatin1String("header.h"));
-}
-
-void TestExtraInclude::testGlobalExtraIncludes()
-{
- const char* cppCode ="struct A {};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <extra-includes>\n\
- <include file-name='header1.h' location='global'/>\n\
- <include file-name='header2.h' location='global'/>\n\
- </extra-includes>\n\
- <value-type name='A'/>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QVERIFY(AbstractMetaClass::findClass(classes, QLatin1String("A")));
-
- TypeDatabase* td = TypeDatabase::instance();
- const TypeSystemTypeEntry *module = td->defaultTypeSystemType();
- QVERIFY(module);
- QCOMPARE(module->name(), QLatin1String("Foo"));
-
- QVector<Include> includes = module->extraIncludes();
- QCOMPARE(includes.count(), 2);
- QCOMPARE(includes.first().name(), QLatin1String("header1.h"));
- QCOMPARE(includes.last().name(), QLatin1String("header2.h"));
-}
-
-QTEST_APPLESS_MAIN(TestExtraInclude)
diff --git a/sources/shiboken2/ApiExtractor/tests/testextrainclude.h b/sources/shiboken2/ApiExtractor/tests/testextrainclude.h
deleted file mode 100644
index 33c5377c7..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testextrainclude.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTEXTRAINCLUDE_H
-#define TESTEXTRAINCLUDE_H
-
-#include <QObject>
-
-class TestExtraInclude : public QObject
-{
- Q_OBJECT
- private slots:
- void testClassExtraInclude();
- void testGlobalExtraIncludes();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testfunctiontag.cpp b/sources/shiboken2/ApiExtractor/tests/testfunctiontag.cpp
deleted file mode 100644
index b9aee5824..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testfunctiontag.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testfunctiontag.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestFunctionTag::testFunctionTagForSpecificSignature()
-{
- const char cppCode[] = "void globalFunction(int); void globalFunction(float); void dummy();\n";
- const char xmlCode[] = "\
- <typesystem package=\"Foo\">\n\
- <primitive-type name='int'/>\n\
- <primitive-type name='float'/>\n\
- <function signature='globalFunction(int)'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- const TypeEntry *func = TypeDatabase::instance()->findType(QLatin1String("globalFunction"));
- QVERIFY(func);
- QCOMPARE(builder->globalFunctions().size(), 1);
-}
-
-void TestFunctionTag::testFunctionTagForAllSignatures()
-{
- const char cppCode[] = "void globalFunction(int); void globalFunction(float); void dummy();\n";
- const char xmlCode[] = "\
- <typesystem package=\"Foo\">\n\
- <primitive-type name='int'/>\n\
- <primitive-type name='float'/>\n\
- <function signature='globalFunction(int)'/>\n\
- <function signature='globalFunction(float)'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- const TypeEntry *func = TypeDatabase::instance()->findType(QLatin1String("globalFunction"));
- QVERIFY(func);
- QCOMPARE(builder->globalFunctions().size(), 2);
-}
-
-void TestFunctionTag::testRenameGlobalFunction()
-{
- const char* cppCode ="void global_function_with_ugly_name();\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <function signature='global_function_with_ugly_name()' rename='smooth'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- const TypeEntry *func = TypeDatabase::instance()->findType(QLatin1String("global_function_with_ugly_name"));
- QVERIFY(func);
-
- QCOMPARE(builder->globalFunctions().size(), 1);
- const AbstractMetaFunction* metaFunc = builder->globalFunctions().first();
-
- QVERIFY(metaFunc);
- QCOMPARE(metaFunc->modifications().size(), 1);
- QVERIFY(metaFunc->modifications().first().isRenameModifier());
- QCOMPARE(metaFunc->modifications().first().renamedTo(), QLatin1String("smooth"));
-
- QCOMPARE(metaFunc->name(), QLatin1String("smooth"));
- QCOMPARE(metaFunc->originalName(), QLatin1String("global_function_with_ugly_name"));
- QCOMPARE(metaFunc->minimalSignature(), QLatin1String("global_function_with_ugly_name()"));
-}
-
-QTEST_APPLESS_MAIN(TestFunctionTag)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testfunctiontag.h b/sources/shiboken2/ApiExtractor/tests/testfunctiontag.h
deleted file mode 100644
index d68499cd9..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testfunctiontag.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTFUNCTIONTAG_H
-#define TESTFUNCTIONTAG_H
-#include <QObject>
-
-class TestFunctionTag : public QObject
-{
- Q_OBJECT
-private slots:
- void testFunctionTagForSpecificSignature();
- void testFunctionTagForAllSignatures();
- void testRenameGlobalFunction();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testimplicitconversions.cpp b/sources/shiboken2/ApiExtractor/tests/testimplicitconversions.cpp
deleted file mode 100644
index 26fb148d5..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testimplicitconversions.cpp
+++ /dev/null
@@ -1,163 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testimplicitconversions.h"
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-#include <QtTest/QTest>
-
-void TestImplicitConversions::testWithPrivateCtors()
-{
- const char* cppCode ="\
- class B;\n\
- class C;\n\
- class A {\n\
- A(const B&);\n\
- public:\n\
- A(const C&);\n\
- };\n\
- class B {};\n\
- class C {};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'/>\n\
- <value-type name='B'/>\n\
- <value-type name='C'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 3);
-
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- const AbstractMetaClass *classC = AbstractMetaClass::findClass(classes, QLatin1String("C"));
- AbstractMetaFunctionList implicitConvs = classA->implicitConversions();
- QCOMPARE(implicitConvs.count(), 1);
- QCOMPARE(implicitConvs.first()->arguments().first()->type()->typeEntry(), classC->typeEntry());
-}
-
-void TestImplicitConversions::testWithModifiedVisibility()
-{
- const char* cppCode ="\
- class B;\n\
- class A {\n\
- public:\n\
- A(const B&);\n\
- };\n\
- class B {};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <value-type name='A'>\n\
- <modify-function signature='A(const B&amp;)'>\n\
- <access modifier='private'/>\n\
- </modify-function>\n\
- </value-type>\n\
- <value-type name='B'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- AbstractMetaFunctionList implicitConvs = classA->implicitConversions();
- QCOMPARE(implicitConvs.count(), 1);
- QCOMPARE(implicitConvs.first()->arguments().first()->type()->typeEntry(), classB->typeEntry());
-}
-
-
-void TestImplicitConversions::testWithAddedCtor()
-{
- const char* cppCode ="\
- class B;\n\
- class A {\n\
- public:\n\
- A(const B&);\n\
- };\n\
- class B {};\n\
- class C {};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <custom-type name='TARGETLANGTYPE'/>\n\
- <value-type name='A'>\n\
- <add-function signature='A(const C&amp;)'/>\n\
- </value-type>\n\
- <value-type name='B'>\n\
- <add-function signature='B(TARGETLANGTYPE*)'/>\n\
- </value-type>\n\
- <value-type name='C'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 3);
-
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- AbstractMetaFunctionList implicitConvs = classA->implicitConversions();
- QCOMPARE(implicitConvs.count(), 2);
-
- // Added constructors with custom types should never result in implicit converters.
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- implicitConvs = classB->implicitConversions();
- QCOMPARE(implicitConvs.count(), 0);
-}
-
-void TestImplicitConversions::testWithExternalConversionOperator()
-{
- const char* cppCode ="\
- class A {};\n\
- struct B {\n\
- operator A() const;\n\
- };\n";
- const char* xmlCode = "\n\
- <typesystem package='Foo'>\n\
- <value-type name='A'/>\n\
- <value-type name='B'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- AbstractMetaClass* classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- AbstractMetaFunctionList implicitConvs = classA->implicitConversions();
- QCOMPARE(implicitConvs.count(), 1);
- AbstractMetaFunctionList externalConvOps = classA->externalConversionOperators();
- QCOMPARE(externalConvOps.count(), 1);
-
- const AbstractMetaFunction *convOp = nullptr;
- for (const AbstractMetaFunction *func : classB->functions()) {
- if (func->isConversionOperator())
- convOp = func;
- }
- QVERIFY(convOp);
- QCOMPARE(implicitConvs.first(), convOp);
-}
-
-QTEST_APPLESS_MAIN(TestImplicitConversions)
diff --git a/sources/shiboken2/ApiExtractor/tests/testimplicitconversions.h b/sources/shiboken2/ApiExtractor/tests/testimplicitconversions.h
deleted file mode 100644
index da8ae4597..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testimplicitconversions.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTIMPLICITCONVERSIONS_H
-#define TESTIMPLICITCONVERSIONS_H
-
-#include <QObject>
-
-class AbstractMetaBuilder;
-
-class TestImplicitConversions : public QObject
-{
- Q_OBJECT
-private slots:
- void testWithPrivateCtors();
- void testWithModifiedVisibility();
- void testWithAddedCtor();
- void testWithExternalConversionOperator();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testinserttemplate.cpp b/sources/shiboken2/ApiExtractor/tests/testinserttemplate.cpp
deleted file mode 100644
index 2d1692ee9..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testinserttemplate.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testinserttemplate.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestInsertTemplate::testInsertTemplateOnClassInjectCode()
-{
- const char* cppCode ="struct A{};\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <template name='code_template'>\n\
- code template content\n\
- </template>\n\
- <value-type name='A'>\n\
- <inject-code class='native'>\n\
- <insert-template name='code_template'/>\n\
- </inject-code>\n\
- </value-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->typeEntry()->codeSnips().count(), 1);
- QString code = classA->typeEntry()->codeSnips().first().code();
- QVERIFY(code.contains(QLatin1String("code template content")));
-}
-
-void TestInsertTemplate::testInsertTemplateOnModuleInjectCode()
-{
- const char* cppCode ="";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <template name='code_template'>\n\
- code template content\n\
- </template>\n\
- <inject-code class='native'>\n\
- <insert-template name='code_template'/>\n\
- </inject-code>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QVERIFY(classes.isEmpty());
-
- const TypeSystemTypeEntry *module = TypeDatabase::instance()->defaultTypeSystemType();
- QVERIFY(module);
- QCOMPARE(module->name(), QLatin1String("Foo"));
- QVERIFY(module);
- QCOMPARE(module->codeSnips().count(), 1);
- QString code = module->codeSnips().first().code().trimmed();
- QVERIFY(code.contains(QLatin1String("code template content")));
-}
-
-QTEST_APPLESS_MAIN(TestInsertTemplate)
diff --git a/sources/shiboken2/ApiExtractor/tests/testinserttemplate.h b/sources/shiboken2/ApiExtractor/tests/testinserttemplate.h
deleted file mode 100644
index 99b171933..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testinserttemplate.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTINSERTTEMPLATE_H
-#define TESTINSERTTEMPLATE_H
-
-#include <QObject>
-
-class TestInsertTemplate : public QObject
-{
- Q_OBJECT
- private slots:
- void testInsertTemplateOnClassInjectCode();
- void testInsertTemplateOnModuleInjectCode();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.cpp b/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.cpp
deleted file mode 100644
index 6acac41d5..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testmodifydocumentation.h"
-
-#include <QCoreApplication>
-#include <QtCore/QTemporaryDir>
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-#include <qtdocparser.h>
-
-void TestModifyDocumentation::testModifyDocumentation()
-{
- const char* cppCode ="struct B { void b(); }; class A {};\n";
- const char xmlCode[] =
-R"(<typesystem package="Foo">
- <value-type name='B'>
- <modify-function signature='b()' remove='all'/>
- </value-type>
- <value-type name='A'>
- <modify-documentation xpath='description/brief'>&lt;brief>Modified Brief&lt;/brief></modify-documentation>
- <modify-documentation xpath='description/para[3]'>&lt;para>Some changed contents here&lt;/para></modify-documentation>
- </value-type>
-</typesystem>
-)";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("A"));
- QVERIFY(classA);
- DocModificationList docMods = classA->typeEntry()->docModifications();
- QCOMPARE(docMods.count(), 2);
- QCOMPARE(docMods[0].code().trimmed(), QLatin1String("<brief>Modified Brief</brief>"));
- QCOMPARE(docMods[0].signature(), QString());
- QCOMPARE(docMods[1].code().trimmed(), QLatin1String("<para>Some changed contents here</para>"));
- QCOMPARE(docMods[1].signature(), QString());
-
- // Create a temporary directory for the documentation file since libxml2
- // cannot handle Qt resources.
- QTemporaryDir tempDir(QDir::tempPath() + QLatin1String("/shiboken_testmodifydocXXXXXX"));
- QVERIFY2(tempDir.isValid(), qPrintable(tempDir.errorString()));
- const QString docFileName = QLatin1String("a.xml");
- QVERIFY(QFile::copy(QLatin1String(":/") + docFileName, tempDir.filePath(docFileName)));
-
- QtDocParser docParser;
- docParser.setDocumentationDataDirectory(tempDir.path());
- docParser.fillDocumentation(classA);
-
- const QString actualDocSimplified = classA->documentation().value().simplified();
- QVERIFY(!actualDocSimplified.isEmpty());
-
-const char expectedDoc[] =
-R"(<?xml version="1.0"?>
-<description>oi
-<brief>Modified Brief</brief>
-<para>Paragraph number 1</para>
-<para>Paragraph number 2</para>
-<para>Some changed contents here</para>
-</description>
-)";
- const QString expectedDocSimplified = QString::fromLatin1(expectedDoc).simplified();
- // Check whether the first modification worked.
- QVERIFY(actualDocSimplified.contains(QLatin1String("Modified Brief")));
-
-#ifndef HAVE_LIBXSLT
- // QtXmlPatterns is unable to handle para[3] in style sheets,
- // this only works in its XPath search.
- QEXPECT_FAIL("", "QtXmlPatterns cannot handle para[3] (QTBUG-66925)", Abort);
-#endif
- QCOMPARE(actualDocSimplified, expectedDocSimplified);
-}
-
-// We expand QTEST_MAIN macro but using QCoreApplication instead of QApplication
-// because this test needs an event loop but can't use QApplication to avoid a crash
-// on our ARMEL/FRAMANTLE buildbot
-int main(int argc, char** argv)
-{
- QCoreApplication app(argc, argv);
- TestModifyDocumentation tc;
- return QTest::qExec(&tc, argc, argv);
-}
diff --git a/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.h b/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.h
deleted file mode 100644
index 6428a5697..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTMODIFYDOCUMENTATION_H
-#define TESTMODIFYDOCUMENTATION_H
-
-#include <QObject>
-
-class TestModifyDocumentation : public QObject
-{
-Q_OBJECT
-private slots:
- void testModifyDocumentation();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.qrc b/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.qrc
deleted file mode 100644
index 76b1bfc61..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testmodifydocumentation.qrc
+++ /dev/null
@@ -1,5 +0,0 @@
-<RCC>
- <qresource>
- <file>a.xml</file>
- </qresource>
-</RCC>
diff --git a/sources/shiboken2/ApiExtractor/tests/testmodifyfunction.cpp b/sources/shiboken2/ApiExtractor/tests/testmodifyfunction.cpp
deleted file mode 100644
index 4fd4269f6..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testmodifyfunction.cpp
+++ /dev/null
@@ -1,466 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testmodifyfunction.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestModifyFunction::testRenameArgument_data()
-{
- QTest::addColumn<QByteArray>("pattern");
- QTest::newRow("fixed_string") << QByteArrayLiteral("method(int)");
- QTest::newRow("regular_expression") << QByteArrayLiteral("^method.*");
-}
-
-void TestModifyFunction::testRenameArgument()
-{
- QFETCH(QByteArray, pattern);
-
- const char* cppCode ="\
- struct A {\n\
- void method(int=0);\n\
- };\n";
- const char xmlCode1[] = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <object-type name='A'>\n\
- <modify-function signature='";
- const char xmlCode2[] = "'>\n\
- <modify-argument index='1'>\n\
- <rename to='otherArg'/>\n\
- </modify-argument>\n\
- </modify-function>\n\
- </object-type>\n\
- </typesystem>\n";
-
- const QByteArray xmlCode = QByteArray(xmlCode1) + pattern + QByteArray(xmlCode2);
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode.constData(), false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- const AbstractMetaFunction* func = classA->findFunction(QLatin1String("method"));
- Q_ASSERT(func);
-
- QCOMPARE(func->argumentName(1), QLatin1String("otherArg"));
-}
-
-void TestModifyFunction::testOwnershipTransfer()
-{
- const char* cppCode ="\
- struct A {};\n\
- struct B {\n\
- virtual A* method();\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <object-type name='A' />\n\
- <object-type name='B'>\n\
- <modify-function signature='method()'>\n\
- <modify-argument index='return'>\n\
- <define-ownership owner='c++'/>\n\
- </modify-argument>\n\
- </modify-function>\n\
- </object-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- const AbstractMetaFunction* func = classB->findFunction(QLatin1String("method"));
-
- QCOMPARE(func->ownership(func->ownerClass(), TypeSystem::TargetLangCode, 0), TypeSystem::CppOwnership);
-}
-
-
-void TestModifyFunction::invalidateAfterUse()
-{
- const char* cppCode ="\
- struct A {\n\
- virtual void call(int *a);\n\
- };\n\
- struct B : A {\n\
- };\n\
- struct C : B {\n\
- virtual void call2(int *a);\n\
- };\n\
- struct D : C {\n\
- virtual void call2(int *a);\n\
- };\n\
- struct E : D {\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='int'/>\n\
- <object-type name='A'>\n\
- <modify-function signature='call(int*)'>\n\
- <modify-argument index='1' invalidate-after-use='true'/>\n\
- </modify-function>\n\
- </object-type>\n\
- <object-type name='B' />\n\
- <object-type name='C'>\n\
- <modify-function signature='call2(int*)'>\n\
- <modify-argument index='1' invalidate-after-use='true'/>\n\
- </modify-function>\n\
- </object-type>\n\
- <object-type name='D'>\n\
- <modify-function signature='call2(int*)'>\n\
- <modify-argument index='1' invalidate-after-use='true'/>\n\
- </modify-function>\n\
- </object-type>\n\
- <object-type name='E' />\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- false, QLatin1String("0.1")));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- const AbstractMetaFunction* func = classB->findFunction(QLatin1String("call"));
- QCOMPARE(func->modifications().size(), 1);
- QCOMPARE(func->modifications().at(0).argument_mods.size(), 1);
- QVERIFY(func->modifications().at(0).argument_mods.at(0).resetAfterUse);
-
- const AbstractMetaClass *classC = AbstractMetaClass::findClass(classes, QLatin1String("C"));
- QVERIFY(classC);
- func = classC->findFunction(QLatin1String("call"));
- QCOMPARE(func->modifications().size(), 1);
- QCOMPARE(func->modifications().at(0).argument_mods.size(), 1);
- QVERIFY(func->modifications().at(0).argument_mods.at(0).resetAfterUse);
-
- func = classC->findFunction(QLatin1String("call2"));
- QCOMPARE(func->modifications().size(), 1);
- QCOMPARE(func->modifications().at(0).argument_mods.size(), 1);
- QVERIFY(func->modifications().at(0).argument_mods.at(0).resetAfterUse);
-
- const AbstractMetaClass *classD = AbstractMetaClass::findClass(classes, QLatin1String("D"));
- QVERIFY(classD);
- func = classD->findFunction(QLatin1String("call"));
- QCOMPARE(func->modifications().size(), 1);
- QCOMPARE(func->modifications().at(0).argument_mods.size(), 1);
- QVERIFY(func->modifications().at(0).argument_mods.at(0).resetAfterUse);
-
- func = classD->findFunction(QLatin1String("call2"));
- QCOMPARE(func->modifications().size(), 1);
- QCOMPARE(func->modifications().at(0).argument_mods.size(), 1);
- QVERIFY(func->modifications().at(0).argument_mods.at(0).resetAfterUse);
-
- const AbstractMetaClass *classE = AbstractMetaClass::findClass(classes, QLatin1String("E"));
- QVERIFY(classE);
- func = classE->findFunction(QLatin1String("call"));
- QVERIFY(func);
- QCOMPARE(func->modifications().size(), 1);
- QCOMPARE(func->modifications().at(0).argument_mods.size(), 1);
- QVERIFY(func->modifications().at(0).argument_mods.at(0).resetAfterUse);
-
- func = classE->findFunction(QLatin1String("call2"));
- QVERIFY(func);
- QCOMPARE(func->modifications().size(), 1);
- QCOMPARE(func->modifications().at(0).argument_mods.size(), 1);
- QVERIFY(func->modifications().at(0).argument_mods.at(0).resetAfterUse);
-}
-
-void TestModifyFunction::testWithApiVersion()
-{
- const char* cppCode ="\
- struct A {};\n\
- struct B {\n\
- virtual A* method();\n\
- virtual B* methodB();\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <object-type name='A' />\n\
- <object-type name='B'>\n\
- <modify-function signature='method()' since='0.1'>\n\
- <modify-argument index='return'>\n\
- <define-ownership owner='c++'/>\n\
- </modify-argument>\n\
- </modify-function>\n\
- <modify-function signature='methodB()' since='0.2'>\n\
- <modify-argument index='return'>\n\
- <define-ownership owner='c++'/>\n\
- </modify-argument>\n\
- </modify-function>\n\
- </object-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- false, QLatin1String("0.1")));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- AbstractMetaClass* classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- const AbstractMetaFunction* func = classB->findFunction(QLatin1String("method"));
-
- QCOMPARE(func->ownership(func->ownerClass(), TypeSystem::TargetLangCode, 0), TypeSystem::CppOwnership);
-
- func = classB->findFunction(QLatin1String("methodB"));
- QVERIFY(func->ownership(func->ownerClass(), TypeSystem::TargetLangCode, 0) != TypeSystem::CppOwnership);
-}
-
-// Modifications on class/typesystem level are tested below
-// in testScopedModifications().
-void TestModifyFunction::testAllowThread()
-{
- const char cppCode[] =R"CPP(\
-struct A {
- void f1();
- void f2();
- void f3();
- int getter1() const;
- int getter2() const;
-};
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <object-type name='A'>
- <modify-function signature='f2()' allow-thread='auto'/>
- <modify-function signature='f3()' allow-thread='no'/>
- <modify-function signature='getter2()const' allow-thread='yes'/>
- </object-type>
-</typesystem>
-)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- false, QLatin1String("0.1")));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
-
- // Nothing specified, true
- const AbstractMetaFunction *f1 = classA->findFunction(QLatin1String("f1"));
- QVERIFY(f1);
- QVERIFY(!f1->allowThread());
-
- // 'auto' specified, should be false for nontrivial function
- const AbstractMetaFunction *f2 = classA->findFunction(QLatin1String("f2"));
- QVERIFY(f2);
- QVERIFY(f2->allowThread());
-
- // 'no' specified, should be false
- const AbstractMetaFunction *f3 = classA->findFunction(QLatin1String("f3"));
- QVERIFY(f3);
- QVERIFY(!f3->allowThread());
-
- // Nothing specified, should be false for simple getter
- const AbstractMetaFunction *getter1 = classA->findFunction(QLatin1String("getter1"));
- QVERIFY(getter1);
- QVERIFY(!getter1->allowThread());
-
- // Forced to true simple getter
- const AbstractMetaFunction *getter2 = classA->findFunction(QLatin1String("getter2"));
- QVERIFY(getter2);
- QVERIFY(getter2->allowThread()); // Forced to true simple getter
-}
-
-void TestModifyFunction::testGlobalFunctionModification()
-{
- const char* cppCode ="\
- struct A {};\n\
- void function(A* a = 0);\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='A'/>\n\
- <function signature='function(A*)'>\n\
- <modify-function signature='function(A*)'>\n\
- <modify-argument index='1'>\n\
- <replace-type modified-type='A'/>\n\
- <replace-default-expression with='A()'/>\n\
- </modify-argument>\n\
- </modify-function>\n\
- </function>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- QCOMPARE(builder->globalFunctions().size(), 1);
-
- FunctionModificationList mods = TypeDatabase::instance()->functionModifications(QLatin1String("function(A*)"));
- QCOMPARE(mods.count(), 1);
- QVector<ArgumentModification> argMods = mods.first().argument_mods;
- QCOMPARE(argMods.count(), 1);
- ArgumentModification argMod = argMods.first();
- QCOMPARE(argMod.replacedDefaultExpression, QLatin1String("A()"));
-
- const AbstractMetaFunction* func = builder->globalFunctions().first();
- QVERIFY(func);
- QCOMPARE(func->arguments().count(), 1);
- const AbstractMetaArgument* arg = func->arguments().first();
- QCOMPARE(arg->type()->cppSignature(), QLatin1String("A *"));
- QCOMPARE(arg->originalDefaultValueExpression(), QLatin1String("0"));
- QCOMPARE(arg->defaultValueExpression(), QLatin1String("A()"));
-}
-
-// Tests modifications of exception handling and allow-thread
-// on various levels.
-void TestModifyFunction::testScopedModifications_data()
-{
- QTest::addColumn<QByteArray>("cppCode");
- QTest::addColumn<QByteArray>("xmlCode");
- QTest::addColumn<bool>("expectedGenerateUnspecified");
- QTest::addColumn<bool>("expectedGenerateNonThrowing");
- QTest::addColumn<bool>("expectedGenerateThrowing");
- QTest::addColumn<bool>("expectedAllowThread");
-
- const QByteArray cppCode = R"CPP(
-struct Base {
-};
-
-struct A : public Base {
- void unspecified();
- void nonThrowing() noexcept;
- void throwing() throw(int);
-};
-)CPP";
-
- // Default: Off
- QTest::newRow("none")
- << cppCode
- << QByteArray(R"XML(
-<typesystem package= 'Foo'>
- <primitive-type name='int'/>
- <object-type name='Base'/>
- <object-type name='A'/>
-</typesystem>)XML")
- << false << false << false // exception
- << false; // allowthread
-
- // Modify one function
- QTest::newRow("modify-function1")
- << cppCode
- << QByteArray(R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <object-type name='Base'/>
- <object-type name='A'>
- <modify-function signature='throwing()' exception-handling='auto-on'/>
- </object-type>
-</typesystem>)XML")
- << false << false << true // exception
- << false; // allowthread
-
- // Flip defaults by modifying functions
- QTest::newRow("modify-function2")
- << cppCode
- << QByteArray(R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <object-type name='Base'/>
- <object-type name='A'>
- <modify-function signature='unspecified()' exception-handling='auto-on'/>
- <modify-function signature='throwing()' exception-handling='off'/>
- </object-type>
-</typesystem>)XML")
- << true << false << false // exception
- << false; // allowthread
-
- // Activate on type system level
- QTest::newRow("typesystem-on")
- << cppCode
- << QByteArray(R"XML(
-<typesystem package='Foo' exception-handling='auto-on' allow-thread='no'>
- <primitive-type name='int'/>
- <object-type name='Base'/>
- <object-type name='A'/>
-</typesystem>)XML")
- << true << false << true // exception
- << false; // allowthread
-
- // Activate on class level
- QTest::newRow("class-on")
- << cppCode
- << QByteArray(R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <object-type name='Base'/>
- <object-type name='A' exception-handling='auto-on' allow-thread='no'/>
-</typesystem>)XML")
- << true << false << true // exception
- << false; // allowthread
-
- // Activate on base class level
- QTest::newRow("baseclass-on")
- << cppCode
- << QByteArray(R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <object-type name='Base' exception-handling='auto-on' allow-thread='no'/>
- <object-type name='A'/>
-</typesystem>)XML")
- << true << false << true // exception
- << false; // allowthread
-
- // Override value on class level
- QTest::newRow("override-class-on")
- << cppCode
- << QByteArray(R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <object-type name='Base'/>
- <object-type name='A' exception-handling='auto-on'>
- <modify-function signature='throwing()' exception-handling='no'/>
- </object-type>
-</typesystem>)XML")
- << true << false << false // exception
- << false; // allowthread
-}
-
-void TestModifyFunction::testScopedModifications()
-{
- QFETCH(QByteArray, cppCode);
- QFETCH(QByteArray, xmlCode);
- QFETCH(bool, expectedGenerateUnspecified);
- QFETCH(bool, expectedGenerateNonThrowing);
- QFETCH(bool, expectedGenerateThrowing);
- QFETCH(bool, expectedAllowThread);
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode.constData(), xmlCode.constData(), false));
- QVERIFY(!builder.isNull());
-
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(builder->classes(), QLatin1String("A"));
- QVERIFY(classA);
-
- const AbstractMetaFunction *f = classA->findFunction(QStringLiteral("unspecified"));
- QVERIFY(f);
- QCOMPARE(f->exceptionSpecification(), ExceptionSpecification::Unknown);
- QCOMPARE(f->generateExceptionHandling(), expectedGenerateUnspecified);
- QCOMPARE(f->allowThread(), expectedAllowThread);
-
- f = classA->findFunction(QStringLiteral("nonThrowing"));
- QVERIFY(f);
- QCOMPARE(f->exceptionSpecification(), ExceptionSpecification::NoExcept);
- QCOMPARE(f->generateExceptionHandling(), expectedGenerateNonThrowing);
-
- f = classA->findFunction(QStringLiteral("throwing"));
- QVERIFY(f);
- QCOMPARE(f->exceptionSpecification(), ExceptionSpecification::Throws);
- QCOMPARE(f->generateExceptionHandling(), expectedGenerateThrowing);
-}
-
-QTEST_APPLESS_MAIN(TestModifyFunction)
diff --git a/sources/shiboken2/ApiExtractor/tests/testmodifyfunction.h b/sources/shiboken2/ApiExtractor/tests/testmodifyfunction.h
deleted file mode 100644
index 375111e03..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testmodifyfunction.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTABSTRACTMETACLASS_H
-#define TESTABSTRACTMETACLASS_H
-
-#include <QObject>
-
-class TestModifyFunction : public QObject
-{
- Q_OBJECT
- private slots:
- void testOwnershipTransfer();
- void testWithApiVersion();
- void testAllowThread();
- void testRenameArgument_data();
- void testRenameArgument();
- void invalidateAfterUse();
- void testGlobalFunctionModification();
- void testScopedModifications_data();
- void testScopedModifications();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testmultipleinheritance.cpp b/sources/shiboken2/ApiExtractor/tests/testmultipleinheritance.cpp
deleted file mode 100644
index a4e506e8c..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testmultipleinheritance.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testmultipleinheritance.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestMultipleInheritance::testVirtualClass()
-{
- const char* cppCode ="\
- struct A {\n\
- virtual ~A();\n\
- virtual void theBug();\n\
- };\n\
- struct B {\n\
- virtual ~B();\n\
- };\n\
- struct C : A, B {\n\
- };\n\
- struct D : C {\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <object-type name='A' />\n\
- <object-type name='B' />\n\
- <object-type name='C' />\n\
- <object-type name='D' />\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 4);
-
- const AbstractMetaClass *classD = AbstractMetaClass::findClass(classes, QLatin1String("D"));
- bool functionFound = false;
- const AbstractMetaFunctionList &functions = classD->functions();
- for (AbstractMetaFunction *f : functions) {
- if (f->name() == QLatin1String("theBug")) {
- functionFound = true;
- break;
- }
- }
- QVERIFY(functionFound);
-
-}
-
-QTEST_APPLESS_MAIN(TestMultipleInheritance)
diff --git a/sources/shiboken2/ApiExtractor/tests/testmultipleinheritance.h b/sources/shiboken2/ApiExtractor/tests/testmultipleinheritance.h
deleted file mode 100644
index 5ee8a21ea..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testmultipleinheritance.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTMULTIPLEINHERITANCE_H
-#define TESTMULTIPLEINHERITANCE_H
-
-#include <QObject>
-
-class AbstractMetaBuilder;
-
-class TestMultipleInheritance : public QObject
-{
- Q_OBJECT
- private slots:
- void testVirtualClass();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testnamespace.cpp b/sources/shiboken2/ApiExtractor/tests/testnamespace.cpp
deleted file mode 100644
index e3aad6b50..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testnamespace.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testnamespace.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void NamespaceTest::testNamespaceMembers()
-{
- const char* cppCode = "\
- namespace Namespace\n\
- {\n\
- enum Option {\n\
- OpZero,\n\
- OpOne\n\
- };\n\
- void foo(Option opt);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <namespace-type name='Namespace'>\n\
- <enum-type name='Option' />\n\
- </namespace-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- AbstractMetaClass *ns = AbstractMetaClass::findClass(classes, QLatin1String("Namespace"));
- QVERIFY(ns);
- const AbstractMetaEnum* metaEnum = ns->findEnum(QLatin1String("Option"));
- QVERIFY(metaEnum);
- const AbstractMetaFunction* func = ns->findFunction(QLatin1String("foo"));
- QVERIFY(func);
-}
-
-void NamespaceTest::testNamespaceInnerClassMembers()
-{
- const char* cppCode = "\
- namespace OuterNamespace\n\
- {\n\
- namespace InnerNamespace {\n\
- struct SomeClass {\n\
- void method();\n\
- };\n\
- };\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <namespace-type name='OuterNamespace'>\n\
- <namespace-type name='InnerNamespace'>\n\
- <value-type name='SomeClass'/>\n\
- </namespace-type>\n\
- </namespace-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *ons = AbstractMetaClass::findClass(classes, QLatin1String("OuterNamespace"));
- QVERIFY(ons);
- const AbstractMetaClass *ins = AbstractMetaClass::findClass(classes, QLatin1String("OuterNamespace::InnerNamespace"));
- QVERIFY(ins);
- const AbstractMetaClass *sc = AbstractMetaClass::findClass(classes, QLatin1String("OuterNamespace::InnerNamespace::SomeClass"));
- QVERIFY(sc);
- const AbstractMetaFunction* meth = sc->findFunction(QLatin1String("method"));
- QVERIFY(meth);
-}
-
-QTEST_APPLESS_MAIN(NamespaceTest)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testnamespace.h b/sources/shiboken2/ApiExtractor/tests/testnamespace.h
deleted file mode 100644
index 5153a28a3..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testnamespace.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTNAMESPACE_H
-#define TESTNAMESPACE_H
-
-#include <QObject>
-
-// The class is named 'NamespaceTest' to avoid clashes with Qt COIN using
-// '-qtnamespace TestNamespace'.
-class NamespaceTest : public QObject
-{
- Q_OBJECT
- private slots:
- void testNamespaceMembers();
- void testNamespaceInnerClassMembers();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testnestedtypes.cpp b/sources/shiboken2/ApiExtractor/tests/testnestedtypes.cpp
deleted file mode 100644
index 10194eb34..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testnestedtypes.cpp
+++ /dev/null
@@ -1,128 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testnestedtypes.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestNestedTypes::testNestedTypesModifications()
-{
- const char* cppCode ="\
- namespace OuterNamespace {\n\
- namespace InnerNamespace {\n\
- struct SomeClass {\n\
- void method() {}\n\
- };\n\
- };\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <namespace-type name='OuterNamespace'>\n\
- <namespace-type name='InnerNamespace'>\n\
- <inject-code class='native'>custom_code1();</inject-code>\n\
- <add-function signature='method()' return-type='OuterNamespace::InnerNamespace::SomeClass'>\n\
- <inject-code class='target'>custom_code2();</inject-code>\n\
- </add-function>\n\
- <object-type name='SomeClass' target-lang-name='RenamedSomeClass'>\n\
- <modify-function signature='method()' remove='all'/>\n\
- </object-type>\n\
- </namespace-type>\n\
- </namespace-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
-
- const AbstractMetaClass *ons = AbstractMetaClass::findClass(classes, QLatin1String("OuterNamespace"));
- QVERIFY(ons);
-
- const AbstractMetaClass *ins = AbstractMetaClass::findClass(classes, QLatin1String("OuterNamespace::InnerNamespace"));
- QVERIFY(ins);
- QCOMPARE(ins->functions().count(), 1);
- QCOMPARE(ins->typeEntry()->codeSnips().count(), 1);
- CodeSnip snip = ins->typeEntry()->codeSnips().first();
- QCOMPARE(snip.code(), QLatin1String("custom_code1();"));
-
- AbstractMetaFunction* addedFunc = ins->functions().first();
- QVERIFY(addedFunc->isUserAdded());
- QCOMPARE(addedFunc->visibility(), AbstractMetaFunction::Public);
- QCOMPARE(addedFunc->functionType(), AbstractMetaFunction::NormalFunction);
- QCOMPARE(addedFunc->type()->minimalSignature(), QLatin1String("OuterNamespace::InnerNamespace::SomeClass"));
-
- QCOMPARE(addedFunc->modifications().size(), 1);
- QVERIFY(addedFunc->modifications().first().isCodeInjection());
- snip = addedFunc->modifications().first().snips.first();
- QCOMPARE(snip.code(), QLatin1String("custom_code2();"));
-
- const AbstractMetaClass *sc = AbstractMetaClass::findClass(classes, QLatin1String("OuterNamespace::InnerNamespace::SomeClass"));
- QVERIFY(ins);
- QCOMPARE(sc->functions().count(), 2); // default constructor and removed method
- AbstractMetaFunction* removedFunc = sc->functions().last();
- QVERIFY(removedFunc->isModifiedRemoved());
-}
-
-
-void TestNestedTypes::testDuplicationOfNestedTypes()
-{
- const char* cppCode ="\
- namespace Namespace {\n\
- class SomeClass {};\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <namespace-type name='Namespace'>\n\
- <value-type name='SomeClass'>\n\
- <add-function signature='createSomeClass(Namespace::SomeClass)'/>\n\
- </value-type>\n\
- </namespace-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 2);
- const AbstractMetaClass *nspace = AbstractMetaClass::findClass(classes, QLatin1String("Namespace"));
- QVERIFY(nspace);
- const AbstractMetaClass *cls1 = AbstractMetaClass::findClass(classes, QLatin1String("SomeClass"));
- QVERIFY(cls1);
- const AbstractMetaClass *cls2 = AbstractMetaClass::findClass(classes, QLatin1String("Namespace::SomeClass"));
- QVERIFY(cls2);
- QCOMPARE(cls1, cls2);
- QCOMPARE(cls1->name(), QLatin1String("SomeClass"));
- QCOMPARE(cls1->qualifiedCppName(), QLatin1String("Namespace::SomeClass"));
-
- TypeEntry* t1 = TypeDatabase::instance()->findType(QLatin1String("Namespace::SomeClass"));
- QVERIFY(t1);
- TypeEntry* t2 = TypeDatabase::instance()->findType(QLatin1String("SomeClass"));
- QVERIFY(!t2);
-}
-
-QTEST_APPLESS_MAIN(TestNestedTypes)
diff --git a/sources/shiboken2/ApiExtractor/tests/testnestedtypes.h b/sources/shiboken2/ApiExtractor/tests/testnestedtypes.h
deleted file mode 100644
index a870511ff..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testnestedtypes.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTNESTEDTYPES_H
-#define TESTNESTEDTYPES_H
-#include <QObject>
-
-class TestNestedTypes : public QObject
-{
- Q_OBJECT
-private slots:
- void testNestedTypesModifications();
- void testDuplicationOfNestedTypes();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testnumericaltypedef.cpp b/sources/shiboken2/ApiExtractor/tests/testnumericaltypedef.cpp
deleted file mode 100644
index 4f0b0e10f..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testnumericaltypedef.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testnumericaltypedef.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestNumericalTypedef::testNumericalTypedef()
-{
- const char* cppCode ="\
- typedef double real;\n\
- void funcDouble(double);\n\
- void funcReal(real);\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='double'/>\n\
- <primitive-type name='real'/>\n\
- <function signature='funcDouble(double)'/>\n\
- <function signature='funcReal(real)'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- QCOMPARE(builder->globalFunctions().size(), 2);
- const AbstractMetaFunction* funcDouble = builder->globalFunctions().first();
- QVERIFY(funcDouble);
- const AbstractMetaFunction* funcReal = builder->globalFunctions().last();
- QVERIFY(funcReal);
-
- if (funcDouble->name() == QLatin1String("funcReal"))
- std::swap(funcDouble, funcReal);
-
- QCOMPARE(funcDouble->minimalSignature(), QLatin1String("funcDouble(double)"));
- QCOMPARE(funcReal->minimalSignature(), QLatin1String("funcReal(real)"));
-
- const AbstractMetaType* doubleType = funcDouble->arguments().first()->type();
- QVERIFY(doubleType);
- QCOMPARE(doubleType->cppSignature(), QLatin1String("double"));
- QVERIFY(doubleType->isPrimitive());
- QVERIFY(doubleType->typeEntry()->isCppPrimitive());
-
- const AbstractMetaType* realType = funcReal->arguments().first()->type();
- QVERIFY(realType);
- QCOMPARE(realType->cppSignature(), QLatin1String("real"));
- QVERIFY(realType->isPrimitive());
- QVERIFY(realType->typeEntry()->isCppPrimitive());
-}
-
-void TestNumericalTypedef::testUnsignedNumericalTypedef()
-{
- const char* cppCode ="\
- typedef unsigned short ushort;\n\
- void funcUnsignedShort(unsigned short);\n\
- void funcUShort(ushort);\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='short'/>\n\
- <primitive-type name='unsigned short'/>\n\
- <primitive-type name='ushort'/>\n\
- <function signature='funcUnsignedShort(unsigned short)'/>\n\
- <function signature='funcUShort(ushort)'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- QCOMPARE(builder->globalFunctions().size(), 2);
- const AbstractMetaFunction* funcUnsignedShort = builder->globalFunctions().first();
- QVERIFY(funcUnsignedShort);
- const AbstractMetaFunction* funcUShort = builder->globalFunctions().last();
- QVERIFY(funcUShort);
-
- if (funcUnsignedShort->name() == QLatin1String("funcUShort"))
- std::swap(funcUnsignedShort, funcUShort);
-
- QCOMPARE(funcUnsignedShort->minimalSignature(), QLatin1String("funcUnsignedShort(unsigned short)"));
- QCOMPARE(funcUShort->minimalSignature(), QLatin1String("funcUShort(ushort)"));
-
- const AbstractMetaType* unsignedShortType = funcUnsignedShort->arguments().first()->type();
- QVERIFY(unsignedShortType);
- QCOMPARE(unsignedShortType->cppSignature(), QLatin1String("unsigned short"));
- QVERIFY(unsignedShortType->isPrimitive());
- QVERIFY(unsignedShortType->typeEntry()->isCppPrimitive());
-
- const AbstractMetaType* ushortType = funcUShort->arguments().first()->type();
- QVERIFY(ushortType);
- QCOMPARE(ushortType->cppSignature(), QLatin1String("ushort"));
- QVERIFY(ushortType->isPrimitive());
- QVERIFY(ushortType->typeEntry()->isCppPrimitive());
-}
-
-QTEST_APPLESS_MAIN(TestNumericalTypedef)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testnumericaltypedef.h b/sources/shiboken2/ApiExtractor/tests/testnumericaltypedef.h
deleted file mode 100644
index e4e051077..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testnumericaltypedef.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTNUMERICALTYPEDEF_H
-#define TESTNUMERICALTYPEDEF_H
-
-#include <QObject>
-
-class TestNumericalTypedef : public QObject
-{
- Q_OBJECT
- private slots:
- void testNumericalTypedef();
- void testUnsignedNumericalTypedef();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testprimitivetypetag.cpp b/sources/shiboken2/ApiExtractor/tests/testprimitivetypetag.cpp
deleted file mode 100644
index e78f9f274..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testprimitivetypetag.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testprimitivetypetag.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestPrimitiveTypeTag::testPrimitiveTypeDefaultConstructor()
-{
- const char* cppCode ="\
- struct A {};\n\
- struct B {};\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <primitive-type name='A' default-constructor='A()'/>\n\
- <object-type name='B'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
-
- PrimitiveTypeEntry* typeEntry = TypeDatabase::instance()->findPrimitiveType(QLatin1String("A"));
- QVERIFY(typeEntry);
- QVERIFY(typeEntry->hasDefaultConstructor());
- QCOMPARE(typeEntry->defaultConstructor(), QLatin1String("A()"));
-}
-
-QTEST_APPLESS_MAIN(TestPrimitiveTypeTag)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testprimitivetypetag.h b/sources/shiboken2/ApiExtractor/tests/testprimitivetypetag.h
deleted file mode 100644
index ee5f5159f..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testprimitivetypetag.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTPRIMITIVETYPETAG_H
-#define TESTPRIMITIVETYPETAG_H
-
-#include <QObject>
-
-class TestPrimitiveTypeTag : public QObject
-{
- Q_OBJECT
- private slots:
- void testPrimitiveTypeDefaultConstructor();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testrefcounttag.cpp b/sources/shiboken2/ApiExtractor/tests/testrefcounttag.cpp
deleted file mode 100644
index 38099c455..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testrefcounttag.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testrefcounttag.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestRefCountTag::testReferenceCountTag()
-{
- const char* cppCode ="\
- struct A {};\n\
- struct B {\n\
- void keepObject(B* b);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <object-type name='A'/>\n\
- <object-type name='B'>\n\
- <modify-function signature='keepObject(B*)'>\n\
- <modify-argument index='1'>\n\
- <reference-count action='add'/>\n\
- </modify-argument>\n\
- </modify-function>\n\
- </object-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- const AbstractMetaFunction* func = classB->findFunction(QLatin1String("keepObject"));
- QVERIFY(func);
- ReferenceCount refCount = func->modifications().first().argument_mods.first().referenceCounts.first();
- QCOMPARE(refCount.action, ReferenceCount::Add);
-}
-
-void TestRefCountTag::testWithApiVersion()
-{
- const char* cppCode ="\
- struct A {};\n\
- struct B {\n\
- void keepObject(B*, B*);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <object-type name='A'/>\n\
- <object-type name='B'>\n\
- <modify-function signature='keepObject(B*, B*)'>\n\
- <modify-argument index='1' since='0.1'>\n\
- <reference-count action='add'/>\n\
- </modify-argument>\n\
- <modify-argument index='2' since='0.2'>\n\
- <reference-count action='add'/>\n\
- </modify-argument>\n\
- </modify-function>\n\
- </object-type>\n\
- </typesystem>\n";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode,
- false, QLatin1String("0.1")));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- const AbstractMetaFunction* func = classB->findFunction(QLatin1String("keepObject"));
- QVERIFY(func);
- ReferenceCount refCount = func->modifications().first().argument_mods.first().referenceCounts.first();
- QCOMPARE(refCount.action, ReferenceCount::Add);
-
- QCOMPARE(func->modifications().size(), 1);
-}
-
-
-QTEST_APPLESS_MAIN(TestRefCountTag)
-
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testrefcounttag.h b/sources/shiboken2/ApiExtractor/tests/testrefcounttag.h
deleted file mode 100644
index 4acbddcfc..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testrefcounttag.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTREFCOUNTTAG_H
-#define TESTREFCOUNTTAG_H
-
-#include <QObject>
-
-class TestRefCountTag : public QObject
-{
- Q_OBJECT
- private slots:
- void testReferenceCountTag();
- void testWithApiVersion();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testreferencetopointer.cpp b/sources/shiboken2/ApiExtractor/tests/testreferencetopointer.cpp
deleted file mode 100644
index c7b4abe9a..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testreferencetopointer.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testreferencetopointer.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestReferenceToPointer::testReferenceToPointerArgument()
-{
- const char* cppCode ="\
- struct A {};\n\
- struct B {\n\
- void dummy(A*&);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <object-type name='A'/>\n\
- <object-type name='B'/>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
- const AbstractMetaFunction* func = classB->findFunction(QLatin1String("dummy"));
- QVERIFY(func);
- QCOMPARE(func->arguments().first()->type()->minimalSignature(), QLatin1String("A*&"));
-}
-
-QTEST_APPLESS_MAIN(TestReferenceToPointer)
-
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testreferencetopointer.h b/sources/shiboken2/ApiExtractor/tests/testreferencetopointer.h
deleted file mode 100644
index 0f717b55d..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testreferencetopointer.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTREFERENCETOPOINTER_H
-#define TESTREFERENCETOPOINTER_H
-
-#include <QObject>
-
-class TestReferenceToPointer : public QObject
-{
- Q_OBJECT
- private slots:
- void testReferenceToPointerArgument();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testremovefield.cpp b/sources/shiboken2/ApiExtractor/tests/testremovefield.cpp
deleted file mode 100644
index b586fd711..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testremovefield.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testremovefield.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestRemoveField::testRemoveField()
-{
- const char* cppCode ="\
- struct A {\n\
- int fieldA;\n\
- int fieldB;\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <primitive-type name='int'/>\n\
- <value-type name='A'>\n\
- <modify-field name='fieldB' remove='all'/>\n\
- </value-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->fields().size(), 1);
- const AbstractMetaField* fieldA = classA->fields().first();
- QVERIFY(fieldA);
- QCOMPARE(fieldA->name(), QLatin1String("fieldA"));
-}
-
-QTEST_APPLESS_MAIN(TestRemoveField)
-
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testremovefield.h b/sources/shiboken2/ApiExtractor/tests/testremovefield.h
deleted file mode 100644
index 8b52cc32f..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testremovefield.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTREMOVEFIELD_H
-#define TESTREMOVEFIELD_H
-
-#include <QObject>
-
-class TestRemoveField : public QObject
-{
- Q_OBJECT
- private slots:
- void testRemoveField();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testremoveimplconv.cpp b/sources/shiboken2/ApiExtractor/tests/testremoveimplconv.cpp
deleted file mode 100644
index 96090d1cc..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testremoveimplconv.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testremoveimplconv.h"
-#include "testutil.h"
-#include <QtTest/QTest>
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-// When a constructor able to trigger implicity conversions is removed
-// it should not appear in the implicity conversion list.
-void TestRemoveImplConv::testRemoveImplConv()
-{
- const char* cppCode ="\
- struct A {};\n\
- struct B {};\n\
- struct C {\n\
- C(const A&);\n\
- C(const B&);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package=\"Foo\">\n\
- <value-type name='A'/>\n\
- <value-type name='B'/>\n\
- <value-type name='C'>\n\
- <modify-function signature='C(const A&amp;)' remove='all'/>\n\
- </value-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 3);
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
- const AbstractMetaClass *classC = AbstractMetaClass::findClass(classes, QLatin1String("C"));
- QVERIFY(classC);
- AbstractMetaFunctionList implConv = classC->implicitConversions();
- QCOMPARE(implConv.count(), 1);
- QCOMPARE(implConv.first()->arguments().first()->type()->typeEntry(), classB->typeEntry());
-}
-
-QTEST_APPLESS_MAIN(TestRemoveImplConv)
diff --git a/sources/shiboken2/ApiExtractor/tests/testremoveimplconv.h b/sources/shiboken2/ApiExtractor/tests/testremoveimplconv.h
deleted file mode 100644
index 9e96dc2e9..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testremoveimplconv.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTREMOVEIMPLCONV_H
-#define TESTREMOVEIMPLCONV_H
-
-#include <QObject>
-
-class TestRemoveImplConv : public QObject
-{
-Q_OBJECT
-private slots:
- void testRemoveImplConv();
-};
-
-#endif // TESTREMOVEIMPLCONV_H
diff --git a/sources/shiboken2/ApiExtractor/tests/testremoveoperatormethod.cpp b/sources/shiboken2/ApiExtractor/tests/testremoveoperatormethod.cpp
deleted file mode 100644
index a6d28ccf5..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testremoveoperatormethod.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testremoveoperatormethod.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestRemoveOperatorMethod::testRemoveOperatorMethod()
-{
- const char* cppCode ="\
- #include <stdint.h>\n\
- \n\
- struct Char {};\n\
- struct ByteArray {};\n\
- struct String {};\n\
- \n\
- struct A {\n\
- A& operator>>(char&);\n\
- A& operator>>(char*);\n\
- A& operator>>(short&);\n\
- A& operator>>(unsigned short&);\n\
- A& operator>>(int&);\n\
- A& operator>>(unsigned int&);\n\
- A& operator>>(int64_t&);\n\
- A& operator>>(uint64_t&);\n\
- A& operator>>(float&);\n\
- A& operator>>(double&);\n\
- A& operator>>(Char&);\n\
- A& operator>>(ByteArray&);\n\
- A& operator>>(String&);\n\
- };\n";
- const char* xmlCode = "\
- <typesystem package='Foo'>\n\
- <primitive-type name='char'/>\n\
- <primitive-type name='short'/>\n\
- <primitive-type name='unsigned short'/>\n\
- <primitive-type name='int'/>\n\
- <primitive-type name='unsigned int'/>\n\
- <primitive-type name='int64_t'/>\n\
- <primitive-type name='uint64_t'/>\n\
- <primitive-type name='float'/>\n\
- <primitive-type name='double'/>\n\
- <primitive-type name='Char'/>\n\
- <primitive-type name='String'/>\n\
- <value-type name='ByteArray'/>\n\
- <object-type name='A'>\n\
- <modify-function signature='operator&gt;&gt;(char&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(char*)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(short&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(unsigned short&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(int&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(unsigned int&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(int64_t&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(uint64_t&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(float&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(double&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(Char&amp;)' remove='all'/>\n\
- <modify-function signature='operator&gt;&gt;(String&amp;)' remove='all'/>\n\
- </object-type>\n\
- </typesystem>\n";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->functions().size(), 14);
- QStringList removedSignatures;
- removedSignatures.append(QLatin1String("operator>>(char&)"));
- removedSignatures.append(QLatin1String("operator>>(char*)"));
- removedSignatures.append(QLatin1String("operator>>(short&)"));
- removedSignatures.append(QLatin1String("operator>>(unsigned short&)"));
- removedSignatures.append(QLatin1String("operator>>(int&)"));
- removedSignatures.append(QLatin1String("operator>>(unsigned int&)"));
- removedSignatures.append(QLatin1String("operator>>(int64_t&)"));
- removedSignatures.append(QLatin1String("operator>>(uint64_t&)"));
- removedSignatures.append(QLatin1String("operator>>(float&)"));
- removedSignatures.append(QLatin1String("operator>>(double&)"));
- removedSignatures.append(QLatin1String("operator>>(Char&)"));
- removedSignatures.append(QLatin1String("operator>>(String&)"));
- int notRemoved = classA->functions().size();
- const AbstractMetaFunctionList &functions = classA->functions();
- for (const AbstractMetaFunction *f : functions) {
- QCOMPARE(f->isModifiedRemoved(), bool(removedSignatures.contains(f->minimalSignature())));
- notRemoved -= int(f->isModifiedRemoved());
- }
- QCOMPARE(notRemoved, 2);
-}
-
-QTEST_APPLESS_MAIN(TestRemoveOperatorMethod)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testremoveoperatormethod.h b/sources/shiboken2/ApiExtractor/tests/testremoveoperatormethod.h
deleted file mode 100644
index 23c3e5144..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testremoveoperatormethod.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTREMOVEOPERATORMETHOD_H
-#define TESTREMOVEOPERATORMETHOD_H
-
-#include <QObject>
-
-class TestRemoveOperatorMethod : public QObject
-{
- Q_OBJECT
- private slots:
- void testRemoveOperatorMethod();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testresolvetype.cpp b/sources/shiboken2/ApiExtractor/tests/testresolvetype.cpp
deleted file mode 100644
index 2203f3648..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testresolvetype.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testresolvetype.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestResolveType::testResolveReturnTypeFromParentScope()
-{
- const char* cppCode = "\n\
- namespace A {\n\
- struct B {\n\
- struct C {};\n\
- };\n\
- struct D : public B::C {\n\
- C* foo = 0;\n\
- C* method();\n\
- };\n\
- };";
- const char* xmlCode = R"XML(
- <typesystem package='Foo'>
- <namespace-type name='A'>
- <value-type name='B'>
- <value-type name='C'/>
- </value-type>
- <value-type name='D'/>
- </namespace-type>
- </typesystem>)XML";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classD = AbstractMetaClass::findClass(classes, QLatin1String("A::D"));
- QVERIFY(classD);
- const AbstractMetaFunction* meth = classD->findFunction(QLatin1String("method"));
- QVERIFY(meth);
-}
-
-QTEST_APPLESS_MAIN(TestResolveType)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testresolvetype.h b/sources/shiboken2/ApiExtractor/tests/testresolvetype.h
deleted file mode 100644
index 62c08bcd7..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testresolvetype.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTRESOLVETYPE_H
-#define TESTRESOLVETYPE_H
-
-#include <QObject>
-
-class TestResolveType : public QObject
-{
- Q_OBJECT
- private slots:
- void testResolveReturnTypeFromParentScope();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testreverseoperators.cpp b/sources/shiboken2/ApiExtractor/tests/testreverseoperators.cpp
deleted file mode 100644
index dc4801e18..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testreverseoperators.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testreverseoperators.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestReverseOperators::testReverseSum()
-{
- const char cppCode[] = "struct A {\n\
- A& operator+(int);\n\
- };\n\
- A& operator+(int, const A&);";
- const char xmlCode[] = "\n\
- <typesystem package=\"Foo\">\n\
- <primitive-type name='int' />\n\
- <value-type name='A' />\n\
- </typesystem>";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- AbstractMetaClass* classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->functions().count(), 4);
-
- const AbstractMetaFunction* reverseOp = nullptr;
- const AbstractMetaFunction* normalOp = 0;
- for (const AbstractMetaFunction *func : classA->functions()) {
- if (func->name() == QLatin1String("operator+")) {
- if (func->isReverseOperator())
- reverseOp = func;
- else
- normalOp = func;
- }
- }
-
- QVERIFY(normalOp);
- QVERIFY(!normalOp->isReverseOperator());
- QCOMPARE(normalOp->arguments().count(), 1);
- QVERIFY(reverseOp);
- QVERIFY(reverseOp->isReverseOperator());
- QCOMPARE(reverseOp->arguments().count(), 1);
-}
-
-void TestReverseOperators::testReverseSumWithAmbiguity()
-{
- const char cppCode[] = "\n\
- struct A { A operator+(int); };\n\
- A operator+(int, const A&);\n\
- struct B {};\n\
- B operator+(const A&, const B&);\n\
- B operator+(const B&, const A&);\n\
- int operator-(int, const A*);\n\
- int operator/(const A*, int);\n\
- ";
- const char xmlCode[] = "\n\
- <typesystem package=\"Foo\">\n\
- <primitive-type name='int' />\n\
- <value-type name='A' />\n\
- <value-type name='B' />\n\
- </typesystem>";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QEXPECT_FAIL("", "Clang: Does not compile", Abort);
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QCOMPARE(classA->functions().count(), 6);
-
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
- QCOMPARE(classB->functions().count(), 4);
-
- const AbstractMetaFunction *reverseOp = nullptr;
- const AbstractMetaFunction *normalOp = nullptr;
- for (const AbstractMetaFunction *func : classB->functions()) {
- if (func->name() == QLatin1String("operator+")) {
- if (func->isReverseOperator())
- reverseOp = func;
- else
- normalOp = func;
- }
- }
- QVERIFY(normalOp);
- QVERIFY(!normalOp->isReverseOperator());
- QCOMPARE(normalOp->arguments().count(), 1);
- QCOMPARE(normalOp->minimalSignature(), QLatin1String("operator+(B,A)"));
- QVERIFY(reverseOp);
- QVERIFY(reverseOp->isReverseOperator());
- QCOMPARE(reverseOp->arguments().count(), 1);
- QCOMPARE(reverseOp->minimalSignature(), QLatin1String("operator+(A,B)"));
-
- reverseOp = classA->findFunction(QLatin1String("operator-"));
- QVERIFY(reverseOp);
- QCOMPARE(reverseOp->arguments().count(), 1);
- QVERIFY(reverseOp->isPointerOperator());
- QVERIFY(reverseOp->isReverseOperator());
-
- normalOp = classA->findFunction(QLatin1String("operator/"));
- QVERIFY(normalOp);
- QCOMPARE(normalOp->arguments().count(), 1);
- QVERIFY(normalOp->isPointerOperator());
- QVERIFY(!normalOp->isReverseOperator());
-
-}
-
-
-
-QTEST_APPLESS_MAIN(TestReverseOperators)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testreverseoperators.h b/sources/shiboken2/ApiExtractor/tests/testreverseoperators.h
deleted file mode 100644
index ba3b43cfb..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testreverseoperators.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTREVERSEOPERATORS_H
-#define TESTREVERSEOPERATORS_H
-#include <QObject>
-
-class TestReverseOperators : public QObject
-{
- Q_OBJECT
-private slots:
- void testReverseSum();
- void testReverseSumWithAmbiguity();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testtemplates.cpp b/sources/shiboken2/ApiExtractor/tests/testtemplates.cpp
deleted file mode 100644
index ec3ddb8b2..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testtemplates.cpp
+++ /dev/null
@@ -1,644 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testtemplates.h"
-#include <QtTest/QTest>
-#include <QtCore/QTextStream>
-#include <QTemporaryFile>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestTemplates::testTemplateWithNamespace()
-{
- const char cppCode[] = R"CPP(
-template<typename T> struct QList {};
-struct Url {
- void name();
-};
-namespace Internet {
- struct Url{};
- struct Bookmarks {
- QList<Url> list();
- };
-};
-)CPP";
-
- const char xmlCode0[] = R"XML(
-<typesystem package='Package.Network'>
- <value-type name='Url'/>
-</typesystem>)XML";
-
- QTemporaryFile file;
- QVERIFY(file.open());
- file.write(xmlCode0);
- file.close();
-
- QString xmlCode1 = QString::fromLatin1(R"XML(
-<typesystem package='Package.Internet'>
- <load-typesystem name='%1' generate='no'/>
- <container-type name='QList' type='list'/>
- <namespace-type name='Internet' generate='no'>
- <value-type name='Url'/>
- <value-type name='Bookmarks'/>
- </namespace-type>
-</typesystem>)XML").arg(file.fileName());
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, qPrintable(xmlCode1), false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
-
- AbstractMetaClass* classB = AbstractMetaClass::findClass(classes, QLatin1String("Bookmarks"));
- QVERIFY(classB);
- const AbstractMetaFunction* func = classB->findFunction(QLatin1String("list"));
- AbstractMetaType* funcType = func->type();
- QVERIFY(funcType);
- QCOMPARE(funcType->cppSignature(), QLatin1String("QList<Internet::Url >"));
-}
-
-void TestTemplates::testTemplateOnContainers()
-{
- const char cppCode[] = R"CPP(
-struct Base {};
-template<typename T> struct QList {};
-namespace Namespace {
- enum SomeEnum { E1, E2 };
- template<SomeEnum type> struct A {
- A<type> foo(const QList<A<type> >& a);
- };
- typedef A<E1> B;
-}
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package="Package">
- <container-type name='QList' type='list'/>
- <namespace-type name='Namespace'>
- <enum-type name='SomeEnum'/>
- <object-type name='A' generate='no'/>
- <object-type name='B'/>
- </namespace-type>
- <object-type name='Base'/>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
-
- AbstractMetaClass* classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
- QVERIFY(!classB->baseClass());
- QVERIFY(classB->baseClassName().isEmpty());
- const AbstractMetaFunction* func = classB->findFunction(QLatin1String("foo"));
- AbstractMetaType* argType = func->arguments().first()->type();
- QCOMPARE(argType->instantiations().count(), 1);
- QCOMPARE(argType->typeEntry()->qualifiedCppName(), QLatin1String("QList"));
-
- const AbstractMetaType* instance1 = argType->instantiations().first();
- QCOMPARE(instance1->instantiations().count(), 1);
- QCOMPARE(instance1->typeEntry()->qualifiedCppName(), QLatin1String("Namespace::A"));
-
- const AbstractMetaType* instance2 = instance1->instantiations().first();
- QCOMPARE(instance2->instantiations().count(), 0);
- QCOMPARE(instance2->typeEntry()->qualifiedCppName(), QLatin1String("Namespace::E1"));
-}
-
-void TestTemplates::testTemplateValueAsArgument()
-{
- const char cppCode[] = R"CPP(
-template<typename T> struct List {};
-void func(List<int> arg) {}
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Package'>
- <primitive-type name='int'/>
- <container-type name='List' type='list'/>
- <function signature='func(List&lt;int&gt;)'/>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaFunctionList globalFuncs = builder->globalFunctions();
- QCOMPARE(globalFuncs.count(), 1);
-
- AbstractMetaFunction* func = globalFuncs.first();
- QCOMPARE(func->minimalSignature(), QLatin1String("func(List<int>)"));
- QCOMPARE(func->arguments().first()->type()->cppSignature(), QLatin1String("List<int >"));
-}
-
-void TestTemplates::testTemplatePointerAsArgument()
-{
- const char cppCode[] = R"CPP(
-template<typename T> struct List {};
-void func(List<int>* arg) {}
-)CPP";
-
- const char xmlCode[] = R"XML(
- <typesystem package='Package'>
- <primitive-type name='int'/>
- <container-type name='List' type='list'/>
- <function signature='func(List&lt;int&gt;*)'/>
- </typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaFunctionList globalFuncs = builder->globalFunctions();
- QCOMPARE(globalFuncs.count(), 1);
-
- AbstractMetaFunction* func = globalFuncs.first();
- QCOMPARE(func->minimalSignature(), QLatin1String("func(List<int>*)"));
- QCOMPARE(func->arguments().first()->type()->cppSignature(), QLatin1String("List<int > *"));
-}
-
-void TestTemplates::testTemplateReferenceAsArgument()
-{
- const char cppCode[] = R"CPP(
-template<typename T> struct List {};
-void func(List<int>& arg) {}
- )CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Package'>
- <primitive-type name='int'/>
- <container-type name='List' type='list'/>
- <function signature='func(List&lt;int&gt;&amp;)'/>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaFunctionList globalFuncs = builder->globalFunctions();
- QCOMPARE(globalFuncs.count(), 1);
-
- AbstractMetaFunction* func = globalFuncs.first();
- QCOMPARE(func->minimalSignature(), QLatin1String("func(List<int>&)"));
- QCOMPARE(func->arguments().first()->type()->cppSignature(), QLatin1String("List<int > &"));
-}
-
-void TestTemplates::testTemplateParameterFixup()
-{
- const char cppCode[] = R"CPP(
-template<typename T>
-struct List {
- struct Iterator {};
- void append(List l);
- void erase(List::Iterator it);
-};
-)CPP";
-
- const char xmlCode[] = R"XML(
- <typesystem package='Package'>
- <container-type name='List' type='list'>
- <value-type name='Iterator'/>
- </container-type>
- </typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- const AbstractMetaClassList templates = builder->templates();
-
- QCOMPARE(templates.count(), 1);
- const AbstractMetaClass *list = templates.first();
- // Verify that the parameter of "void append(List l)" gets fixed to "List<T >"
- const AbstractMetaFunction *append = list->findFunction(QStringLiteral("append"));
- QVERIFY(append);
- QCOMPARE(append->arguments().size(), 1);
- QCOMPARE(append->arguments().at(0)->type()->cppSignature(), QLatin1String("List<T >"));
- // Verify that the parameter of "void erase(Iterator)" is not modified
- const AbstractMetaFunction *erase = list->findFunction(QStringLiteral("erase"));
- QVERIFY(erase);
- QCOMPARE(erase->arguments().size(), 1);
- QEXPECT_FAIL("", "Clang: Some other code changes the parameter type", Abort);
- QCOMPARE(erase->arguments().at(0)->type()->cppSignature(), QLatin1String("List::Iterator"));
-}
-
-void TestTemplates::testInheritanceFromContainterTemplate()
-{
- const char cppCode[] = R"CPP(
-template<typename T>
-struct ListContainer {
- inline void push_front(const T& t);
- inline T& front();
-};
-struct FooBar {};
-struct FooBars : public ListContainer<FooBar> {};
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Package'>
- <container-type name='ListContainer' type='list'/>
- <value-type name='FooBar'/>
- <value-type name='FooBars'>
- <modify-function signature='push_front(FooBar)' remove='all'/>
- <modify-function signature='front()' remove='all'/>
- </value-type>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- AbstractMetaClassList templates = builder->templates();
- QCOMPARE(classes.count(), 2);
- QCOMPARE(templates.count(), 1);
-
- const AbstractMetaClass* foobars = AbstractMetaClass::findClass(classes, QLatin1String("FooBars"));
- QCOMPARE(foobars->functions().count(), 4);
-
- const AbstractMetaClass* lc = templates.first();
- QCOMPARE(lc->functions().count(), 2);
-}
-
-void TestTemplates::testTemplateInheritanceMixedWithForwardDeclaration()
-{
- const char cppCode[] = R"CPP(
-enum SomeEnum { E1, E2 };
-template<SomeEnum type> struct Future;
-template<SomeEnum type>
-struct A {
- A();
- void method();
- friend struct Future<type>;
-};
-typedef A<E1> B;
-template<SomeEnum type> struct Future {};
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Package'>
- <enum-type name='SomeEnum'/>
- <value-type name='A' generate='no'/>
- <value-type name='B'/>
- <value-type name='Future' generate='no'/>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
-
- AbstractMetaClass* classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
- QVERIFY(!classB->baseClass());
- QVERIFY(classB->baseClassName().isEmpty());
- // 3 functions: simple constructor, copy constructor and "method()".
- QCOMPARE(classB->functions().count(), 3);
-}
-
-void TestTemplates::testTemplateInheritanceMixedWithNamespaceAndForwardDeclaration()
-{
- const char cppCode[] = R"CPP(
-namespace Namespace {
-enum SomeEnum { E1, E2 };
-template<SomeEnum type> struct Future;
-template<SomeEnum type>
-struct A {
- A();
- void method();
- friend struct Future<type>;
-};
-typedef A<E1> B;
-template<SomeEnum type> struct Future {};
-};
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Package'>
- <namespace-type name='Namespace'>
- <enum-type name='SomeEnum'/>
- <value-type name='A' generate='no'/>
- <value-type name='B'/>
- <value-type name='Future' generate='no'/>
- </namespace-type>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
-
- AbstractMetaClass* classB = AbstractMetaClass::findClass(classes, QLatin1String("Namespace::B"));
- QVERIFY(classB);
- QVERIFY(!classB->baseClass());
- QVERIFY(classB->baseClassName().isEmpty());
- // 3 functions: simple constructor, copy constructor and "method()".
- QCOMPARE(classB->functions().count(), 3);
-}
-
-void TestTemplates::testTypedefOfInstantiationOfTemplateClass()
-{
- const char cppCode[] = R"CPP(
-namespace NSpace {
-enum ClassType {
- TypeOne
-};
-template<ClassType CLASS_TYPE>
-struct BaseTemplateClass {
- inline ClassType getClassType() const { CLASS_TYPE; }
-};
-typedef BaseTemplateClass<TypeOne> TypeOneClass;
-}
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Package'>
- <namespace-type name='NSpace'>
- <enum-type name='ClassType'/>
- <object-type name='BaseTemplateClass' generate='no'/>
- <object-type name='TypeOneClass'/>
- </namespace-type>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 3);
-
- const AbstractMetaClass* base = AbstractMetaClass::findClass(classes, QLatin1String("BaseTemplateClass"));
- QVERIFY(base);
- const AbstractMetaClass* one = AbstractMetaClass::findClass(classes, QLatin1String("TypeOneClass"));
- QVERIFY(one);
- QCOMPARE(one->templateBaseClass(), base);
- QCOMPARE(one->functions().count(), base->functions().count());
- QVERIFY(one->isTypeDef());
- const ComplexTypeEntry* oneType = one->typeEntry();
- const ComplexTypeEntry* baseType = base->typeEntry();
- QCOMPARE(oneType->baseContainerType(), baseType);
- QCOMPARE(one->baseClassNames(), QStringList(QLatin1String("BaseTemplateClass<TypeOne>")));
-
- QVERIFY(one->hasTemplateBaseClassInstantiations());
- AbstractMetaTypeList instantiations = one->templateBaseClassInstantiations();
- QCOMPARE(instantiations.count(), 1);
- const AbstractMetaType* inst = instantiations.first();
- QVERIFY(inst);
- QVERIFY(!inst->isEnum());
- QVERIFY(!inst->typeEntry()->isEnum());
- QVERIFY(inst->typeEntry()->isEnumValue());
- QCOMPARE(inst->cppSignature(), QLatin1String("NSpace::TypeOne"));
-}
-
-void TestTemplates::testContainerTypeIncompleteArgument()
-{
- const char cppCode[] = R"CPP(
-template<typename T>
-class Vector {
- void method(const Vector& vector);
- Vector otherMethod();
-};
-template <typename T>
-void Vector<T>::method(const Vector<T>& vector) {}
-template <typename T>
-Vector<T> Vector<T>::otherMethod() { return Vector<T>(); }
-typedef Vector<int> IntVector;
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <container-type name='Vector' type='vector'/>
- <value-type name='IntVector'/>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, true));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- QCOMPARE(classes.count(), 1);
-
- AbstractMetaClass* vector = AbstractMetaClass::findClass(classes, QLatin1String("IntVector"));
- QVERIFY(vector);
- auto baseContainer = vector->typeEntry()->baseContainerType();
- QVERIFY(baseContainer);
- QCOMPARE(reinterpret_cast<const ContainerTypeEntry*>(baseContainer)->containerKind(),
- ContainerTypeEntry::VectorContainer);
- QCOMPARE(vector->functions().count(), 4);
-
- const AbstractMetaFunction* method = vector->findFunction(QLatin1String("method"));
- QVERIFY(method);
- QCOMPARE(method->signature(), QLatin1String("method(const Vector<int > & vector)"));
-
- const AbstractMetaFunction* otherMethod = vector->findFunction(QLatin1String("otherMethod"));
- QVERIFY(otherMethod);
- QCOMPARE(otherMethod->signature(), QLatin1String("otherMethod()"));
- QVERIFY(otherMethod->type());
- QCOMPARE(otherMethod->type()->cppSignature(), QLatin1String("Vector<int >"));
-}
-
-void TestTemplates::testNonTypeTemplates()
-{
- // PYSIDe-1296, functions with non type templates parameters.
- const char cppCode[] = R"CPP(
-template <class T, int Size>
-class Array {
- T array[Size];
-};
-
-Array<int, 2> foo();
-
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <container-type name='Array' type='vector'/>
- <function signature="foo()"/>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, true));
- QVERIFY(!builder.isNull());
- auto functions = builder->globalFunctions();
- QCOMPARE(functions.count(), 1);
- auto foo = functions.constFirst();
- QCOMPARE(foo->name(), QLatin1String("foo"));
- QCOMPARE(foo->type()->name(), QLatin1String("Array"));
-}
-
-// Perform checks on template inheritance; a typedef of a template class
-// should result in rewritten types.
-void TestTemplates::testTemplateTypeDefs_data()
-{
- QTest::addColumn<QString>("cpp");
- QTest::addColumn<QString>("xml");
-
- const char optionalClassDef[] = R"CPP(
-template<class T> // Some value type similar to std::optional
-class Optional {
-public:
- T value() const { return m_value; }
- operator bool() const { return m_success; }
-
- T m_value;
- bool m_success = false;
-};
-)CPP";
-
- const char xmlPrefix[] = R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <primitive-type name='bool'/>
-)XML";
-
- const char xmlOptionalDecl[] = "<value-type name='Optional' generate='no'/>\n";
- const char xmlOptionalIntDecl[] = "<value-type name='IntOptional'/>\n";
- const char xmlPostFix[] = "</typesystem>\n";
-
- // Flat, global namespace
- QString cpp;
- QTextStream(&cpp) << optionalClassDef
- << "typedef Optional<int> IntOptional;\n";
- QString xml;
- QTextStream(&xml) << xmlPrefix << xmlOptionalDecl << xmlOptionalIntDecl
- << "<typedef-type name='XmlIntOptional' source='Optional&lt;int&gt;'/>"
- << xmlPostFix;
- QTest::newRow("global-namespace")
- << cpp << xml;
-
- // Typedef from namespace Std
- cpp.clear();
- QTextStream(&cpp) << "namespace Std {\n" << optionalClassDef << "}\n"
- << "typedef Std::Optional<int> IntOptional;\n";
- xml.clear();
- QTextStream(&xml) << xmlPrefix
- << "<namespace-type name='Std'>\n" << xmlOptionalDecl
- << "</namespace-type>\n" << xmlOptionalIntDecl
- << "<typedef-type name='XmlIntOptional' source='Std::Optional&lt;int&gt;'/>"
- << xmlPostFix;
- QTest::newRow("namespace-Std")
- << cpp << xml;
-
- // Typedef from nested class
- cpp.clear();
- QTextStream(&cpp) << "class Outer {\npublic:\n" << optionalClassDef << "\n};\n"
- << "typedef Outer::Optional<int> IntOptional;\n";
- xml.clear();
- QTextStream(&xml) << xmlPrefix
- << "<object-type name='Outer'>\n" << xmlOptionalDecl
- << "</object-type>\n" << xmlOptionalIntDecl
- << "<typedef-type name='XmlIntOptional' source='Outer::Optional&lt;int&gt;'/>"
- << xmlPostFix;
- QTest::newRow("nested-class")
- << cpp << xml;
-}
-
-void TestTemplates::testTemplateTypeDefs()
-{
- QFETCH(QString, cpp);
- QFETCH(QString, xml);
-
- const QByteArray cppBa = cpp.toLocal8Bit();
- const QByteArray xmlBa = xml.toLocal8Bit();
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppBa.constData(), xmlBa.constData(), true));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
-
- const AbstractMetaClass *optional = AbstractMetaClass::findClass(classes, QLatin1String("Optional"));
- QVERIFY(optional);
-
- // Find the typedef'ed class
- const AbstractMetaClass *optionalInt =
- AbstractMetaClass::findClass(classes, QLatin1String("IntOptional"));
- QVERIFY(optionalInt);
- QCOMPARE(optionalInt->templateBaseClass(), optional);
-
- // Find the class typedef'ed in the typesystem XML
- const AbstractMetaClass *xmlOptionalInt =
- AbstractMetaClass::findClass(classes, QLatin1String("XmlIntOptional"));
- QVERIFY(xmlOptionalInt);
- QCOMPARE(xmlOptionalInt->templateBaseClass(), optional);
-
- // Check whether the value() method now has an 'int' return
- const AbstractMetaFunction *valueMethod =
- optionalInt->findFunction(QLatin1String("value"));
- QVERIFY(valueMethod);
- QCOMPARE(valueMethod->type()->cppSignature(), QLatin1String("int"));
-
- // ditto for typesystem XML
- const AbstractMetaFunction *xmlValueMethod =
- xmlOptionalInt->findFunction(QLatin1String("value"));
- QVERIFY(xmlValueMethod);
- QCOMPARE(xmlValueMethod->type()->cppSignature(), QLatin1String("int"));
-
- // Check whether the m_value field is of type 'int'
- const AbstractMetaField *valueField =
- optionalInt->findField(QLatin1String("m_value"));
- QVERIFY(valueField);
- QCOMPARE(valueField->type()->cppSignature(), QLatin1String("int"));
-
- // ditto for typesystem XML
- const AbstractMetaField *xmlValueField =
- xmlOptionalInt->findField(QLatin1String("m_value"));
- QVERIFY(xmlValueField);
- QCOMPARE(xmlValueField->type()->cppSignature(), QLatin1String("int"));
-}
-
-void TestTemplates::testTemplateTypeAliases()
-{
- // Model Qt 6's "template<typename T> using QList = QVector<T>"
- const char cppCode[] = R"CPP(
-template<typename T>
-class Container1 { };
-
-template<typename T>
-using Container2 = Container1<T>;
-
-class Test
-{
-public:
- Container2<int> m_intContainer;
-};
-
-class Derived : public Container2<int>
-{
-public:
-};
-)CPP";
-
- const char xmlCode[] = R"XML(
-<typesystem package='Foo'>
- <primitive-type name='int'/>
- <value-type name='Container1'/>
- <value-type name='Derived'/>
- <object-type name='Test'/>
-</typesystem>)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, true));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
- auto testClass = AbstractMetaClass::findClass(classes, QLatin1String("Test"));
- QVERIFY(testClass);
-
- auto fields = testClass->fields();
- QCOMPARE(fields.count(), 1);
- auto fieldType = testClass->fields().at(0)->type();
- QCOMPARE(fieldType->name(), QLatin1String("Container1"));
- QCOMPARE(fieldType->instantiations().size(), 1);
-
- auto derived = AbstractMetaClass::findClass(classes, QLatin1String("Derived"));
- QVERIFY(derived);
- auto base = derived->templateBaseClass();
- QCOMPARE(base->name(), QLatin1String("Container1"));
-}
-
-QTEST_APPLESS_MAIN(TestTemplates)
diff --git a/sources/shiboken2/ApiExtractor/tests/testtemplates.h b/sources/shiboken2/ApiExtractor/tests/testtemplates.h
deleted file mode 100644
index c96e7fe4a..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testtemplates.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTTEMPLATES_H
-#define TESTTEMPLATES_H
-
-#include <QObject>
-
-class TestTemplates : public QObject
-{
- Q_OBJECT
-private slots:
- void testTemplateOnContainers();
- void testTemplateWithNamespace();
- void testTemplateValueAsArgument();
- void testTemplatePointerAsArgument();
- void testTemplateReferenceAsArgument();
- void testTemplateParameterFixup();
- void testInheritanceFromContainterTemplate();
- void testTemplateInheritanceMixedWithForwardDeclaration();
- void testTemplateInheritanceMixedWithNamespaceAndForwardDeclaration();
- void testTypedefOfInstantiationOfTemplateClass();
- void testContainerTypeIncompleteArgument();
- void testNonTypeTemplates();
- void testTemplateTypeDefs_data();
- void testTemplateTypeDefs();
- void testTemplateTypeAliases();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testtoposort.cpp b/sources/shiboken2/ApiExtractor/tests/testtoposort.cpp
deleted file mode 100644
index c59fa8c3d..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testtoposort.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testtoposort.h"
-#include <QtTest/QTest>
-#include "graph.h"
-#include <QDebug>
-
-void TestTopoSort::testTopoSort()
-{
- {
- Graph g(3);
- g.addEdge(1, 2);
- g.addEdge(0, 1);
- const auto result = g.topologicalSort();
- QCOMPARE(result.size(), 3);
- auto it = result.begin();
- QCOMPARE(*it, 0);
- QCOMPARE(*(++it), 1);
- QCOMPARE(*(++it), 2);
- }
- {
- Graph g(2);
- const auto result = g.topologicalSort();
- QCOMPARE(result.size(), 2);
- auto it = result.begin();
- QCOMPARE(*it, 1);
- QCOMPARE(*(++it), 0);
- }
-}
-
-void TestTopoSort::testCiclicGraph()
-{
- Graph g(3);
- g.addEdge(0, 1);
- g.addEdge(1, 2);
- g.addEdge(2, 0);
- const auto result = g.topologicalSort();
- QVERIFY(result.isEmpty());
-}
-
-QTEST_APPLESS_MAIN(TestTopoSort)
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testtoposort.h b/sources/shiboken2/ApiExtractor/tests/testtoposort.h
deleted file mode 100644
index 0770a8d0e..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testtoposort.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTTOPOSORT_H
-#define TESTTOPOSORT_H
-
-#include <QObject>
-
-class TestTopoSort : public QObject
-{
-Q_OBJECT
-private slots:
- void testTopoSort();
- void testCiclicGraph();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testtyperevision.cpp b/sources/shiboken2/ApiExtractor/tests/testtyperevision.cpp
deleted file mode 100644
index 10bf35d59..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testtyperevision.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testtyperevision.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-#include <typedatabase.h>
-
-void TestTypeRevision::testRevisionAttr()
-{
- const char* cppCode = "class Rev_0 {};"
- "class Rev_1 {};"
- "class Rev_2 { public: enum Rev_3 { X }; enum Rev_5 { Y }; };";
- const char* xmlCode = "<typesystem package=\"Foo\">"
- "<value-type name=\"Rev_0\"/>"
- "<value-type name=\"Rev_1\" revision=\"1\"/>"
- "<object-type name=\"Rev_2\" revision=\"2\">"
- " <enum-type name=\"Rev_3\" revision=\"3\" flags=\"Flag_4\" flags-revision=\"4\" />"
- " <enum-type name=\"Rev_5\" revision=\"5\" flags=\"Flag_5\" />"
- "</object-type>"
- "</typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *rev0 = AbstractMetaClass::findClass(classes, QLatin1String("Rev_0"));
- QCOMPARE(rev0->typeEntry()->revision(), 0);
-
- const AbstractMetaClass *rev1 = AbstractMetaClass::findClass(classes, QLatin1String("Rev_1"));
- QCOMPARE(rev1->typeEntry()->revision(), 1);
-
- AbstractMetaClass *rev2 = AbstractMetaClass::findClass(classes, QLatin1String("Rev_2"));
- QCOMPARE(rev2->typeEntry()->revision(), 2);
-
- AbstractMetaEnum* rev3 = rev2->findEnum(QLatin1String("Rev_3"));
- QCOMPARE(rev3->typeEntry()->revision(), 3);
- FlagsTypeEntry* rev4 = rev3->typeEntry()->flags();
- QCOMPARE(rev4->revision(), 4);
- AbstractMetaEnum* rev5 = rev2->findEnum(QLatin1String("Rev_5"));
- const EnumTypeEntry *revEnumTypeEntry = rev5->typeEntry();
- QCOMPARE(revEnumTypeEntry->revision(), 5);
- QCOMPARE(revEnumTypeEntry->flags()->revision(), 5);
-}
-
-
-void TestTypeRevision::testVersion_data()
-{
- QTest::addColumn<QString>("version");
- QTest::addColumn<int>("expectedClassCount");
-
- QTest::newRow("none") << QString() << 2;
- QTest::newRow("1.0") << QString::fromLatin1("1.0") << 1; // Bar20 excluded
- QTest::newRow("2.0") << QString::fromLatin1("2.0") << 2;
- QTest::newRow("3.0") << QString::fromLatin1("3.0") << 1; // Bar excluded by "until"
-}
-
-void TestTypeRevision::testVersion()
-{
- QFETCH(QString, version);
- QFETCH(int, expectedClassCount);
-
- const char cppCode[] = R"CPP(
-class Bar {};
-class Bar20 {};
-)CPP";
- const char xmlCode[] = R"XML(
-<typesystem package="Foo">
- <value-type name="Bar" until="2.0"/>
- <value-type name="Bar20" since="2.0"/>
-</typesystem>
-)XML";
-
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, true, version));
- QVERIFY(!builder.isNull());
-
- QCOMPARE(builder->classes().size(), expectedClassCount);
-}
-
-QTEST_APPLESS_MAIN(TestTypeRevision)
-
-
diff --git a/sources/shiboken2/ApiExtractor/tests/testtyperevision.h b/sources/shiboken2/ApiExtractor/tests/testtyperevision.h
deleted file mode 100644
index 3832c3883..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testtyperevision.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTTYPEREVISION_H
-#define TESTTYPEREVISION_H
-
-#include <QObject>
-
-class TestTypeRevision : public QObject
-{
- Q_OBJECT
-
-private slots:
- void testRevisionAttr();
- void testVersion_data();
- void testVersion();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testutil.h b/sources/shiboken2/ApiExtractor/tests/testutil.h
deleted file mode 100644
index e24e54365..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testutil.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTUTIL_H
-#define TESTUTIL_H
-#include <QtCore/QBuffer>
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QTemporaryFile>
-#include "abstractmetabuilder.h"
-#include "reporthandler.h"
-#include "typedatabase.h"
-
-namespace TestUtil
-{
- static AbstractMetaBuilder *parse(const char *cppCode, const char *xmlCode,
- bool silent = true,
- const QString &apiVersion = QString(),
- const QStringList &dropTypeEntries = QStringList())
- {
- ReportHandler::setSilent(silent);
- ReportHandler::startTimer();
- TypeDatabase* td = TypeDatabase::instance(true);
- if (apiVersion.isEmpty())
- TypeDatabase::clearApiVersions();
- else if (!TypeDatabase::setApiVersion(QLatin1String("*"), apiVersion))
- return nullptr;
- td->setDropTypeEntries(dropTypeEntries);
- QBuffer buffer;
- // parse typesystem
- buffer.setData(xmlCode);
- if (!buffer.open(QIODevice::ReadOnly))
- return Q_NULLPTR;
- if (!td->parseFile(&buffer))
- return nullptr;
- buffer.close();
- // parse C++ code
- QTemporaryFile tempSource(QDir::tempPath() + QLatin1String("/st_XXXXXX_main.cpp"));
- if (!tempSource.open()) {
- qWarning().noquote().nospace() << "Creation of temporary file failed: "
- << tempSource.errorString();
- return nullptr;
- }
- QByteArrayList arguments;
- arguments.append(QFile::encodeName(tempSource.fileName()));
- tempSource.write(cppCode, qint64(strlen(cppCode)));
- tempSource.close();
- auto *builder = new AbstractMetaBuilder;
- if (!builder->build(arguments)) {
- delete builder;
- return Q_NULLPTR;
- }
- return builder;
- }
-} // namespace TestUtil
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testvaluetypedefaultctortag.cpp b/sources/shiboken2/ApiExtractor/tests/testvaluetypedefaultctortag.cpp
deleted file mode 100644
index 1850025d6..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testvaluetypedefaultctortag.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testvaluetypedefaultctortag.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestValueTypeDefaultCtorTag::testValueTypeDefaultCtorTagArgument()
-{
- const char* cppCode ="\n\
- struct A {\n\
- A(int,int);\n\
- };\n\
- struct B {};\n\
- ";
- const char* xmlCode = "\n\
- <typesystem package='Foo'>\n\
- <primitive-type name='int' />\n\
- <value-type name='A' default-constructor='A(0, 0)' />\n\
- <value-type name='B' />\n\
- </typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode, false));
- QVERIFY(!builder.isNull());
-
- AbstractMetaClassList classes = builder->classes();
-
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- QVERIFY(classA->typeEntry()->hasDefaultConstructor());
- QCOMPARE(classA->typeEntry()->defaultConstructor(), QLatin1String("A(0, 0)"));
-
- const AbstractMetaClass *classB = AbstractMetaClass::findClass(classes, QLatin1String("B"));
- QVERIFY(classB);
- QVERIFY(!classB->typeEntry()->hasDefaultConstructor());
-}
-
-QTEST_APPLESS_MAIN(TestValueTypeDefaultCtorTag)
diff --git a/sources/shiboken2/ApiExtractor/tests/testvaluetypedefaultctortag.h b/sources/shiboken2/ApiExtractor/tests/testvaluetypedefaultctortag.h
deleted file mode 100644
index 244181707..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testvaluetypedefaultctortag.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTVALUETYPEDEFAULTCTORTAG_H
-#define TESTVALUETYPEDEFAULTCTORTAG_H
-
-#include <QObject>
-
-class TestValueTypeDefaultCtorTag : public QObject
-{
- Q_OBJECT
- private slots:
- void testValueTypeDefaultCtorTagArgument();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/testvoidarg.cpp b/sources/shiboken2/ApiExtractor/tests/testvoidarg.cpp
deleted file mode 100644
index 68681550f..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testvoidarg.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "testvoidarg.h"
-#include <QtTest/QTest>
-#include "testutil.h"
-#include <abstractmetalang.h>
-#include <typesystem.h>
-
-void TestVoidArg::testVoidParsedFunction()
-{
- const char cppCode[] = "struct A { void a(void); };";
- const char xmlCode[] = "\n\
- <typesystem package=\"Foo\">\n\
- <value-type name='A'/>\n\
- </typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaFunction* addedFunc = classA->findFunction(QLatin1String("a"));
- QCOMPARE(addedFunc->arguments().count(), 0);
-}
-
-void TestVoidArg::testVoidAddedFunction()
-{
- const char cppCode[] = "struct A { };";
- const char xmlCode[] = "\n\
- <typesystem package=\"Foo\">\n\
- <value-type name='A' >\n\
- <add-function signature=\"a(void)\"/>\n\
- </value-type>\n\
- </typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaFunction* addedFunc = classA->findFunction(QLatin1String("a"));
- QCOMPARE(addedFunc->arguments().count(), 0);
-
-}
-
-void TestVoidArg::testVoidPointerParsedFunction()
-{
- const char cppCode[] = "struct A { void a(void*); };";
- const char xmlCode[] = "\n\
- <typesystem package=\"Foo\">\n\
- <value-type name='A' />\n\
- </typesystem>";
- QScopedPointer<AbstractMetaBuilder> builder(TestUtil::parse(cppCode, xmlCode));
- QVERIFY(!builder.isNull());
- AbstractMetaClassList classes = builder->classes();
- const AbstractMetaClass *classA = AbstractMetaClass::findClass(classes, QLatin1String("A"));
- QVERIFY(classA);
- const AbstractMetaFunction* addedFunc = classA->findFunction(QLatin1String("a"));
- QCOMPARE(addedFunc->arguments().count(), 1);
-
-}
-
-QTEST_APPLESS_MAIN(TestVoidArg)
diff --git a/sources/shiboken2/ApiExtractor/tests/testvoidarg.h b/sources/shiboken2/ApiExtractor/tests/testvoidarg.h
deleted file mode 100644
index 44d90d075..000000000
--- a/sources/shiboken2/ApiExtractor/tests/testvoidarg.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TESTVOIDARG_H
-#define TESTVOIDARG_H
-#include <QObject>
-
-class TestVoidArg : public QObject
-{
- Q_OBJECT
-private slots:
- void testVoidParsedFunction();
- void testVoidPointerParsedFunction();
- void testVoidAddedFunction();
-};
-
-#endif
diff --git a/sources/shiboken2/ApiExtractor/tests/utf8code.txt b/sources/shiboken2/ApiExtractor/tests/utf8code.txt
deleted file mode 100644
index 6d5fa9dcf..000000000
--- a/sources/shiboken2/ApiExtractor/tests/utf8code.txt
+++ /dev/null
@@ -1 +0,0 @@
-áéíóú \ No newline at end of file
diff --git a/sources/shiboken2/ApiExtractor/typedatabase.cpp b/sources/shiboken2/ApiExtractor/typedatabase.cpp
deleted file mode 100644
index 4a29a25c9..000000000
--- a/sources/shiboken2/ApiExtractor/typedatabase.cpp
+++ /dev/null
@@ -1,1039 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "typedatabase.h"
-#include "typesystem.h"
-#include "typesystemparser.h"
-
-#include <QtCore/QFile>
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QPair>
-#include <QtCore/QVector>
-#include <QtCore/QRegularExpression>
-#include <QtCore/QVersionNumber>
-#include <QtCore/QXmlStreamReader>
-#include "reporthandler.h"
-// #include <tr1/tuple>
-#include <algorithm>
-
-// package -> api-version
-
-static QString wildcardToRegExp(QString w)
-{
- w.replace(QLatin1Char('?'), QLatin1Char('.'));
- w.replace(QLatin1Char('*'), QStringLiteral(".*"));
- return w;
-}
-
-using ApiVersion =QPair<QRegularExpression, QVersionNumber>;
-using ApiVersions = QVector<ApiVersion>;
-
-Q_GLOBAL_STATIC(ApiVersions, apiVersions)
-
-TypeDatabase::TypeDatabase()
-{
- addType(new VoidTypeEntry());
- addType(new VarargsTypeEntry());
-}
-
-TypeDatabase::~TypeDatabase() = default;
-
-TypeDatabase* TypeDatabase::instance(bool newInstance)
-{
- static TypeDatabase *db = nullptr;
- if (!db || newInstance) {
- delete db;
- db = new TypeDatabase;
- }
- return db;
-}
-
-// A list of regex/replacements to fix int types like "ushort" to "unsigned short"
-// unless present in TypeDatabase
-struct IntTypeNormalizationEntry
-{
- QRegularExpression regex;
- QString replacement;
-};
-
-using IntTypeNormalizationEntries = QVector<IntTypeNormalizationEntry>;
-
-static const IntTypeNormalizationEntries &intTypeNormalizationEntries()
-{
- static IntTypeNormalizationEntries result;
- static bool firstTime = true;
- if (firstTime) {
- firstTime = false;
- for (auto t : {"char", "short", "int", "long"}) {
- const QString intType = QLatin1String(t);
- if (!TypeDatabase::instance()->findType(QLatin1Char('u') + intType)) {
- IntTypeNormalizationEntry entry;
- entry.replacement = QStringLiteral("unsigned ") + intType;
- entry.regex.setPattern(QStringLiteral("\\bu") + intType + QStringLiteral("\\b"));
- Q_ASSERT(entry.regex.isValid());
- result.append(entry);
- }
- }
- }
- return result;
-}
-
-QString TypeDatabase::normalizedSignature(const QString &signature)
-{
- QString normalized = QLatin1String(QMetaObject::normalizedSignature(signature.toUtf8().constData()));
-
- if (instance() && signature.contains(QLatin1String("unsigned"))) {
- const IntTypeNormalizationEntries &entries = intTypeNormalizationEntries();
- for (const auto &entry : entries)
- normalized.replace(entry.regex, entry.replacement);
- }
-
- return normalized;
-}
-
-QStringList TypeDatabase::requiredTargetImports() const
-{
- return m_requiredTargetImports;
-}
-
-void TypeDatabase::addRequiredTargetImport(const QString& moduleName)
-{
- if (!m_requiredTargetImports.contains(moduleName))
- m_requiredTargetImports << moduleName;
-}
-
-void TypeDatabase::addTypesystemPath(const QString& typesystem_paths)
-{
- #if defined(Q_OS_WIN32)
- const char path_splitter = ';';
- #else
- const char path_splitter = ':';
- #endif
- m_typesystemPaths += typesystem_paths.split(QLatin1Char(path_splitter));
-}
-
-IncludeList TypeDatabase::extraIncludes(const QString& className) const
-{
- ComplexTypeEntry* typeEntry = findComplexType(className);
- return typeEntry ? typeEntry->extraIncludes() : IncludeList();
-}
-
-void TypeDatabase::addSystemInclude(const QString &name)
-{
- m_systemIncludes.append(name.toUtf8());
-}
-
-// Add a lookup for the short name excluding inline namespaces
-// so that "std::shared_ptr" finds "std::__1::shared_ptr" as well.
-// Note: This inserts duplicate TypeEntry * into m_entries.
-void TypeDatabase::addInlineNamespaceLookups(const NamespaceTypeEntry *n)
-{
- QVector<TypeEntry *> additionalEntries; // Store before modifying the hash
- for (TypeEntry *entry : m_entries) {
- if (entry->isChildOf(n))
- additionalEntries.append(entry);
- }
- for (const auto &ae : additionalEntries)
- m_entries.insert(ae->shortName(), ae);
-}
-
-ContainerTypeEntry* TypeDatabase::findContainerType(const QString &name) const
-{
- QString template_name = name;
-
- int pos = name.indexOf(QLatin1Char('<'));
- if (pos > 0)
- template_name = name.left(pos);
-
- TypeEntry* type_entry = findType(template_name);
- if (type_entry && type_entry->isContainer())
- return static_cast<ContainerTypeEntry*>(type_entry);
- return nullptr;
-}
-
-static bool inline useType(const TypeEntry *t)
-{
- return !t->isPrimitive()
- || static_cast<const PrimitiveTypeEntry *>(t)->preferredTargetLangType();
-}
-
-FunctionTypeEntry* TypeDatabase::findFunctionType(const QString& name) const
-{
- const auto entries = findTypeRange(name);
- for (TypeEntry *entry : entries) {
- if (entry->type() == TypeEntry::FunctionType && useType(entry))
- return static_cast<FunctionTypeEntry*>(entry);
- }
- return nullptr;
-}
-
-void TypeDatabase::addTypeSystemType(const TypeSystemTypeEntry *e)
-{
- m_typeSystemEntries.append(e);
-}
-
-const TypeSystemTypeEntry *TypeDatabase::findTypeSystemType(const QString &name) const
-{
- for (auto entry : m_typeSystemEntries) {
- if (entry->name() == name)
- return entry;
- }
- return nullptr;
-}
-
-const TypeSystemTypeEntry *TypeDatabase::defaultTypeSystemType() const
-{
- return m_typeSystemEntries.value(0, nullptr);
-}
-
-QString TypeDatabase::defaultPackageName() const
-{
- Q_ASSERT(!m_typeSystemEntries.isEmpty());
- return m_typeSystemEntries.constFirst()->name();
-}
-
-TypeEntry* TypeDatabase::findType(const QString& name) const
-{
- const auto entries = findTypeRange(name);
- for (TypeEntry *entry : entries) {
- if (useType(entry))
- return entry;
- }
- return nullptr;
-}
-
-template <class Predicate>
-TypeEntries TypeDatabase::findTypesHelper(const QString &name, Predicate pred) const
-{
- TypeEntries result;
- const auto entries = findTypeRange(name);
- for (TypeEntry *entry : entries) {
- if (pred(entry))
- result.append(entry);
- }
- return result;
-}
-
-TypeEntries TypeDatabase::findTypes(const QString &name) const
-{
- return findTypesHelper(name, useType);
-}
-
-static bool useCppType(const TypeEntry *t)
-{
- bool result = false;
- switch (t->type()) {
- case TypeEntry::PrimitiveType:
- case TypeEntry::VoidType:
- case TypeEntry::FlagsType:
- case TypeEntry::EnumType:
- case TypeEntry::TemplateArgumentType:
- case TypeEntry::BasicValueType:
- case TypeEntry::ContainerType:
- case TypeEntry::ObjectType:
- case TypeEntry::ArrayType:
- case TypeEntry::CustomType:
- case TypeEntry::SmartPointerType:
- case TypeEntry::TypedefType:
- result = useType(t);
- break;
- default:
- break;
- }
- return result;
-}
-
-TypeEntries TypeDatabase::findCppTypes(const QString &name) const
-{
- return findTypesHelper(name, useCppType);
-}
-
-TypeEntryMultiMapConstIteratorRange TypeDatabase::findTypeRange(const QString &name) const
-{
- const auto range = m_entries.equal_range(name);
- return {range.first, range.second};
-}
-
-PrimitiveTypeEntryList TypeDatabase::primitiveTypes() const
-{
- PrimitiveTypeEntryList returned;
- for (auto it = m_entries.cbegin(), end = m_entries.cend(); it != end; ++it) {
- TypeEntry *typeEntry = it.value();
- if (typeEntry->isPrimitive())
- returned.append(static_cast<PrimitiveTypeEntry *>(typeEntry));
- }
- return returned;
-}
-
-ContainerTypeEntryList TypeDatabase::containerTypes() const
-{
- ContainerTypeEntryList returned;
- for (auto it = m_entries.cbegin(), end = m_entries.cend(); it != end; ++it) {
- TypeEntry *typeEntry = it.value();
- if (typeEntry->isContainer())
- returned.append(static_cast<ContainerTypeEntry *>(typeEntry));
- }
- return returned;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const TypeRejection &r)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "TypeRejection(type=" << r.matchType << ", class="
- << r.className.pattern() << ", pattern=" << r.pattern.pattern() << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-void TypeDatabase::addRejection(const TypeRejection &r)
-{
- m_rejections << r;
-}
-
-static inline QString msgRejectReason(const TypeRejection &r, const QString &needle = QString())
-{
- QString result;
- QTextStream str(&result);
- switch (r.matchType) {
- case TypeRejection::ExcludeClass:
- str << " matches class exclusion \"" << r.className.pattern() << '"';
- break;
- case TypeRejection::Function:
- case TypeRejection::Field:
- case TypeRejection::Enum:
- str << " matches class \"" << r.className.pattern() << "\" and \"" << r.pattern.pattern() << '"';
- break;
- case TypeRejection::ArgumentType:
- case TypeRejection::ReturnType:
- str << " matches class \"" << r.className.pattern() << "\" and \"" << needle
- << "\" matches \"" << r.pattern.pattern() << '"';
- break;
- case TypeRejection::Invalid:
- break;
- }
- return result;
-}
-
-// Match class name only
-bool TypeDatabase::isClassRejected(const QString& className, QString *reason) const
-{
- for (const TypeRejection& r : m_rejections) {
- if (r.matchType == TypeRejection::ExcludeClass && r.className.match(className).hasMatch()) {
- if (reason)
- *reason = msgRejectReason(r);
- return true;
- }
- }
- return false;
-}
-
-// Match class name and function/enum/field
-static bool findRejection(const QVector<TypeRejection> &rejections,
- TypeRejection::MatchType matchType,
- const QString& className, const QString& name,
- QString *reason = nullptr)
-{
- Q_ASSERT(matchType != TypeRejection::ExcludeClass);
- for (const TypeRejection& r : rejections) {
- if (r.matchType == matchType && r.pattern.match(name).hasMatch()
- && r.className.match(className).hasMatch()) {
- if (reason)
- *reason = msgRejectReason(r, name);
- return true;
- }
- }
- return false;
-}
-
-bool TypeDatabase::isEnumRejected(const QString& className, const QString& enumName, QString *reason) const
-{
- return findRejection(m_rejections, TypeRejection::Enum, className, enumName, reason);
-}
-
-TypeEntry *TypeDatabase::resolveTypeDefEntry(TypedefEntry *typedefEntry,
- QString *errorMessage)
-{
- QString sourceName = typedefEntry->sourceType();
- const int lessThanPos = sourceName.indexOf(QLatin1Char('<'));
- if (lessThanPos != -1)
- sourceName.truncate(lessThanPos);
- ComplexTypeEntry *source = nullptr;
- for (TypeEntry *e : findTypeRange(sourceName)) {
- switch (e->type()) {
- case TypeEntry::BasicValueType:
- case TypeEntry::ContainerType:
- case TypeEntry::ObjectType:
- case TypeEntry::SmartPointerType:
- source = dynamic_cast<ComplexTypeEntry *>(e);
- Q_ASSERT(source);
- break;
- default:
- break;
- }
- }
- if (!source) {
- if (errorMessage)
- *errorMessage = QLatin1String("Unable to resolve typedef \"")
- + typedefEntry->sourceType() + QLatin1Char('"');
- return nullptr;
- }
-
- auto *result = static_cast<ComplexTypeEntry *>(source->clone());
- result->useAsTypedef(typedefEntry);
- typedefEntry->setSource(source);
- typedefEntry->setTarget(result);
- m_typedefEntries.insert(typedefEntry->qualifiedCppName(), typedefEntry);
- return result;
-}
-
-bool TypeDatabase::addType(TypeEntry *e, QString *errorMessage)
-{
- if (e->type() == TypeEntry::TypedefType) {
- e = resolveTypeDefEntry(static_cast<TypedefEntry *>(e), errorMessage);
- if (Q_UNLIKELY(!e))
- return false;
- }
- m_entries.insert(e->qualifiedCppName(), e);
- return true;
-}
-
-// Add a dummy value entry for non-type template parameters
-ConstantValueTypeEntry *
- TypeDatabase::addConstantValueTypeEntry(const QString &value,
- const TypeEntry *parent)
-{
- auto result = new ConstantValueTypeEntry(value, parent);
- result->setCodeGeneration(0);
- addType(result);
- return result;
-}
-
-bool TypeDatabase::isFunctionRejected(const QString& className, const QString& functionName,
- QString *reason) const
-{
- return findRejection(m_rejections, TypeRejection::Function, className, functionName, reason);
-}
-
-bool TypeDatabase::isFieldRejected(const QString& className, const QString& fieldName,
- QString *reason) const
-{
- return findRejection(m_rejections, TypeRejection::Field, className, fieldName, reason);
-}
-
-bool TypeDatabase::isArgumentTypeRejected(const QString& className, const QString& typeName,
- QString *reason) const
-{
- return findRejection(m_rejections, TypeRejection::ArgumentType, className, typeName, reason);
-}
-
-bool TypeDatabase::isReturnTypeRejected(const QString& className, const QString& typeName,
- QString *reason) const
-{
- return findRejection(m_rejections, TypeRejection::ReturnType, className, typeName, reason);
-}
-
-FlagsTypeEntry* TypeDatabase::findFlagsType(const QString &name) const
-{
- TypeEntry *fte = findType(name);
- if (!fte) {
- fte = m_flagsEntries.value(name);
- if (!fte) {
- //last hope, search for flag without scope inside of flags hash
- for (auto it = m_flagsEntries.cbegin(), end = m_flagsEntries.cend(); it != end; ++it) {
- if (it.key().endsWith(name)) {
- fte = it.value();
- break;
- }
- }
- }
- }
- return static_cast<FlagsTypeEntry *>(fte);
-}
-
-void TypeDatabase::addFlagsType(FlagsTypeEntry *fte)
-{
- m_flagsEntries[fte->originalName()] = fte;
-}
-
-void TypeDatabase::addTemplate(TemplateEntry *t)
-{
- m_templates[t->name()] = t;
-}
-
-void TypeDatabase::addGlobalUserFunctions(const AddedFunctionList &functions)
-{
- m_globalUserFunctions << functions;
-}
-
-AddedFunctionList TypeDatabase::findGlobalUserFunctions(const QString& name) const
-{
- AddedFunctionList addedFunctions;
- for (const AddedFunctionPtr &func : m_globalUserFunctions) {
- if (func->name() == name)
- addedFunctions.append(func);
- }
- return addedFunctions;
-}
-
-void TypeDatabase::addGlobalUserFunctionModifications(const FunctionModificationList &functionModifications)
-{
- m_functionMods << functionModifications;
-}
-
-QString TypeDatabase::globalNamespaceClassName(const TypeEntry * /*entry*/)
-{
- return QLatin1String("Global");
-}
-
-FunctionModificationList TypeDatabase::functionModifications(const QString& signature) const
-{
- FunctionModificationList lst;
- for (int i = 0; i < m_functionMods.count(); ++i) {
- const FunctionModification& mod = m_functionMods.at(i);
- if (mod.matches(signature))
- lst << mod;
- }
-
- return lst;
-}
-
-bool TypeDatabase::addSuppressedWarning(const QString &warning, QString *errorMessage)
-{
- QString pattern;
- if (warning.startsWith(QLatin1Char('^')) && warning.endsWith(QLatin1Char('$'))) {
- pattern = warning;
- } else {
- // Legacy syntax: Use wildcards '*' (unless escaped by '\')
- QVector<int> asteriskPositions;
- const int warningSize = warning.size();
- for (int i = 0; i < warningSize; ++i) {
- if (warning.at(i) == QLatin1Char('\\'))
- ++i;
- else if (warning.at(i) == QLatin1Char('*'))
- asteriskPositions.append(i);
- }
- asteriskPositions.append(warningSize);
-
- pattern.append(QLatin1Char('^'));
- int lastPos = 0;
- for (int a = 0, aSize = asteriskPositions.size(); a < aSize; ++a) {
- if (a)
- pattern.append(QStringLiteral(".*"));
- const int nextPos = asteriskPositions.at(a);
- if (nextPos > lastPos)
- pattern.append(QRegularExpression::escape(warning.mid(lastPos, nextPos - lastPos)));
- lastPos = nextPos + 1;
- }
- pattern.append(QLatin1Char('$'));
- }
-
- QRegularExpression expression(pattern);
- if (!expression.isValid()) {
- *errorMessage = QLatin1String("Invalid message pattern \"") + warning
- + QLatin1String("\": ") + expression.errorString();
- return false;
- }
- expression.setPatternOptions(expression.patternOptions() | QRegularExpression::MultilineOption);
-
- m_suppressedWarnings.append(expression);
- return true;
-}
-
-bool TypeDatabase::isSuppressedWarning(const QString& s) const
-{
- if (!m_suppressWarnings)
- return false;
-
- for (const QRegularExpression &warning : m_suppressedWarnings) {
- if (warning.match(s).hasMatch())
- return true;
- }
-
- return false;
-}
-
-QString TypeDatabase::modifiedTypesystemFilepath(const QString& tsFile, const QString &currentPath) const
-{
- const QFileInfo tsFi(tsFile);
- if (tsFi.isAbsolute()) // No point in further lookups
- return tsFi.absoluteFilePath();
- if (tsFi.isFile()) // Make path absolute
- return tsFi.absoluteFilePath();
- if (!currentPath.isEmpty()) {
- const QFileInfo fi(currentPath + QLatin1Char('/') + tsFile);
- if (fi.isFile())
- return fi.absoluteFilePath();
- }
- for (const QString &path : m_typesystemPaths) {
- const QFileInfo fi(path + QLatin1Char('/') + tsFile);
- if (fi.isFile())
- return fi.absoluteFilePath();
- }
- return tsFile;
-}
-
-bool TypeDatabase::parseFile(const QString &filename, bool generate)
-{
- return parseFile(filename, QString(), generate);
-}
-
-bool TypeDatabase::parseFile(const QString &filename, const QString &currentPath, bool generate)
-{
-
- QString filepath = modifiedTypesystemFilepath(filename, currentPath);
- if (m_parsedTypesystemFiles.contains(filepath))
- return m_parsedTypesystemFiles[filepath];
-
- m_parsedTypesystemFiles[filepath] = true; // Prevent recursion when including self.
-
- QFile file(filepath);
- if (!file.exists()) {
- m_parsedTypesystemFiles[filepath] = false;
- QString message = QLatin1String("Can't find ") + filename;
- if (!currentPath.isEmpty())
- message += QLatin1String(", current path: ") + currentPath;
- message += QLatin1String(", typesystem paths: ") + m_typesystemPaths.join(QLatin1String(", "));
- qCWarning(lcShiboken).noquote().nospace() << message;
- return false;
- }
- if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- m_parsedTypesystemFiles[filepath] = false;
- qCWarning(lcShiboken).noquote().nospace()
- << "Can't open " << QDir::toNativeSeparators(filename) << ": " << file.errorString();
- return false;
- }
-
- bool ok = parseFile(&file, generate);
- m_parsedTypesystemFiles[filepath] = ok;
- return ok;
-}
-
-bool TypeDatabase::parseFile(QIODevice* device, bool generate)
-{
- QXmlStreamReader reader(device);
- TypeSystemParser handler(this, generate);
- const bool result = handler.parse(reader);
- if (!result)
- qCWarning(lcShiboken, "%s", qPrintable(handler.errorString()));
- return result;
-}
-
-PrimitiveTypeEntry *TypeDatabase::findPrimitiveType(const QString& name) const
-{
- const auto entries = findTypeRange(name);
- for (TypeEntry *entry : entries) {
- if (entry->isPrimitive()) {
- auto *pe = static_cast<PrimitiveTypeEntry *>(entry);
- if (pe->preferredTargetLangType())
- return pe;
- }
- }
-
- return nullptr;
-}
-
-ComplexTypeEntry* TypeDatabase::findComplexType(const QString& name) const
-{
- const auto entries = findTypeRange(name);
- for (TypeEntry *entry : entries) {
- if (entry->isComplex() && useType(entry))
- return static_cast<ComplexTypeEntry*>(entry);
- }
- return nullptr;
-}
-
-ObjectTypeEntry* TypeDatabase::findObjectType(const QString& name) const
-{
- const auto entries = findTypeRange(name);
- for (TypeEntry *entry : entries) {
- if (entry && entry->isObject() && useType(entry))
- return static_cast<ObjectTypeEntry*>(entry);
- }
- return nullptr;
-}
-
-NamespaceTypeEntryList TypeDatabase::findNamespaceTypes(const QString& name) const
-{
- NamespaceTypeEntryList result;
- const auto entries = findTypeRange(name);
- for (TypeEntry *entry : entries) {
- if (entry->isNamespace())
- result.append(static_cast<NamespaceTypeEntry*>(entry));
- }
- return result;
-}
-
-NamespaceTypeEntry *TypeDatabase::findNamespaceType(const QString& name,
- const QString &fileName) const
-{
- const auto entries = findNamespaceTypes(name);
- // Preferably check on matching file name first, if a pattern was given.
- if (!fileName.isEmpty()) {
- for (NamespaceTypeEntry *entry : entries) {
- if (entry->hasPattern() && entry->matchesFile(fileName))
- return entry;
- }
- }
- for (NamespaceTypeEntry *entry : entries) {
- if (!entry->hasPattern())
- return entry;
- }
- return nullptr;
-}
-
-bool TypeDatabase::shouldDropTypeEntry(const QString& fullTypeName) const
-{
- return m_dropTypeEntries.contains(fullTypeName);
-}
-
-void TypeDatabase::setDropTypeEntries(QStringList dropTypeEntries)
-{
- m_dropTypeEntries = dropTypeEntries;
- m_dropTypeEntries.sort();
-}
-
-static bool computeTypeIndexes = true;
-static int maxTypeIndex;
-
-static bool typeEntryLessThan(const TypeEntry* t1, const TypeEntry* t2)
-{
- if (t1->revision() < t2->revision())
- return true;
- return t1->revision() == t2->revision()
- && t1->qualifiedCppName() < t2->qualifiedCppName();
-}
-
-static void _computeTypeIndexes()
-{
- TypeDatabase* tdb = TypeDatabase::instance();
-
- TypeEntryList list;
-
- // Group type entries by revision numbers
- const auto &allEntries = tdb->entries();
- list.reserve(allEntries.size());
- for (auto tit = allEntries.cbegin(), end = allEntries.cend(); tit != end; ++tit) {
- TypeEntry *entry = tit.value();
- if (entry->isPrimitive()
- || entry->isContainer()
- || entry->isFunction()
- || !entry->generateCode()
- || entry->isEnumValue()
- || entry->isVarargs()
- || entry->isTypeSystem()
- || entry->isVoid()
- || entry->isCustom())
- continue;
- if (!list.contains(entry)) // Remove duplicates
- list.append(entry);
- }
-
- // Sort the type entries by revision, name
- std::sort(list.begin(), list.end(), typeEntryLessThan);
-
- maxTypeIndex = 0;
- for (TypeEntry *e : qAsConst(list))
- e->setSbkIndex(maxTypeIndex++);
- computeTypeIndexes = false;
-}
-
-// Build the C++ name excluding any inline namespaces
-// ("std::__1::shared_ptr" -> "std::shared_ptr"
-QString TypeEntry::shortName() const
-{
- if (m_cachedShortName.isEmpty()) {
- QVarLengthArray<const TypeEntry *> parents;
- bool foundInlineNamespace = false;
- for (auto p = m_parent; p != nullptr && p->type() != TypeEntry::TypeSystemType; p = p->parent()) {
- if (p->type() == TypeEntry::NamespaceType
- && static_cast<const NamespaceTypeEntry *>(p)->isInlineNamespace()) {
- foundInlineNamespace = true;
- } else {
- parents.append(p);
- }
- }
- if (foundInlineNamespace) {
- m_cachedShortName.reserve(m_name.size());
- for (int i = parents.size() - 1; i >= 0; --i) {
- m_cachedShortName.append(parents.at(i)->entryName());
- m_cachedShortName.append(QLatin1String("::"));
- }
- m_cachedShortName.append(m_entryName);
- } else {
- m_cachedShortName = m_name;
- }
- }
- return m_cachedShortName;
-}
-
-void TypeEntry::setRevision(int r)
-{
- if (m_revision != r) {
- m_revision = r;
- computeTypeIndexes = true;
- }
-}
-
-int TypeEntry::sbkIndex() const
-{
- if (computeTypeIndexes)
- _computeTypeIndexes();
- return m_sbkIndex;
-}
-
-int getMaxTypeIndex()
-{
- if (computeTypeIndexes)
- _computeTypeIndexes();
- return maxTypeIndex;
-}
-
-void TypeDatabase::clearApiVersions()
-{
- apiVersions()->clear();
-}
-
-bool TypeDatabase::setApiVersion(const QString& packageWildcardPattern, const QString &version)
-{
- const QString packagePattern = wildcardToRegExp(packageWildcardPattern.trimmed());
- const QVersionNumber versionNumber = QVersionNumber::fromString(version);
- if (versionNumber.isNull())
- return false;
- ApiVersions &versions = *apiVersions();
- for (int i = 0, size = versions.size(); i < size; ++i) {
- if (versions.at(i).first.pattern() == packagePattern) {
- versions[i].second = versionNumber;
- return true;
- }
- }
- const QRegularExpression packageRegex(packagePattern);
- if (!packageRegex.isValid())
- return false;
- versions.append(qMakePair(packageRegex, versionNumber));
- return true;
-}
-
-bool TypeDatabase::checkApiVersion(const QString &package,
- const VersionRange &vr)
-{
- const ApiVersions &versions = *apiVersions();
- if (versions.isEmpty()) // Nothing specified: use latest.
- return true;
- for (int i = 0, size = versions.size(); i < size; ++i) {
- if (versions.at(i).first.match(package).hasMatch())
- return versions.at(i).second >= vr.since
- && versions.at(i).second <= vr.until;
- }
- return false;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-
-#define FORMAT_BOOL(name, var) \
- if (var) \
- d << ", [" << name << ']';
-
-#define FORMAT_NONEMPTY_STRING(name, var) \
- if (!var.isEmpty()) \
- d << ", " << name << "=\"" << var << '"';
-
-#define FORMAT_LIST_SIZE(name, var) \
- if (!var.isEmpty()) \
- d << ", " << var.size() << ' ' << name;
-
-template <class Container, class Separator>
-static void formatList(QDebug &d, const char *name, const Container &c, Separator sep)
-{
- if (const int size = c.size()) {
- d << ", " << name << '[' << size << "]=(";
- for (int i = 0; i < size; ++i) {
- if (i)
- d << sep;
- d << c.at(i);
- }
- d << ')';
- }
-}
-
-void TypeEntry::formatDebug(QDebug &d) const
-{
- const QString cppName = qualifiedCppName();
- d << '"' << m_name << '"';
- if (m_name != cppName)
- d << "\", cppName=\"" << cppName << '"';
- d << ", type=" << m_type << ", codeGeneration=0x"
- << Qt::hex << m_codeGeneration << Qt::dec
- << ", target=\"" << targetLangName() << '"';
- FORMAT_NONEMPTY_STRING("package", m_targetLangPackage)
- FORMAT_BOOL("stream", m_stream)
- FORMAT_LIST_SIZE("codeSnips", m_codeSnips)
- FORMAT_NONEMPTY_STRING("conversionRule", m_conversionRule)
- if (!m_version.isNull() && m_version > QVersionNumber(0, 0))
- d << ", version=" << m_version;
- if (m_revision)
- d << ", revision=" << m_revision;
- if (m_sbkIndex)
- d << ", sbkIndex=" << m_sbkIndex;
- if (m_include.isValid())
- d << ", include=" << m_include;
- formatList(d, "extraIncludes", m_extraIncludes, ", ");
-}
-
-void ComplexTypeEntry::formatDebug(QDebug &d) const
-{
- TypeEntry::formatDebug(d);
- FORMAT_BOOL("polymorphicBase", m_polymorphicBase)
- FORMAT_BOOL("genericClass", m_genericClass)
- FORMAT_BOOL("deleteInMainThread", m_deleteInMainThread)
- if (m_typeFlags != 0)
- d << ", typeFlags=" << m_typeFlags;
- d << ", copyableFlag=" << m_copyableFlag
- << ", except=" << int(m_exceptionHandling);
- FORMAT_NONEMPTY_STRING("defaultSuperclass", m_defaultSuperclass)
- FORMAT_NONEMPTY_STRING("polymorphicIdValue", m_polymorphicIdValue)
- FORMAT_NONEMPTY_STRING("targetType", m_targetType)
- FORMAT_NONEMPTY_STRING("hash", m_hashFunction)
- FORMAT_LIST_SIZE("addedFunctions", m_addedFunctions)
- formatList(d, "functionMods", m_functionMods, ", ");
- FORMAT_LIST_SIZE("fieldMods", m_fieldMods)
-}
-
-void TypedefEntry::formatDebug(QDebug &d) const
-{
- ComplexTypeEntry::formatDebug(d);
- d << ", sourceType=\"" << m_sourceType << '"'
- << ", source=" << m_source << ", target=" << m_target;
-}
-
-void EnumTypeEntry::formatDebug(QDebug &d) const
-{
- TypeEntry::formatDebug(d);
- if (m_flags)
- d << ", flags=(" << m_flags << ')';
-}
-
-void NamespaceTypeEntry::formatDebug(QDebug &d) const
-{
- ComplexTypeEntry::formatDebug(d);
- auto pattern = m_filePattern.pattern();
- FORMAT_NONEMPTY_STRING("pattern", pattern)
- d << ",visibility=" << m_visibility;
- if (m_inlineNamespace)
- d << "[inline]";
-}
-
-void ContainerTypeEntry::formatDebug(QDebug &d) const
-{
- ComplexTypeEntry::formatDebug(d);
- d << ", type=" << m_containerKind << ",\"" << typeName() << '"';
-}
-
-void SmartPointerTypeEntry::formatDebug(QDebug &d) const
-{
- ComplexTypeEntry::formatDebug(d);
- if (!m_instantiations.isEmpty()) {
- d << ", instantiations[" << m_instantiations.size() << "]=(";
- for (auto i : m_instantiations)
- d << i->name() << ',';
- d << ')';
- }
-}
-
-QDebug operator<<(QDebug d, const TypeEntry *te)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "TypeEntry(";
- if (te)
- te->formatDebug(d);
- else
- d << '0';
- d << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const TemplateEntry *te)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "TemplateEntry(";
- if (te) {
- d << '"' << te->name() << '"';
- } else {
- d << '0';
- }
- d << ')';
- return d;
-}
-
-void TypeDatabase::formatDebug(QDebug &d) const
-{
- d << "TypeDatabase("
- << "entries[" << m_entries.size() << "]=";
- for (auto it = m_entries.cbegin(), end = m_entries.cend(); it != end; ++it)
- d << " " << it.value() << '\n';
- if (!m_templates.isEmpty()) {
- d << "templates[" << m_templates.size() << "]=(";
- const auto begin = m_templates.cbegin();
- for (auto it = begin, end = m_templates.cend(); it != end; ++it) {
- if (it != begin)
- d << ", ";
- d << it.value();
- }
- d << ")\n";
- }
- if (!m_flagsEntries.isEmpty()) {
- d << "flags[" << m_flagsEntries.size() << "]=(";
- const auto begin = m_flagsEntries.cbegin();
- for (auto it = begin, end = m_flagsEntries.cend(); it != end; ++it) {
- if (it != begin)
- d << ", ";
- d << it.value();
- }
- d << ")\n";
- }
- d <<"\nglobalUserFunctions=" << m_globalUserFunctions << '\n';
- formatList(d, "globalFunctionMods", m_functionMods, '\n');
- d << ')';
-}
-
-QDebug operator<<(QDebug d, const TypeDatabase &db)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- db.formatDebug(d);
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
diff --git a/sources/shiboken2/ApiExtractor/typedatabase.h b/sources/shiboken2/ApiExtractor/typedatabase.h
deleted file mode 100644
index 7651d6b7b..000000000
--- a/sources/shiboken2/ApiExtractor/typedatabase.h
+++ /dev/null
@@ -1,222 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TYPEDATABASE_H
-#define TYPEDATABASE_H
-
-#include "apiextractormacros.h"
-#include "include.h"
-#include "typedatabase_typedefs.h"
-#include "typesystem_enums.h"
-#include "typesystem_typedefs.h"
-
-#include <QtCore/QRegularExpression>
-#include <QtCore/QStringList>
-#include <QtCore/QVersionNumber>
-
-QT_FORWARD_DECLARE_CLASS(QIODevice)
-
-class ComplexTypeEntry;
-class ContainerTypeEntry;
-class FlagsTypeEntry;
-class FunctionTypeEntry;
-class NamespaceTypeEntry;
-class ObjectTypeEntry;
-class TemplateEntry;
-class TypeEntry;
-
-struct TypeRejection;
-
-QT_FORWARD_DECLARE_CLASS(QDebug)
-
-int getMaxTypeIndex();
-
-class ContainerTypeEntry;
-class PrimitiveTypeEntry;
-class TypeSystemTypeEntry;
-
-struct VersionRange
-{
- bool isNull() const
- {
- return since.majorVersion() == 0 && since.minorVersion() == 0
- && until.majorVersion() == 9999 && until.minorVersion() == 9999;
- }
-
- QVersionNumber since{0, 0};
- QVersionNumber until{9999, 9999};
-};
-
-class TypeDatabase
-{
- TypeDatabase();
- Q_DISABLE_COPY(TypeDatabase)
-public:
- ~TypeDatabase();
-
- /**
- * Return the type system instance.
- * \param newInstance This parameter is useful just for unit testing, because singletons causes
- * too many side effects on unit testing.
- */
- static TypeDatabase *instance(bool newInstance = false);
-
- static QString normalizedSignature(const QString &signature);
-
- QStringList requiredTargetImports() const;
-
- void addRequiredTargetImport(const QString &moduleName);
-
- void addTypesystemPath(const QString &typesystem_paths);
-
- IncludeList extraIncludes(const QString &className) const;
-
- const QByteArrayList &systemIncludes() const { return m_systemIncludes; }
- void addSystemInclude(const QString &name);
-
- void addInlineNamespaceLookups(const NamespaceTypeEntry *n);
-
- PrimitiveTypeEntry *findPrimitiveType(const QString &name) const;
- ComplexTypeEntry *findComplexType(const QString &name) const;
- ObjectTypeEntry *findObjectType(const QString &name) const;
- NamespaceTypeEntryList findNamespaceTypes(const QString &name) const;
- NamespaceTypeEntry *findNamespaceType(const QString &name, const QString &fileName = QString()) const;
- ContainerTypeEntry *findContainerType(const QString &name) const;
- FunctionTypeEntry *findFunctionType(const QString &name) const;
- const TypeSystemTypeEntry *findTypeSystemType(const QString &name) const;
- const TypeSystemTypeEntry *defaultTypeSystemType() const;
- QString defaultPackageName() const;
-
- TypeEntry *findType(const QString &name) const;
- TypeEntries findTypes(const QString &name) const;
- TypeEntries findCppTypes(const QString &name) const;
-
- const TypeEntryMultiMap &entries() const { return m_entries; }
- const TypedefEntryMap &typedefEntries() const { return m_typedefEntries; }
-
- PrimitiveTypeEntryList primitiveTypes() const;
-
- ContainerTypeEntryList containerTypes() const;
-
- void addRejection(const TypeRejection &);
- bool isClassRejected(const QString &className, QString *reason = nullptr) const;
- bool isFunctionRejected(const QString &className, const QString &functionName,
- QString *reason = nullptr) const;
- bool isFieldRejected(const QString &className, const QString &fieldName,
- QString *reason = nullptr) const;
- bool isEnumRejected(const QString &className, const QString &enumName,
- QString *reason = nullptr) const;
- bool isArgumentTypeRejected(const QString &className, const QString &typeName,
- QString *reason = nullptr) const;
- bool isReturnTypeRejected(const QString &className, const QString &typeName,
- QString *reason = nullptr) const;
-
- bool addType(TypeEntry *e, QString *errorMessage = nullptr);
- ConstantValueTypeEntry *addConstantValueTypeEntry(const QString &value,
- const TypeEntry *parent);
- void addTypeSystemType(const TypeSystemTypeEntry *e);
-
- FlagsTypeEntry *findFlagsType(const QString &name) const;
- void addFlagsType(FlagsTypeEntry *fte);
-
- TemplateEntry *findTemplate(const QString &name) const { return m_templates[name]; }
-
- void addTemplate(TemplateEntry *t);
-
- AddedFunctionList globalUserFunctions() const { return m_globalUserFunctions; }
-
- void addGlobalUserFunctions(const AddedFunctionList &functions);
-
- AddedFunctionList findGlobalUserFunctions(const QString &name) const;
-
- void addGlobalUserFunctionModifications(const FunctionModificationList &functionModifications);
-
- FunctionModificationList functionModifications(const QString &signature) const;
-
- void setSuppressWarnings(bool on) { m_suppressWarnings = on; }
-
- bool addSuppressedWarning(const QString &warning, QString *errorMessage);
-
- bool isSuppressedWarning(const QString &s) const;
-
- static QString globalNamespaceClassName(const TypeEntry *te);
-
- bool parseFile(const QString &filename, bool generate = true);
- bool parseFile(const QString &filename, const QString &currentPath, bool generate);
-
- bool parseFile(QIODevice *device, bool generate = true);
-
- static bool setApiVersion(const QString &package, const QString &version);
- static void clearApiVersions();
-
- static bool checkApiVersion(const QString &package, const VersionRange &vr);
-
- bool hasDroppedTypeEntries() const { return !m_dropTypeEntries.isEmpty(); }
-
- bool shouldDropTypeEntry(const QString &fullTypeName) const;
-
- void setDropTypeEntries(QStringList dropTypeEntries);
-
- QString modifiedTypesystemFilepath(const QString &tsFile, const QString &currentPath = QString()) const;
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const;
-#endif
-private:
- TypeEntryMultiMapConstIteratorRange findTypeRange(const QString &name) const;
- template <class Predicate>
- TypeEntries findTypesHelper(const QString &name, Predicate pred) const;
- TypeEntry *resolveTypeDefEntry(TypedefEntry *typedefEntry, QString *errorMessage);
-
- bool m_suppressWarnings = true;
- TypeEntryMultiMap m_entries; // Contains duplicate entries (cf addInlineNamespaceLookups).
- TypeEntryMap m_flagsEntries;
- TypedefEntryMap m_typedefEntries;
- TemplateEntryMap m_templates;
- QVector<QRegularExpression> m_suppressedWarnings;
- QVector<const TypeSystemTypeEntry *> m_typeSystemEntries; // maintain order, default is first.
-
- AddedFunctionList m_globalUserFunctions;
- FunctionModificationList m_functionMods;
-
- QStringList m_requiredTargetImports;
-
- QStringList m_typesystemPaths;
- QHash<QString, bool> m_parsedTypesystemFiles;
-
- QVector<TypeRejection> m_rejections;
-
- QStringList m_dropTypeEntries;
- QByteArrayList m_systemIncludes;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const TypeEntry *te);
-QDebug operator<<(QDebug d, const TypeDatabase &db);
-#endif
-#endif // TYPEDATABASE_H
diff --git a/sources/shiboken2/ApiExtractor/typedatabase_typedefs.h b/sources/shiboken2/ApiExtractor/typedatabase_typedefs.h
deleted file mode 100644
index f9e6c669e..000000000
--- a/sources/shiboken2/ApiExtractor/typedatabase_typedefs.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TYPEDATABASE_TYPEDEFS_H
-#define TYPEDATABASE_TYPEDEFS_H
-
-#include <QtCore/QMultiMap>
-#include <QtCore/QString>
-#include <QtCore/QVector>
-
-class ConstantValueTypeEntry;
-class ContainerTypeEntry;
-class NamespaceTypeEntry;
-class PrimitiveTypeEntry;
-class TemplateEntry;
-class TypeEntry;
-class TypedefEntry;
-
-using TypeEntryList = QVector<TypeEntry *>;
-using TemplateEntryMap =QMap<QString, TemplateEntry *>;
-
-template <class Key, class Value>
-struct QMultiMapConstIteratorRange // A range of iterator for a range-based for loop
-{
- using ConstIterator = typename QMultiMap<Key, Value>::const_iterator;
-
- ConstIterator begin() const { return m_begin; }
- ConstIterator end() const { return m_end; }
-
- ConstIterator m_begin;
- ConstIterator m_end;
-};
-
-using TypeEntryMultiMap = QMultiMap<QString, TypeEntry *>;
-using TypeEntryMultiMapConstIteratorRange = QMultiMapConstIteratorRange<QString, TypeEntry *>;
-
-using TypeEntryMap = QMap<QString, TypeEntry *>;
-using TypedefEntryMap = QMap<QString, TypedefEntry *>;
-
-using ContainerTypeEntryList = QVector<const ContainerTypeEntry *>;
-using NamespaceTypeEntryList = QVector<NamespaceTypeEntry *>;
-using PrimitiveTypeEntryList = QVector<const PrimitiveTypeEntry *>;
-
-#endif // TYPEDATABASE_TYPEDEFS_H
diff --git a/sources/shiboken2/ApiExtractor/typeparser.cpp b/sources/shiboken2/ApiExtractor/typeparser.cpp
deleted file mode 100644
index c440fb66d..000000000
--- a/sources/shiboken2/ApiExtractor/typeparser.cpp
+++ /dev/null
@@ -1,305 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "typeparser.h"
-#include <codemodel.h>
-
-#include <QtCore/QDebug>
-#include <QtCore/QStack>
-#include <QtCore/QTextStream>
-
-class Scanner
-{
-public:
- enum Token {
- StarToken,
- AmpersandToken,
- LessThanToken,
- ColonToken,
- CommaToken,
- OpenParenToken,
- CloseParenToken,
- SquareBegin,
- SquareEnd,
- GreaterThanToken,
-
- ConstToken,
- VolatileToken,
- Identifier,
- NoToken,
- InvalidToken
- };
-
- Scanner(const QString &s)
- : m_pos(0), m_length(s.length()), m_tokenStart(-1), m_chars(s.constData())
- {
- }
-
- Token nextToken(QString *errorMessage = Q_NULLPTR);
- QString identifier() const;
-
- QString msgParseError(const QString &why) const;
-
-private:
- int m_pos;
- int m_length;
- int m_tokenStart;
- const QChar *m_chars;
-};
-
-QString Scanner::identifier() const
-{
- return QString(m_chars + m_tokenStart, m_pos - m_tokenStart);
-}
-
-Scanner::Token Scanner::nextToken(QString *errorMessage)
-{
- Token tok = NoToken;
-
- // remove whitespace
- while (m_pos < m_length && m_chars[m_pos] == QLatin1Char(' '))
- ++m_pos;
-
- m_tokenStart = m_pos;
-
- while (m_pos < m_length) {
-
- const QChar &c = m_chars[m_pos];
-
- if (tok == NoToken) {
- switch (c.toLatin1()) {
- case '*': tok = StarToken; break;
- case '&': tok = AmpersandToken; break;
- case '<': tok = LessThanToken; break;
- case '>': tok = GreaterThanToken; break;
- case ',': tok = CommaToken; break;
- case '(': tok = OpenParenToken; break;
- case ')': tok = CloseParenToken; break;
- case '[': tok = SquareBegin; break;
- case ']' : tok = SquareEnd; break;
- case ':':
- tok = ColonToken;
- Q_ASSERT(m_pos + 1 < m_length);
- ++m_pos;
- break;
- default:
- if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
- tok = Identifier;
- } else {
- QString message;
- QTextStream (&message) << ": Unrecognized character in lexer at "
- << m_pos << " : '" << c << '\'';
- message = msgParseError(message);
- if (errorMessage)
- *errorMessage = message;
- else
- qWarning().noquote().nospace() << message;
- return InvalidToken;
- }
- break;
- }
- }
-
- if (tok <= GreaterThanToken) {
- ++m_pos;
- break;
- }
-
- if (tok == Identifier) {
- if (c.isLetterOrNumber() || c == QLatin1Char('_'))
- ++m_pos;
- else
- break;
- }
- }
-
- if (tok == Identifier) {
- switch (m_pos - m_tokenStart) {
- case 5:
- if (m_chars[m_tokenStart] == QLatin1Char('c')
- && m_chars[m_tokenStart + 1] == QLatin1Char('o')
- && m_chars[m_tokenStart + 2] == QLatin1Char('n')
- && m_chars[m_tokenStart + 3] == QLatin1Char('s')
- && m_chars[m_tokenStart + 4] == QLatin1Char('t')) {
- tok = ConstToken;
- }
- break;
- case 8:
- if (m_chars[m_tokenStart] == QLatin1Char('v')
- && m_chars[m_tokenStart + 1] == QLatin1Char('o')
- && m_chars[m_tokenStart + 2] == QLatin1Char('l')
- && m_chars[m_tokenStart + 3] == QLatin1Char('a')
- && m_chars[m_tokenStart + 4] == QLatin1Char('t')
- && m_chars[m_tokenStart + 5] == QLatin1Char('i')
- && m_chars[m_tokenStart + 6] == QLatin1Char('l')
- && m_chars[m_tokenStart + 7] == QLatin1Char('e')) {
- tok = VolatileToken;
- }
- break;
- }
- }
-
- return tok;
-
-}
-
-QString Scanner::msgParseError(const QString &why) const
-{
- return QStringLiteral("TypeParser: Unable to parse \"")
- + QString(m_chars, m_length) + QStringLiteral("\": ") + why;
-}
-
-TypeInfo TypeParser::parse(const QString &str, QString *errorMessage)
-{
- Scanner scanner(str);
-
- TypeInfo info;
- QStack<TypeInfo *> stack;
- stack.push(&info);
-
- bool colon_prefix = false;
- bool in_array = false;
- QString array;
- bool seenStar = false;
-
- Scanner::Token tok = scanner.nextToken(errorMessage);
- while (tok != Scanner::NoToken) {
- if (tok == Scanner::InvalidToken)
- return TypeInfo();
-
-// switch (tok) {
-// case Scanner::StarToken: printf(" - *\n"); break;
-// case Scanner::AmpersandToken: printf(" - &\n"); break;
-// case Scanner::LessThanToken: printf(" - <\n"); break;
-// case Scanner::GreaterThanToken: printf(" - >\n"); break;
-// case Scanner::ColonToken: printf(" - ::\n"); break;
-// case Scanner::CommaToken: printf(" - ,\n"); break;
-// case Scanner::ConstToken: printf(" - const\n"); break;
-// case Scanner::SquareBegin: printf(" - [\n"); break;
-// case Scanner::SquareEnd: printf(" - ]\n"); break;
-// case Scanner::Identifier: printf(" - '%s'\n", qPrintable(scanner.identifier())); break;
-// default:
-// break;
-// }
-
- switch (tok) {
-
- case Scanner::StarToken:
- seenStar = true;
- stack.top()->addIndirection(Indirection::Pointer);
- break;
-
- case Scanner::AmpersandToken:
- switch (stack.top()->referenceType()) {
- case NoReference:
- stack.top()->setReferenceType(LValueReference);
- break;
- case LValueReference:
- stack.top()->setReferenceType(RValueReference);
- break;
- case RValueReference:
- const QString message = scanner.msgParseError(QStringLiteral("Too many '&' qualifiers"));
- if (errorMessage)
- *errorMessage = message;
- else
- qWarning().noquote().nospace() << message;
- return TypeInfo();
- }
- break;
- case Scanner::LessThanToken:
- stack.top()->m_instantiations << TypeInfo();
- stack.push(&stack.top()->m_instantiations.last());
- break;
-
- case Scanner::CommaToken:
- stack.pop();
- stack.top()->m_instantiations << TypeInfo();
- stack.push(&stack.top()->m_instantiations.last());
- break;
-
- case Scanner::GreaterThanToken:
- stack.pop();
- break;
-
- case Scanner::ColonToken:
- colon_prefix = true;
- break;
-
- case Scanner::ConstToken:
- if (seenStar) { // "int *const": Last indirection is const.
- Q_ASSERT(!stack.top()->m_indirections.isEmpty());
- *stack.top()->m_indirections.rbegin() = Indirection::ConstPointer;
- } else {
- stack.top()->m_constant = true;
- }
- break;
-
- case Scanner::VolatileToken:
- stack.top()->m_volatile = true;
- break;
-
- case Scanner::OpenParenToken: // function pointers not supported
- case Scanner::CloseParenToken: {
- const QString message = scanner.msgParseError(QStringLiteral("Function pointers are not supported"));
- if (errorMessage)
- *errorMessage = message;
- else
- qWarning().noquote().nospace() << message;
- return TypeInfo();
- }
-
- case Scanner::Identifier:
- if (in_array) {
- array = scanner.identifier();
- } else if (colon_prefix || stack.top()->m_qualifiedName.isEmpty()) {
- stack.top()->m_qualifiedName << scanner.identifier();
- colon_prefix = false;
- } else {
- stack.top()->m_qualifiedName.last().append(QLatin1Char(' ') + scanner.identifier());
- }
- break;
-
- case Scanner::SquareBegin:
- in_array = true;
- break;
-
- case Scanner::SquareEnd:
- in_array = false;
- stack.top()->m_arrayElements += array;
- break;
-
-
- default:
- break;
- }
-
- tok = scanner.nextToken();
- }
-
- return info;
-}
diff --git a/sources/shiboken2/ApiExtractor/typeparser.h b/sources/shiboken2/ApiExtractor/typeparser.h
deleted file mode 100644
index 3b538017a..000000000
--- a/sources/shiboken2/ApiExtractor/typeparser.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TYPEPARSER_H
-#define TYPEPARSER_H
-
-#include "parser/codemodel_enums.h"
-
-#include <QtCore/QString>
-#include <QtCore/QVector>
-
-class TypeInfo;
-
-class TypeParser
-{
-public:
- static TypeInfo parse(const QString &str, QString *errorMessage = nullptr);
-};
-
-#endif // TYPEPARSER_H
diff --git a/sources/shiboken2/ApiExtractor/typesystem.cpp b/sources/shiboken2/ApiExtractor/typesystem.cpp
deleted file mode 100644
index 920da9e10..000000000
--- a/sources/shiboken2/ApiExtractor/typesystem.cpp
+++ /dev/null
@@ -1,1186 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "typesystem.h"
-#include "typedatabase.h"
-#include "messages.h"
-#include <QtCore/QDebug>
-#include <QtCore/QRegularExpression>
-#include <QtCore/QSet>
-
-#include <algorithm>
-
-static QString strings_Object = QLatin1String("Object");
-static QString strings_String = QLatin1String("String");
-static QString strings_char = QLatin1String("char");
-static QString strings_jchar = QLatin1String("jchar");
-static QString strings_jobject = QLatin1String("jobject");
-
-static inline QString callOperator() { return QStringLiteral("operator()"); }
-
-PrimitiveTypeEntry::PrimitiveTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent) :
- TypeEntry(entryName, PrimitiveType, vr, parent),
- m_preferredTargetLangType(true)
-{
-}
-
-QString PrimitiveTypeEntry::targetLangApiName() const
-{
- return m_targetLangApiName;
-}
-
-PrimitiveTypeEntry *PrimitiveTypeEntry::basicReferencedTypeEntry() const
-{
- if (!m_referencedTypeEntry)
- return nullptr;
-
- PrimitiveTypeEntry *baseReferencedTypeEntry = m_referencedTypeEntry->basicReferencedTypeEntry();
- return baseReferencedTypeEntry ? baseReferencedTypeEntry : m_referencedTypeEntry;
-}
-
-TypeEntry *PrimitiveTypeEntry::clone() const
-{
- return new PrimitiveTypeEntry(*this);
-}
-
-PrimitiveTypeEntry::PrimitiveTypeEntry(const PrimitiveTypeEntry &) = default;
-
-CodeSnipList TypeEntry::codeSnips() const
-{
- return m_codeSnips;
-}
-
-void TypeEntry::addExtraInclude(const Include &newInclude)
-{
- if (!m_extraIncludes.contains(newInclude))
- m_extraIncludes.append(newInclude);
-}
-
-QString Modification::accessModifierString() const
-{
- if (isPrivate()) return QLatin1String("private");
- if (isProtected()) return QLatin1String("protected");
- if (isPublic()) return QLatin1String("public");
- if (isFriendly()) return QLatin1String("friendly");
- return QString();
-}
-
-FunctionModificationList ComplexTypeEntry::functionModifications(const QString &signature) const
-{
- FunctionModificationList lst;
- for (int i = 0; i < m_functionMods.count(); ++i) {
- const FunctionModification &mod = m_functionMods.at(i);
- if (mod.matches(signature))
- lst << mod;
- }
- return lst;
-}
-
-FieldModification ComplexTypeEntry::fieldModification(const QString &name) const
-{
- for (const auto &fieldMod : m_fieldMods) {
- if (fieldMod.name == name)
- return fieldMod;
- }
- FieldModification mod;
- mod.name = name;
- mod.modifiers = FieldModification::Readable | FieldModification::Writable;
- return mod;
-}
-
-void ComplexTypeEntry::setDefaultConstructor(const QString& defaultConstructor)
-{
- m_defaultConstructor = defaultConstructor;
-}
-QString ComplexTypeEntry::defaultConstructor() const
-{
- return m_defaultConstructor;
-}
-bool ComplexTypeEntry::hasDefaultConstructor() const
-{
- return !m_defaultConstructor.isEmpty();
-}
-
-TypeEntry *ComplexTypeEntry::clone() const
-{
- return new ComplexTypeEntry(*this);
-}
-
-// Take over parameters relevant for typedefs
-void ComplexTypeEntry::useAsTypedef(const ComplexTypeEntry *source)
-{
- TypeEntry::useAsTypedef(source);
- m_qualifiedCppName = source->m_qualifiedCppName;
- m_targetType = source->m_targetType;
-}
-
-ComplexTypeEntry::ComplexTypeEntry(const ComplexTypeEntry &) = default;
-
-QString ContainerTypeEntry::qualifiedCppName() const
-{
- if (m_containerKind == StringListContainer)
- return QLatin1String("QStringList");
- return ComplexTypeEntry::qualifiedCppName();
-}
-
-TypeEntry *ContainerTypeEntry::clone() const
-{
- return new ContainerTypeEntry(*this);
-}
-
-ContainerTypeEntry::ContainerTypeEntry(const ContainerTypeEntry &) = default;
-
-QString EnumTypeEntry::targetLangQualifier() const
-{
- const QString q = qualifier();
- if (!q.isEmpty()) {
- if (auto te = TypeDatabase::instance()->findType(q))
- return te->targetLangName();
- }
- return q;
-}
-
-QString EnumTypeEntry::qualifier() const
-{
- auto parentEntry = parent();
- return parentEntry && parentEntry->type() != TypeEntry::TypeSystemType ?
- parentEntry->name() : QString();
-}
-
-QString EnumTypeEntry::targetLangApiName() const
-{
- return QLatin1String("jint");
-}
-
-QString FlagsTypeEntry::targetLangApiName() const
-{
- return QLatin1String("jint");
-}
-
-TypeEntry *EnumTypeEntry::clone() const
-{
- return new EnumTypeEntry(*this);
-}
-
-EnumTypeEntry::EnumTypeEntry(const EnumTypeEntry &) = default;
-
-TypeEntry *FlagsTypeEntry::clone() const
-{
- return new FlagsTypeEntry(*this);
-}
-
-FlagsTypeEntry::FlagsTypeEntry(const FlagsTypeEntry &) = default;
-
-QString TemplateInstance::expandCode() const
-{
- TemplateEntry *templateEntry = TypeDatabase::instance()->findTemplate(m_name);
- if (!templateEntry)
- qFatal("<insert-template> referring to non-existing template '%s'.", qPrintable(m_name));
-
- QString code = templateEntry->code();
- for (auto it = replaceRules.cbegin(), end = replaceRules.cend(); it != end; ++it)
- code.replace(it.key(), it.value());
- while (!code.isEmpty() && code.at(code.size() - 1).isSpace())
- code.chop(1);
- QString result = QLatin1String("// TEMPLATE - ") + m_name + QLatin1String(" - START");
- if (!code.startsWith(QLatin1Char('\n')))
- result += QLatin1Char('\n');
- result += code;
- result += QLatin1String("\n// TEMPLATE - ") + m_name + QLatin1String(" - END");
- return result;
-}
-
-
-QString CodeSnipAbstract::code() const
-{
- QString res;
- for (const CodeSnipFragment &codeFrag : codeList)
- res.append(codeFrag.code());
-
- return res;
-}
-
-QString CodeSnipFragment::code() const
-{
- return m_instance ? m_instance->expandCode() : m_code;
-}
-
-bool FunctionModification::setSignature(const QString &s, QString *errorMessage)
-{
- if (s.startsWith(QLatin1Char('^'))) {
- m_signaturePattern.setPattern(s);
- if (!m_signaturePattern.isValid()) {
- if (errorMessage) {
- *errorMessage = QLatin1String("Invalid signature pattern: \"")
- + s + QLatin1String("\": ") + m_signaturePattern.errorString();
- }
- return false;
- }
- } else {
- m_signature = s;
- }
- return true;
-}
-
-QString FunctionModification::toString() const
-{
- QString str = signature() + QLatin1String("->");
- if (modifiers & AccessModifierMask) {
- switch (modifiers & AccessModifierMask) {
- case Private: str += QLatin1String("private"); break;
- case Protected: str += QLatin1String("protected"); break;
- case Public: str += QLatin1String("public"); break;
- case Friendly: str += QLatin1String("friendly"); break;
- }
- }
-
- if (modifiers & Final) str += QLatin1String("final");
- if (modifiers & NonFinal) str += QLatin1String("non-final");
-
- if (modifiers & Readable) str += QLatin1String("readable");
- if (modifiers & Writable) str += QLatin1String("writable");
-
- if (modifiers & CodeInjection) {
- for (const CodeSnip &s : snips) {
- str += QLatin1String("\n//code injection:\n");
- str += s.code();
- }
- }
-
- if (modifiers & Rename) str += QLatin1String("renamed:") + renamedToName;
-
- if (modifiers & Deprecated) str += QLatin1String("deprecate");
-
- if (modifiers & ReplaceExpression) str += QLatin1String("replace-expression");
-
- return str;
-}
-
-static AddedFunction::TypeInfo parseType(const QString& signature,
- int startPos = 0, int *endPos = nullptr,
- QString *argumentName = nullptr)
-{
- AddedFunction::TypeInfo result;
- static const QRegularExpression regex(QLatin1String("\\w"));
- Q_ASSERT(regex.isValid());
- int length = signature.length();
- int start = signature.indexOf(regex, startPos);
- if (start == -1) {
- if (signature.midRef(startPos + 1, 3) == QLatin1String("...")) { // varargs
- if (endPos)
- *endPos = startPos + 4;
- result.name = QLatin1String("...");
- } else { // error
- if (endPos)
- *endPos = length;
- }
- return result;
- }
-
- int cantStop = 0;
- QString paramString;
- QChar c;
- int i = start;
- for (; i < length; ++i) {
- c = signature[i];
- if (c == QLatin1Char('<'))
- cantStop++;
- if (c == QLatin1Char('>'))
- cantStop--;
- if (cantStop < 0)
- break; // FIXME: report error?
- if ((c == QLatin1Char(')') || c == QLatin1Char(',')) && !cantStop)
- break;
- paramString += signature[i];
- }
- if (endPos)
- *endPos = i;
-
- // Check default value
- if (paramString.contains(QLatin1Char('='))) {
- QStringList lst = paramString.split(QLatin1Char('='));
- paramString = lst[0].trimmed();
- result.defaultValue = lst[1].trimmed();
- }
-
- // check constness
- if (paramString.startsWith(QLatin1String("const "))) {
- result.isConstant = true;
- paramString.remove(0, sizeof("const")/sizeof(char));
- paramString = paramString.trimmed();
- }
-
- // Extract argument name from "T<bla,blub>* @foo@"
- const int nameStartPos = paramString.indexOf(QLatin1Char('@'));
- if (nameStartPos != -1) {
- const int nameEndPos = paramString.indexOf(QLatin1Char('@'), nameStartPos + 1);
- if (nameEndPos > nameStartPos) {
- if (argumentName)
- *argumentName = paramString.mid(nameStartPos + 1, nameEndPos - nameStartPos - 1);
- paramString.remove(nameStartPos, nameEndPos - nameStartPos + 1);
- paramString = paramString.trimmed();
- }
- }
-
- // check reference
- if (paramString.endsWith(QLatin1Char('&'))) {
- result.isReference = true;
- paramString.chop(1);
- paramString = paramString.trimmed();
- }
- // check Indirections
- while (paramString.endsWith(QLatin1Char('*'))) {
- result.indirections++;
- paramString.chop(1);
- paramString = paramString.trimmed();
- }
- result.name = paramString;
-
- return result;
-}
-
-AddedFunction::AddedFunction(QString signature, const QString &returnType) :
- m_access(Public)
-{
- Q_ASSERT(!returnType.isEmpty());
- m_returnType = parseType(returnType);
- signature = signature.trimmed();
- // Skip past "operator()(...)"
- const int parenStartPos = signature.startsWith(callOperator())
- ? callOperator().size() : 0;
- int endPos = signature.indexOf(QLatin1Char('('), parenStartPos);
- if (endPos < 0) {
- m_isConst = false;
- m_name = signature;
- } else {
- m_name = signature.left(endPos).trimmed();
- int signatureLength = signature.length();
- while (endPos < signatureLength) {
- QString argumentName;
- TypeInfo arg = parseType(signature, endPos, &endPos, &argumentName);
- if (!arg.name.isEmpty())
- m_arguments.append({argumentName, arg});
- // end of parameters...
- if (endPos >= signatureLength || signature[endPos] == QLatin1Char(')'))
- break;
- }
- // is const?
- m_isConst = signature.rightRef(signatureLength - endPos).contains(QLatin1String("const"));
- }
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const ReferenceCount &r)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "ReferenceCount(" << r.varName << ", action=" << r.action << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const CodeSnip &s)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "CodeSnip(language=" << s.language << ", position=" << s.position << ", \"";
- for (const auto &f : s.codeList) {
- const QString &code = f.code();
- const auto lines = code.splitRef(QLatin1Char('\n'));
- for (int i = 0, size = lines.size(); i < size; ++i) {
- if (i)
- d << "\\n";
- d << lines.at(i).trimmed();
- }
- }
- d << '"';
- if (!s.argumentMap.isEmpty()) {
- d << ", argumentMap{";
- for (auto it = s.argumentMap.cbegin(), end = s.argumentMap.cend(); it != end; ++it)
- d << it.key() << "->\"" << it.value() << '"';
- d << '}';
- }
- d << ')';
- return d;
-}
-
-void Modification::formatDebug(QDebug &d) const
-{
- d << "modifiers=" << Qt::hex << Qt::showbase << modifiers << Qt::noshowbase << Qt::dec;
- if (removal)
- d << ", removal";
- if (!renamedToName.isEmpty())
- d << ", renamedToName=\"" << renamedToName << '"';
-}
-
-void FunctionModification::formatDebug(QDebug &d) const
-{
- if (m_signature.isEmpty())
- d << "pattern=\"" << m_signaturePattern.pattern();
- else
- d << "signature=\"" << m_signature;
- d << "\", ";
- Modification::formatDebug(d);
- if (!association.isEmpty())
- d << ", association=\"" << association << '"';
- if (m_allowThread != TypeSystem::AllowThread::Unspecified)
- d << ", allowThread=" << int(m_allowThread);
- if (m_thread)
- d << ", thread";
- if (m_exceptionHandling != TypeSystem::ExceptionHandling::Unspecified)
- d << ", exceptionHandling=" << int(m_exceptionHandling);
- if (!snips.isEmpty())
- d << ", snips=(" << snips << ')';
- if (!argument_mods.isEmpty())
- d << ", argument_mods=(" << argument_mods << ')';
-}
-
-QDebug operator<<(QDebug d, const ArgumentOwner &a)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "ArgumentOwner(index=" << a.index << ", action=" << a.action << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const ArgumentModification &a)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "ArgumentModification(index=" << a.index;
- if (a.removedDefaultExpression)
- d << ", removedDefaultExpression";
- if (a.removed)
- d << ", removed";
- if (a.noNullPointers)
- d << ", noNullPointers";
- if (a.array)
- d << ", array";
- if (!a.referenceCounts.isEmpty())
- d << ", referenceCounts=" << a.referenceCounts;
- if (!a.modified_type.isEmpty())
- d << ", modified_type=\"" << a.modified_type << '"';
- if (!a.replace_value.isEmpty())
- d << ", replace_value=\"" << a.replace_value << '"';
- if (!a.replacedDefaultExpression.isEmpty())
- d << ", replacedDefaultExpression=\"" << a.replacedDefaultExpression << '"';
- if (!a.ownerships.isEmpty())
- d << ", ownerships=" << a.ownerships;
- if (!a.renamed_to.isEmpty())
- d << ", renamed_to=\"" << a.renamed_to << '"';
- d << ", owner=" << a.owner << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const FunctionModification &fm)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "FunctionModification(";
- fm.formatDebug(d);
- d << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const AddedFunction::TypeInfo &ti)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "TypeInfo(";
- if (ti.isConstant)
- d << "const";
- if (ti.indirections)
- d << QByteArray(ti.indirections, '*');
- if (ti.isReference)
- d << " &";
- d << ti.name;
- if (!ti.defaultValue.isEmpty())
- d << " = " << ti.defaultValue;
- d << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const AddedFunction::Argument &a)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "Argument(";
- d << a.typeInfo;
- if (!a.name.isEmpty())
- d << ' ' << a.name;
- d << ')';
- return d;
-}
-
-QDebug operator<<(QDebug d, const AddedFunction &af)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "AddedFunction(";
- if (af.access() == AddedFunction::Protected)
- d << "protected";
- if (af.isStatic())
- d << " static";
- d << af.returnType() << ' ' << af.name() << '(' << af.arguments() << ')';
- if (af.isConstant())
- d << " const";
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
-
-AddedFunction::TypeInfo AddedFunction::TypeInfo::fromSignature(const QString& signature)
-{
- return parseType(signature);
-}
-
-static QString buildName(const QString &entryName, const TypeEntry *parent)
-{
- return parent == nullptr || parent->type() == TypeEntry::TypeSystemType
- ? entryName : parent->name() + QLatin1String("::") + entryName;
-}
-
-ComplexTypeEntry::ComplexTypeEntry(const QString &entryName, TypeEntry::Type t,
- const QVersionNumber &vr,
- const TypeEntry *parent) :
- TypeEntry(entryName, t, vr, parent),
- m_qualifiedCppName(buildName(entryName, parent)),
- m_polymorphicBase(false),
- m_genericClass(false),
- m_deleteInMainThread(false)
-{
-}
-
-bool ComplexTypeEntry::isComplex() const
-{
- return true;
-}
-
-QString ComplexTypeEntry::targetLangApiName() const
-{
- return strings_jobject;
-}
-
-QString ContainerTypeEntry::typeName() const
-{
- switch (m_containerKind) {
- case LinkedListContainer:
- return QLatin1String("linked-list");
- case ListContainer:
- return QLatin1String("list");
- case StringListContainer:
- return QLatin1String("string-list");
- case VectorContainer:
- return QLatin1String("vector");
- case StackContainer:
- return QLatin1String("stack");
- case QueueContainer:
- return QLatin1String("queue");
- case SetContainer:
- return QLatin1String("set");
- case MapContainer:
- return QLatin1String("map");
- case MultiMapContainer:
- return QLatin1String("multi-map");
- case HashContainer:
- return QLatin1String("hash");
- case MultiHashContainer:
- return QLatin1String("multi-hash");
- case PairContainer:
- return QLatin1String("pair");
- case NoContainer:
- default:
- return QLatin1String("?");
- }
-}
-
-static const QSet<QString> &primitiveCppTypes()
-{
- static QSet<QString> result;
- if (result.isEmpty()) {
- static const char *cppTypes[] = {
- "bool", "char", "double", "float", "int",
- "long", "long long", "short",
- "wchar_t"
- };
- for (const char *cppType : cppTypes)
- result.insert(QLatin1String(cppType));
- }
- return result;
-}
-
-void TypeEntry::setInclude(const Include &inc)
-{
- // This is a workaround for preventing double inclusion of the QSharedPointer implementation
- // header, which does not use header guards. In the previous parser this was not a problem
- // because the Q_QDOC define was set, and the implementation header was never included.
- if (inc.name().endsWith(QLatin1String("qsharedpointer_impl.h"))) {
- QString path = inc.name();
- path.remove(QLatin1String("_impl"));
- m_include = Include(inc.type(), path);
- } else {
- m_include = inc;
- }
-}
-
-bool TypeEntry::isCppPrimitive() const
-{
- if (!isPrimitive())
- return false;
-
- if (m_type == VoidType)
- return true;
-
- const PrimitiveTypeEntry *referencedType =
- static_cast<const PrimitiveTypeEntry *>(this)->basicReferencedTypeEntry();
- const QString &typeName = referencedType ? referencedType->name() : m_name;
- return typeName.contains(QLatin1Char(' ')) || primitiveCppTypes().contains(typeName);
-}
-
-TypeEntry::TypeEntry(const QString &entryName, TypeEntry::Type t, const QVersionNumber &vr,
- const TypeEntry *parent) :
- m_parent(parent),
- m_name(buildName(entryName, parent)),
- m_entryName(entryName),
- m_version(vr),
- m_type(t)
-{
-}
-
-TypeEntry::~TypeEntry()
-{
- delete m_customConversion;
-}
-
-bool TypeEntry::isChildOf(const TypeEntry *p) const
-{
- for (auto e = m_parent; e; e = e->parent()) {
- if (e == p)
- return true;
- }
- return false;
-}
-
-const TypeSystemTypeEntry *TypeEntry::typeSystemTypeEntry() const
-{
- for (auto e = this; e; e = e->parent()) {
- if (e->type() == TypeEntry::TypeSystemType)
- return static_cast<const TypeSystemTypeEntry *>(e);
- }
- return nullptr;
-}
-
-const TypeEntry *TypeEntry::targetLangEnclosingEntry() const
-{
- auto result = m_parent;
- while (result && result->type() != TypeEntry::TypeSystemType
- && !NamespaceTypeEntry::isVisibleScope(result)) {
- result = result->parent();
- }
- return result;
-}
-
-QString TypeEntry::targetLangName() const
-{
- if (m_cachedTargetLangName.isEmpty())
- m_cachedTargetLangName = buildTargetLangName();
- return m_cachedTargetLangName;
-}
-
-QString TypeEntry::buildTargetLangName() const
-{
- QString result = m_entryName;
- for (auto p = parent(); p && p->type() != TypeEntry::TypeSystemType; p = p->parent()) {
- if (NamespaceTypeEntry::isVisibleScope(p)) {
- if (!result.isEmpty())
- result.prepend(QLatin1Char('.'));
- QString n = p->m_entryName;
- n.replace(QLatin1String("::"), QLatin1String(".")); // Primitive types may have "std::"
- result.prepend(n);
- }
- }
- return result;
-}
-
-QString TypeEntry::targetLangEntryName() const
-{
- if (m_cachedTargetLangEntryName.isEmpty()) {
- m_cachedTargetLangEntryName = targetLangName();
- const int lastDot = m_cachedTargetLangEntryName.lastIndexOf(QLatin1Char('.'));
- if (lastDot != -1)
- m_cachedTargetLangEntryName.remove(0, lastDot + 1);
- }
- return m_cachedTargetLangEntryName;
-}
-
-QString TypeEntry::qualifiedTargetLangName() const
-{
- return targetLangPackage() + QLatin1Char('.') + targetLangName();
-}
-
-bool TypeEntry::hasCustomConversion() const
-{
- return m_customConversion != nullptr;
-}
-
-void TypeEntry::setCustomConversion(CustomConversion* customConversion)
-{
- m_customConversion = customConversion;
-}
-
-CustomConversion* TypeEntry::customConversion() const
-{
- return m_customConversion;
-}
-
-TypeEntry *TypeEntry::clone() const
-{
- return new TypeEntry(*this);
-}
-
-// Take over parameters relevant for typedefs
-void TypeEntry::useAsTypedef(const TypeEntry *source)
-{
- // XML Typedefs are in the global namespace for now.
- m_parent = source->typeSystemTypeEntry();
- m_entryName = source->m_entryName;
- m_name = source->m_name;
- m_targetLangPackage = source->m_targetLangPackage;
- m_codeGeneration = source->m_codeGeneration;
- m_version = source->m_version;
-}
-
-TypeEntry::TypeEntry(const TypeEntry &) = default;
-
-TypeSystemTypeEntry::TypeSystemTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent) :
- TypeEntry(entryName, TypeSystemType, vr, parent)
-{
-}
-
-TypeEntry *TypeSystemTypeEntry::clone() const
-{
- return new TypeSystemTypeEntry(*this);
-}
-
-TypeSystemTypeEntry::TypeSystemTypeEntry(const TypeSystemTypeEntry &) = default;
-
-VoidTypeEntry::VoidTypeEntry() :
- TypeEntry(QLatin1String("void"), VoidType, QVersionNumber(0, 0), nullptr)
-{
-}
-
-TypeEntry *VoidTypeEntry::clone() const
-{
- return new VoidTypeEntry(*this);
-}
-
-VoidTypeEntry::VoidTypeEntry(const VoidTypeEntry &) = default;
-
-VarargsTypeEntry::VarargsTypeEntry() :
- TypeEntry(QLatin1String("..."), VarargsType, QVersionNumber(0, 0), nullptr)
-{
-}
-
-TypeEntry *VarargsTypeEntry::clone() const
-{
- return new VarargsTypeEntry(*this);
-}
-
-VarargsTypeEntry::VarargsTypeEntry(const VarargsTypeEntry &) = default;
-
-TemplateArgumentEntry::TemplateArgumentEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent) :
- TypeEntry(entryName, TemplateArgumentType, vr, parent)
-{
-}
-
-TypeEntry *TemplateArgumentEntry::clone() const
-{
- return new TemplateArgumentEntry(*this);
-}
-
-TemplateArgumentEntry::TemplateArgumentEntry(const TemplateArgumentEntry &) = default;
-
-ArrayTypeEntry::ArrayTypeEntry(const TypeEntry *nested_type, const QVersionNumber &vr,
- const TypeEntry *parent) :
- TypeEntry(QLatin1String("Array"), ArrayType, vr, parent),
- m_nestedType(nested_type)
-{
- Q_ASSERT(m_nestedType);
-}
-
-QString ArrayTypeEntry::buildTargetLangName() const
-{
- return m_nestedType->targetLangName() + QLatin1String("[]");
-}
-
-QString ArrayTypeEntry::targetLangApiName() const
-{
- return m_nestedType->isPrimitive()
- ? m_nestedType->targetLangApiName() + QLatin1String("Array")
- : QLatin1String("jobjectArray");
-}
-
-TypeEntry *ArrayTypeEntry::clone() const
-{
- return new ArrayTypeEntry(*this);
-}
-
-ArrayTypeEntry::ArrayTypeEntry(const ArrayTypeEntry &) = default;
-
-EnumTypeEntry::EnumTypeEntry(const QString &entryName,
- const QVersionNumber &vr,
- const TypeEntry *parent) :
- TypeEntry(entryName, EnumType, vr, parent)
-{
-}
-
-EnumValueTypeEntry::EnumValueTypeEntry(const QString &name, const QString &value,
- const EnumTypeEntry *enclosingEnum,
- bool isScopedEnum,
- const QVersionNumber &vr) :
- TypeEntry(name, TypeEntry::EnumValue, vr,
- isScopedEnum ? enclosingEnum : enclosingEnum->parent()),
- m_value(value),
- m_enclosingEnum(enclosingEnum)
-{
-}
-
-TypeEntry *EnumValueTypeEntry::clone() const
-{
- return new EnumValueTypeEntry(*this);
-}
-
-EnumValueTypeEntry::EnumValueTypeEntry(const EnumValueTypeEntry &) = default;
-
-FlagsTypeEntry::FlagsTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent) :
- TypeEntry(entryName, FlagsType, vr, parent)
-{
-}
-
-QString FlagsTypeEntry::buildTargetLangName() const
-{
- QString on = m_originalName;
- on.replace(QLatin1String("::"), QLatin1String("."));
- return on;
-}
-
-ConstantValueTypeEntry::ConstantValueTypeEntry(const QString& name,
- const TypeEntry *parent) :
- TypeEntry(name, ConstantValueType, QVersionNumber(0, 0), parent)
-{
-}
-
-TypeEntry *ConstantValueTypeEntry::clone() const
-{
- return new ConstantValueTypeEntry(*this);
-}
-
-ConstantValueTypeEntry::ConstantValueTypeEntry(const ConstantValueTypeEntry &) = default;
-
-/* A typedef entry allows for specifying template specializations in the
- * typesystem XML file. */
-TypedefEntry::TypedefEntry(const QString &entryName, const QString &sourceType,
- const QVersionNumber &vr, const TypeEntry *parent) :
- ComplexTypeEntry(entryName, TypedefType, vr, parent),
- m_sourceType(sourceType)
-{
-}
-
-TypeEntry *TypedefEntry::clone() const
-{
- return new TypedefEntry(*this);
-}
-
-TypedefEntry::TypedefEntry(const TypedefEntry &) = default;
-
-ContainerTypeEntry::ContainerTypeEntry(const QString &entryName, ContainerKind containerKind,
- const QVersionNumber &vr,
- const TypeEntry *parent) :
- ComplexTypeEntry(entryName, ContainerType, vr, parent),
- m_containerKind(containerKind)
-{
- setCodeGeneration(GenerateForSubclass);
-}
-
-SmartPointerTypeEntry::SmartPointerTypeEntry(const QString &entryName,
- const QString &getterName,
- const QString &smartPointerType,
- const QString &refCountMethodName,
- const QVersionNumber &vr, const TypeEntry *parent) :
- ComplexTypeEntry(entryName, SmartPointerType, vr, parent),
- m_getterName(getterName),
- m_smartPointerType(smartPointerType),
- m_refCountMethodName(refCountMethodName)
-{
-}
-
-TypeEntry *SmartPointerTypeEntry::clone() const
-{
- return new SmartPointerTypeEntry(*this);
-}
-
-SmartPointerTypeEntry::SmartPointerTypeEntry(const SmartPointerTypeEntry &) = default;
-
-bool SmartPointerTypeEntry::matchesInstantiation(const TypeEntry *e) const
-{
- return m_instantiations.isEmpty() || m_instantiations.contains(e);
-}
-
-NamespaceTypeEntry::NamespaceTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent) :
- ComplexTypeEntry(entryName, NamespaceType, vr, parent)
-{
-}
-
-TypeEntry *NamespaceTypeEntry::clone() const
-{
- return new NamespaceTypeEntry(*this);
-}
-
-void NamespaceTypeEntry::setFilePattern(const QRegularExpression &r)
-{
- m_filePattern = r;
- m_hasPattern = !m_filePattern.pattern().isEmpty();
- if (m_hasPattern)
- m_filePattern.optimize();
-}
-
-NamespaceTypeEntry::NamespaceTypeEntry(const NamespaceTypeEntry &) = default;
-
-bool NamespaceTypeEntry::matchesFile(const QString &needle) const
-{
- return m_filePattern.match(needle).hasMatch();
-}
-
-bool NamespaceTypeEntry::isVisible() const
-{
- return m_visibility == TypeSystem::Visibility::Visible
- || (m_visibility == TypeSystem::Visibility::Auto && !m_inlineNamespace);
-}
-
-bool NamespaceTypeEntry::isVisibleScope(const TypeEntry *e)
-{
- return e->type() != TypeEntry::NamespaceType
- || static_cast<const NamespaceTypeEntry *>(e)->isVisible();
-}
-
-ValueTypeEntry::ValueTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent) :
- ComplexTypeEntry(entryName, BasicValueType, vr, parent)
-{
-}
-
-bool ValueTypeEntry::isValue() const
-{
- return true;
-}
-
-TypeEntry *ValueTypeEntry::clone() const
-{
- return new ValueTypeEntry(*this);
-}
-
-ValueTypeEntry::ValueTypeEntry(const ValueTypeEntry &) = default;
-
-ValueTypeEntry::ValueTypeEntry(const QString &entryName, Type t, const QVersionNumber &vr,
- const TypeEntry *parent) :
- ComplexTypeEntry(entryName, t, vr, parent)
-{
-}
-
-struct CustomConversion::CustomConversionPrivate
-{
- CustomConversionPrivate(const TypeEntry* ownerType)
- : ownerType(ownerType), replaceOriginalTargetToNativeConversions(false)
- {
- }
- const TypeEntry* ownerType;
- QString nativeToTargetConversion;
- bool replaceOriginalTargetToNativeConversions;
- TargetToNativeConversions targetToNativeConversions;
-};
-
-struct CustomConversion::TargetToNativeConversion::TargetToNativeConversionPrivate
-{
- TargetToNativeConversionPrivate()
- : sourceType(nullptr)
- {
- }
- const TypeEntry* sourceType;
- QString sourceTypeName;
- QString sourceTypeCheck;
- QString conversion;
-};
-
-CustomConversion::CustomConversion(TypeEntry* ownerType)
-{
- m_d = new CustomConversionPrivate(ownerType);
- if (ownerType)
- ownerType->setCustomConversion(this);
-}
-
-CustomConversion::~CustomConversion()
-{
- qDeleteAll(m_d->targetToNativeConversions);
- delete m_d;
-}
-
-const TypeEntry* CustomConversion::ownerType() const
-{
- return m_d->ownerType;
-}
-
-QString CustomConversion::nativeToTargetConversion() const
-{
- return m_d->nativeToTargetConversion;
-}
-
-void CustomConversion::setNativeToTargetConversion(const QString& nativeToTargetConversion)
-{
- m_d->nativeToTargetConversion = nativeToTargetConversion;
-}
-
-bool CustomConversion::replaceOriginalTargetToNativeConversions() const
-{
- return m_d->replaceOriginalTargetToNativeConversions;
-}
-
-void CustomConversion::setReplaceOriginalTargetToNativeConversions(bool replaceOriginalTargetToNativeConversions)
-{
- m_d->replaceOriginalTargetToNativeConversions = replaceOriginalTargetToNativeConversions;
-}
-
-bool CustomConversion::hasTargetToNativeConversions() const
-{
- return !(m_d->targetToNativeConversions.isEmpty());
-}
-
-CustomConversion::TargetToNativeConversions& CustomConversion::targetToNativeConversions()
-{
- return m_d->targetToNativeConversions;
-}
-
-const CustomConversion::TargetToNativeConversions& CustomConversion::targetToNativeConversions() const
-{
- return m_d->targetToNativeConversions;
-}
-
-void CustomConversion::addTargetToNativeConversion(const QString& sourceTypeName,
- const QString& sourceTypeCheck,
- const QString& conversion)
-{
- m_d->targetToNativeConversions.append(new TargetToNativeConversion(sourceTypeName, sourceTypeCheck, conversion));
-}
-
-CustomConversion::TargetToNativeConversion::TargetToNativeConversion(const QString& sourceTypeName,
- const QString& sourceTypeCheck,
- const QString& conversion)
-{
- m_d = new TargetToNativeConversionPrivate;
- m_d->sourceTypeName = sourceTypeName;
- m_d->sourceTypeCheck = sourceTypeCheck;
- m_d->conversion = conversion;
-}
-
-CustomConversion::TargetToNativeConversion::~TargetToNativeConversion()
-{
- delete m_d;
-}
-
-const TypeEntry* CustomConversion::TargetToNativeConversion::sourceType() const
-{
- return m_d->sourceType;
-}
-
-void CustomConversion::TargetToNativeConversion::setSourceType(const TypeEntry* sourceType)
-{
- m_d->sourceType = sourceType;
-}
-
-bool CustomConversion::TargetToNativeConversion::isCustomType() const
-{
- return !(m_d->sourceType);
-}
-
-QString CustomConversion::TargetToNativeConversion::sourceTypeName() const
-{
- return m_d->sourceTypeName;
-}
-
-QString CustomConversion::TargetToNativeConversion::sourceTypeCheck() const
-{
- return m_d->sourceTypeCheck;
-}
-
-QString CustomConversion::TargetToNativeConversion::conversion() const
-{
- return m_d->conversion;
-}
-
-void CustomConversion::TargetToNativeConversion::setConversion(const QString& conversion)
-{
- m_d->conversion = conversion;
-}
-
-FunctionTypeEntry::FunctionTypeEntry(const QString &entryName, const QString &signature,
- const QVersionNumber &vr,
- const TypeEntry *parent) :
- TypeEntry(entryName, FunctionType, vr, parent)
-{
- addSignature(signature);
-}
-
-TypeEntry *FunctionTypeEntry::clone() const
-{
- return new FunctionTypeEntry(*this);
-}
-
-FunctionTypeEntry::FunctionTypeEntry(const FunctionTypeEntry &) = default;
-
-ObjectTypeEntry::ObjectTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent)
- : ComplexTypeEntry(entryName, ObjectType, vr, parent)
-{
-}
-
-TypeEntry *ObjectTypeEntry::clone() const
-{
- return new ObjectTypeEntry(*this);
-}
-
-ObjectTypeEntry::ObjectTypeEntry(const ObjectTypeEntry &) = default;
diff --git a/sources/shiboken2/ApiExtractor/typesystem.h b/sources/shiboken2/ApiExtractor/typesystem.h
deleted file mode 100644
index 6d2d4bb44..000000000
--- a/sources/shiboken2/ApiExtractor/typesystem.h
+++ /dev/null
@@ -1,1662 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TYPESYSTEM_H
-#define TYPESYSTEM_H
-
-#include "typesystem_enums.h"
-#include "typesystem_typedefs.h"
-#include "include.h"
-
-#include <QtCore/QHash>
-#include <QtCore/qobjectdefs.h>
-#include <QtCore/QRegularExpression>
-#include <QtCore/QString>
-#include <QtCore/QStringList>
-#include <QtCore/QMap>
-#include <QtCore/QVector>
-#include <QtCore/QVersionNumber>
-
-//Used to identify the conversion rule to avoid break API
-extern const char *TARGET_CONVERSION_RULE_FLAG;
-extern const char *NATIVE_CONVERSION_RULE_FLAG;
-
-class AbstractMetaType;
-QT_BEGIN_NAMESPACE
-class QDebug;
-class QTextStream;
-QT_END_NAMESPACE
-
-class EnumTypeEntry;
-class FlagsTypeEntry;
-
-using ArgumentMap = QMap<int, QString>;
-
-class TemplateInstance;
-
-struct ReferenceCount
-{
- enum Action { // 0x01 - 0xff
- Invalid = 0x00,
- Add = 0x01,
- AddAll = 0x02,
- Remove = 0x04,
- Set = 0x08,
- Ignore = 0x10,
-
- ActionsMask = 0xff,
-
- Padding = 0xffffffff
- };
-
- QString varName;
- Action action = Invalid;
-};
-
-struct ArgumentOwner
-{
- enum Action {
- Invalid = 0x00,
- Add = 0x01,
- Remove = 0x02
- };
- enum {
- InvalidIndex = -2,
- ThisIndex = -1,
- ReturnIndex = 0,
- FirstArgumentIndex = 1
- };
-
- Action action = Invalid;
- int index = InvalidIndex;
-};
-
-class CodeSnipFragment
-{
-public:
- CodeSnipFragment() = default;
- explicit CodeSnipFragment(const QString &code) : m_code(code) {}
- explicit CodeSnipFragment(TemplateInstance *instance) : m_instance(instance) {}
-
- QString code() const;
-
-private:
- QString m_code;
- TemplateInstance *m_instance = nullptr;
-};
-
-class CodeSnipAbstract
-{
-public:
- QString code() const;
-
- void addCode(const QString &code) { codeList.append(CodeSnipFragment(code)); }
- void addCode(const QStringRef &code) { addCode(code.toString()); }
-
- void addTemplateInstance(TemplateInstance *ti)
- {
- codeList.append(CodeSnipFragment(ti));
- }
-
- QVector<CodeSnipFragment> codeList;
-};
-
-class CustomFunction : public CodeSnipAbstract
-{
-public:
- explicit CustomFunction(const QString &n = QString()) : name(n) {}
-
- QString name;
- QString paramName;
-};
-
-class TemplateEntry : public CodeSnipAbstract
-{
-public:
- explicit TemplateEntry(const QString &name) : m_name(name) {}
-
- QString name() const
- {
- return m_name;
- }
-
-private:
- QString m_name;
-};
-
-class TemplateInstance
-{
-public:
- explicit TemplateInstance(const QString &name) : m_name(name) {}
-
- void addReplaceRule(const QString &name, const QString &value)
- {
- replaceRules[name] = value;
- }
-
- QString expandCode() const;
-
- QString name() const
- {
- return m_name;
- }
-
-private:
- const QString m_name;
- QHash<QString, QString> replaceRules;
-};
-
-
-class CodeSnip : public CodeSnipAbstract
-{
-public:
- CodeSnip() = default;
- explicit CodeSnip(TypeSystem::Language lang) : language(lang) {}
-
- TypeSystem::Language language = TypeSystem::TargetLangCode;
- TypeSystem::CodeSnipPosition position = TypeSystem::CodeSnipPositionAny;
- ArgumentMap argumentMap;
-};
-
-struct ArgumentModification
-{
- ArgumentModification() : removedDefaultExpression(false), removed(false),
- noNullPointers(false), resetAfterUse(false), array(false) {}
- explicit ArgumentModification(int idx) : index(idx), removedDefaultExpression(false), removed(false),
- noNullPointers(false), resetAfterUse(false), array(false) {}
-
- // Should the default expression be removed?
-
-
- // Reference count flags for this argument
- QVector<ReferenceCount> referenceCounts;
-
- // The text given for the new type of the argument
- QString modified_type;
-
- QString replace_value;
-
- // The text of the new default expression of the argument
- QString replacedDefaultExpression;
-
- // The new definition of ownership for a specific argument
- QHash<TypeSystem::Language, TypeSystem::Ownership> ownerships;
-
- // Different conversion rules
- CodeSnipList conversion_rules;
-
- //QObject parent(owner) of this argument
- ArgumentOwner owner;
-
- //New name
- QString renamed_to;
-
- // The index of this argument
- int index = -1;
-
- uint removedDefaultExpression : 1;
- uint removed : 1;
- uint noNullPointers : 1;
- uint resetAfterUse : 1;
- uint array : 1; // consider "int*" to be "int[]"
-};
-
-struct Modification
-{
- enum Modifiers : uint {
- InvalidModifier = 0x0000,
- Private = 0x0001,
- Protected = 0x0002,
- Public = 0x0003,
- Friendly = 0x0004,
- AccessModifierMask = 0x000f,
-
- Final = 0x0010,
- NonFinal = 0x0020,
- FinalMask = Final | NonFinal,
-
- Readable = 0x0100,
- Writable = 0x0200,
-
- CodeInjection = 0x1000,
- Rename = 0x2000,
- Deprecated = 0x4000,
- ReplaceExpression = 0x8000
- };
-
- bool isAccessModifier() const
- {
- return modifiers & AccessModifierMask;
- }
- Modifiers accessModifier() const
- {
- return Modifiers(modifiers & AccessModifierMask);
- }
- bool isPrivate() const
- {
- return accessModifier() == Private;
- }
- bool isProtected() const
- {
- return accessModifier() == Protected;
- }
- bool isPublic() const
- {
- return accessModifier() == Public;
- }
- bool isFriendly() const
- {
- return accessModifier() == Friendly;
- }
- bool isFinal() const
- {
- return modifiers & Final;
- }
- bool isNonFinal() const
- {
- return modifiers & NonFinal;
- }
- QString accessModifierString() const;
-
- bool isDeprecated() const
- {
- return modifiers & Deprecated;
- }
-
- void setRenamedTo(const QString &name)
- {
- renamedToName = name;
- }
- QString renamedTo() const
- {
- return renamedToName;
- }
- bool isRenameModifier() const
- {
- return modifiers & Rename;
- }
-
- bool isRemoveModifier() const
- {
- return removal != TypeSystem::NoLanguage;
- }
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const;
-#endif
-
- QString renamedToName;
- uint modifiers = 0;
- TypeSystem::Language removal = TypeSystem::NoLanguage;
-};
-
-struct FunctionModification: public Modification
-{
- using AllowThread = TypeSystem::AllowThread;
-
- bool isCodeInjection() const
- {
- return modifiers & CodeInjection;
- }
- void setIsThread(bool flag)
- {
- m_thread = flag;
- }
- bool isThread() const
- {
- return m_thread;
- }
-
- AllowThread allowThread() const { return m_allowThread; }
- void setAllowThread(AllowThread allow) { m_allowThread = allow; }
-
- bool matches(const QString &functionSignature) const
- {
- return m_signature.isEmpty()
- ? m_signaturePattern.match(functionSignature).hasMatch()
- : m_signature == functionSignature;
- }
-
- bool setSignature(const QString &s, QString *errorMessage = nullptr);
- QString signature() const { return m_signature.isEmpty() ? m_signaturePattern.pattern() : m_signature; }
-
- void setOriginalSignature(const QString &s) { m_originalSignature = s; }
- QString originalSignature() const { return m_originalSignature; }
-
- TypeSystem::ExceptionHandling exceptionHandling() const { return m_exceptionHandling; }
- void setExceptionHandling(TypeSystem::ExceptionHandling e) { m_exceptionHandling = e; }
-
- QString toString() const;
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const;
-#endif
-
- QString association;
- CodeSnipList snips;
-
- QVector<ArgumentModification> argument_mods;
-
-private:
- QString m_signature;
- QString m_originalSignature;
- QRegularExpression m_signaturePattern;
- bool m_thread = false;
- AllowThread m_allowThread = AllowThread::Unspecified;
- TypeSystem::ExceptionHandling m_exceptionHandling = TypeSystem::ExceptionHandling::Unspecified;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const ReferenceCount &);
-QDebug operator<<(QDebug d, const ArgumentOwner &a);
-QDebug operator<<(QDebug d, const ArgumentModification &a);
-QDebug operator<<(QDebug d, const FunctionModification &fm);
-#endif
-
-struct FieldModification: public Modification
-{
- bool isReadable() const
- {
- return modifiers & Readable;
- }
- bool isWritable() const
- {
- return modifiers & Writable;
- }
-
- QString name;
-};
-
-/**
-* \internal
-* Struct used to store information about functions added by the typesystem.
-* This info will be used later to create a fake AbstractMetaFunction which
-* will be inserted into the right AbstractMetaClass.
-*/
-struct AddedFunction
-{
- /// Function access types.
- enum Access {
- InvalidAccess = 0,
- Protected = 0x1,
- Public = 0x2
- };
-
- /**
- * \internal
- * Internal struct used to store information about arguments and return type of the
- * functions added by the type system. This information is later used to create
- * AbstractMetaType and AbstractMetaArgument for the AbstractMetaFunctions.
- */
- struct TypeInfo {
- TypeInfo() = default;
- static TypeInfo fromSignature(const QString& signature);
-
- QString name;
- QString defaultValue;
- int indirections = 0;
- bool isConstant = false;
- bool isReference = false;
- };
-
- struct Argument
- {
- QString name;
- TypeInfo typeInfo;
- };
-
- /// Creates a new AddedFunction with a signature and a return type.
- explicit AddedFunction(QString signature, const QString &returnType);
- AddedFunction() = default;
-
- /// Returns the function name.
- QString name() const
- {
- return m_name;
- }
-
- /// Set the function access type.
- void setAccess(Access access)
- {
- m_access = access;
- }
-
- /// Returns the function access type.
- Access access() const
- {
- return m_access;
- }
-
- /// Returns the function return type.
- TypeInfo returnType() const
- {
- return m_returnType;
- }
-
- /// Returns a list of argument type infos.
- const QVector<Argument> &arguments() const
- {
- return m_arguments;
- }
-
- /// Returns true if this is a constant method.
- bool isConstant() const
- {
- return m_isConst;
- }
-
- /// Set this method static.
- void setStatic(bool value)
- {
- m_isStatic = value;
- }
-
- /// Returns true if this is a static method.
- bool isStatic() const
- {
- return m_isStatic;
- }
-
- FunctionModificationList modifications;
-
-private:
- QString m_name;
- QVector<Argument> m_arguments;
- TypeInfo m_returnType;
- Access m_access = Protected;
- bool m_isConst = false;
- bool m_isStatic = false;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const AddedFunction::TypeInfo &ti);
-QDebug operator<<(QDebug d, const AddedFunction::Argument &a);
-QDebug operator<<(QDebug d, const AddedFunction &af);
-#endif
-
-class ObjectTypeEntry;
-
-class DocModification
-{
-public:
- DocModification() = default;
- explicit DocModification(const QString& xpath, const QString& signature) :
- m_xpath(xpath), m_signature(signature) {}
- explicit DocModification(TypeSystem::DocModificationMode mode, const QString& signature) :
- m_signature(signature), m_mode(mode) {}
-
- void setCode(const QString& code) { m_code = code; }
- void setCode(const QStringRef& code) { m_code = code.toString(); }
-
- QString code() const
- {
- return m_code;
- }
- QString xpath() const
- {
- return m_xpath;
- }
- QString signature() const
- {
- return m_signature;
- }
- TypeSystem::DocModificationMode mode() const
- {
- return m_mode;
- }
-
- TypeSystem::Language format() const { return m_format; }
- void setFormat(TypeSystem::Language f) { m_format = f; }
-
-private:
- QString m_code;
- QString m_xpath;
- QString m_signature;
- TypeSystem::DocModificationMode m_mode = TypeSystem::DocModificationXPathReplace;
- TypeSystem::Language m_format = TypeSystem::NativeCode;
-};
-
-class CustomConversion;
-class TypeSystemTypeEntry;
-
-class TypeEntry
-{
- Q_GADGET
-public:
- TypeEntry &operator=(const TypeEntry &) = delete;
- TypeEntry &operator=(TypeEntry &&) = delete;
- TypeEntry(TypeEntry &&) = delete;
-
- enum Type {
- PrimitiveType,
- VoidType,
- VarargsType,
- FlagsType,
- EnumType,
- EnumValue,
- ConstantValueType,
- TemplateArgumentType,
- BasicValueType,
- ContainerType,
- ObjectType,
- NamespaceType,
- ArrayType,
- TypeSystemType,
- CustomType,
- FunctionType,
- SmartPointerType,
- TypedefType
- };
- Q_ENUM(Type)
-
- enum CodeGeneration {
- GenerateTargetLang = 0x0001,
- GenerateCpp = 0x0002,
- GenerateForSubclass = 0x0004,
-
- GenerateNothing = 0,
- GenerateAll = 0xffff,
- GenerateCode = GenerateTargetLang | GenerateCpp
- };
- Q_ENUM(CodeGeneration)
-
- explicit TypeEntry(const QString &entryName, Type t, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- virtual ~TypeEntry();
-
- Type type() const
- {
- return m_type;
- }
-
- const TypeEntry *parent() const { return m_parent; }
- void setParent(const TypeEntry *p) { m_parent = p; }
- bool isChildOf(const TypeEntry *p) const;
- const TypeSystemTypeEntry *typeSystemTypeEntry() const;
- // cf AbstractMetaClass::targetLangEnclosingClass()
- const TypeEntry *targetLangEnclosingEntry() const;
-
- bool isPrimitive() const
- {
- return m_type == PrimitiveType;
- }
- bool isEnum() const
- {
- return m_type == EnumType;
- }
- bool isFlags() const
- {
- return m_type == FlagsType;
- }
- bool isObject() const
- {
- return m_type == ObjectType;
- }
- bool isNamespace() const
- {
- return m_type == NamespaceType;
- }
- bool isContainer() const
- {
- return m_type == ContainerType;
- }
- bool isSmartPointer() const
- {
- return m_type == SmartPointerType;
- }
- bool isArray() const
- {
- return m_type == ArrayType;
- }
- bool isTemplateArgument() const
- {
- return m_type == TemplateArgumentType;
- }
- bool isVoid() const
- {
- return m_type == VoidType;
- }
- bool isVarargs() const
- {
- return m_type == VarargsType;
- }
- bool isCustom() const
- {
- return m_type == CustomType;
- }
- bool isTypeSystem() const
- {
- return m_type == TypeSystemType;
- }
- bool isFunction() const
- {
- return m_type == FunctionType;
- }
- bool isEnumValue() const
- {
- return m_type == EnumValue;
- }
-
- bool stream() const
- {
- return m_stream;
- }
-
- void setStream(bool b)
- {
- m_stream = b;
- }
-
- // The type's name in C++, fully qualified
- QString name() const { return m_name; }
- // C++ excluding inline namespaces
- QString shortName() const;
- // Name as specified in XML
- QString entryName() const { return m_entryName; }
-
- uint codeGeneration() const
- {
- return m_codeGeneration;
- }
- void setCodeGeneration(uint cg)
- {
- m_codeGeneration = cg;
- }
-
- // Returns true if code must be generated for this entry,
- // it will return false in case of types coming from typesystems
- // included for reference only.
- // NOTE: 'GenerateForSubclass' means 'generate="no"'
- // on 'load-typesystem' tag
- inline bool generateCode() const
- {
- return m_codeGeneration != TypeEntry::GenerateForSubclass
- && m_codeGeneration != TypeEntry::GenerateNothing;
- }
-
- int revision() const { return m_revision; }
- void setRevision(int r); // see typedatabase.cpp
- int sbkIndex() const;
- void setSbkIndex(int i) { m_sbkIndex = i; }
-
- virtual QString qualifiedCppName() const
- {
- return m_name;
- }
-
- /**
- * Its type's name in target language API
- * The target language API name represents how this type is
- * referred on low level code for the target language.
- * Examples: for Java this would be a JNI name, for Python
- * it should represent the CPython type name.
- * /return string representing the target language API name
- * for this type entry
- */
- virtual QString targetLangApiName() const
- {
- return m_name;
- }
-
- // The type's name in TargetLang
- QString targetLangName() const; // "Foo.Bar"
- void setTargetLangName(const QString &n) { m_cachedTargetLangName = n; }
- QString targetLangEntryName() const; // "Bar"
-
- // The package
- QString targetLangPackage() const { return m_targetLangPackage; }
- void setTargetLangPackage(const QString &p) { m_targetLangPackage = p; }
-
- QString qualifiedTargetLangName() const;
-
- void setCustomConstructor(const CustomFunction &func)
- {
- m_customConstructor = func;
- }
- CustomFunction customConstructor() const
- {
- return m_customConstructor;
- }
-
- void setCustomDestructor(const CustomFunction &func)
- {
- m_customDestructor = func;
- }
- CustomFunction customDestructor() const
- {
- return m_customDestructor;
- }
-
- virtual bool isValue() const
- {
- return false;
- }
- virtual bool isComplex() const
- {
- return false;
- }
-
- CodeSnipList codeSnips() const;
- void setCodeSnips(const CodeSnipList &codeSnips)
- {
- m_codeSnips = codeSnips;
- }
- void addCodeSnip(const CodeSnip &codeSnip)
- {
- m_codeSnips << codeSnip;
- }
-
- void setDocModification(const DocModificationList& docMods)
- {
- m_docModifications << docMods;
- }
- DocModificationList docModifications() const
- {
- return m_docModifications;
- }
-
- IncludeList extraIncludes() const
- {
- return m_extraIncludes;
- }
- void setExtraIncludes(const IncludeList &includes)
- {
- m_extraIncludes = includes;
- }
- void addExtraInclude(const Include &newInclude);
-
- Include include() const
- {
- return m_include;
- }
- void setInclude(const Include &inc);
-
- // Replace conversionRule arg to CodeSnip in future version
- /// Set the type convertion rule
- void setConversionRule(const QString& conversionRule)
- {
- m_conversionRule = conversionRule;
- }
-
- /// Returns the type convertion rule
- QString conversionRule() const
- {
- //skip conversions flag
- return m_conversionRule.mid(1);
- }
-
- /// Returns true if there are any conversiton rule for this type, false otherwise.
- bool hasConversionRule() const
- {
- return !m_conversionRule.isEmpty();
- }
-
- QVersionNumber version() const
- {
- return m_version;
- }
-
- /// TODO-CONVERTER: mark as deprecated
- bool hasNativeConversionRule() const
- {
- return m_conversionRule.startsWith(QLatin1String(NATIVE_CONVERSION_RULE_FLAG));
- }
-
- /// TODO-CONVERTER: mark as deprecated
- bool hasTargetConversionRule() const
- {
- return m_conversionRule.startsWith(QLatin1String(TARGET_CONVERSION_RULE_FLAG));
- }
-
- bool isCppPrimitive() const;
-
- bool hasCustomConversion() const;
- void setCustomConversion(CustomConversion* customConversion);
- CustomConversion* customConversion() const;
-
- virtual TypeEntry *clone() const;
-
- void useAsTypedef(const TypeEntry *source);
-
-#ifndef QT_NO_DEBUG_STREAM
- virtual void formatDebug(QDebug &d) const;
-#endif
-
-protected:
- TypeEntry(const TypeEntry &);
-
- virtual QString buildTargetLangName() const;
-
-private:
- const TypeEntry *m_parent;
- QString m_name; // C++ fully qualified
- mutable QString m_cachedShortName; // C++ excluding inline namespaces
- QString m_entryName;
- QString m_targetLangPackage;
- mutable QString m_cachedTargetLangName; // "Foo.Bar"
- mutable QString m_cachedTargetLangEntryName; // "Bar"
- CustomFunction m_customConstructor;
- CustomFunction m_customDestructor;
- CodeSnipList m_codeSnips;
- DocModificationList m_docModifications;
- IncludeList m_extraIncludes;
- Include m_include;
- QString m_conversionRule;
- QVersionNumber m_version;
- CustomConversion *m_customConversion = nullptr;
- uint m_codeGeneration = GenerateAll;
- int m_revision = 0;
- int m_sbkIndex = 0;
- Type m_type;
- bool m_stream = false;
-};
-
-class TypeSystemTypeEntry : public TypeEntry
-{
-public:
- explicit TypeSystemTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- TypeEntry *clone() const override;
-
-protected:
- TypeSystemTypeEntry(const TypeSystemTypeEntry &);
-};
-
-class VoidTypeEntry : public TypeEntry
-{
-public:
- VoidTypeEntry();
-
- TypeEntry *clone() const override;
-
-protected:
- VoidTypeEntry(const VoidTypeEntry &);
-};
-
-class VarargsTypeEntry : public TypeEntry
-{
-public:
- VarargsTypeEntry();
-
- TypeEntry *clone() const override;
-
-protected:
- VarargsTypeEntry(const VarargsTypeEntry &);
-};
-
-class TemplateArgumentEntry : public TypeEntry
-{
-public:
- explicit TemplateArgumentEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- int ordinal() const
- {
- return m_ordinal;
- }
- void setOrdinal(int o)
- {
- m_ordinal = o;
- }
-
- TypeEntry *clone() const override;
-
-protected:
- TemplateArgumentEntry(const TemplateArgumentEntry &);
-
-private:
- int m_ordinal = 0;
-};
-
-class ArrayTypeEntry : public TypeEntry
-{
-public:
- explicit ArrayTypeEntry(const TypeEntry *nested_type, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- void setNestedTypeEntry(TypeEntry *nested)
- {
- m_nestedType = nested;
- }
- const TypeEntry *nestedTypeEntry() const
- {
- return m_nestedType;
- }
-
- QString targetLangApiName() const override;
-
- TypeEntry *clone() const override;
-
-protected:
- ArrayTypeEntry(const ArrayTypeEntry &);
-
- QString buildTargetLangName() const override;
-
-private:
- const TypeEntry *m_nestedType;
-};
-
-
-class PrimitiveTypeEntry : public TypeEntry
-{
-public:
- explicit PrimitiveTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- QString targetLangApiName() const override;
- void setTargetLangApiName(const QString &targetLangApiName)
- {
- m_targetLangApiName = targetLangApiName;
- }
-
- QString defaultConstructor() const
- {
- return m_defaultConstructor;
- }
- void setDefaultConstructor(const QString& defaultConstructor)
- {
- m_defaultConstructor = defaultConstructor;
- }
- bool hasDefaultConstructor() const
- {
- return !m_defaultConstructor.isEmpty();
- }
-
- /**
- * The PrimitiveTypeEntry pointed by this type entry if it
- * represents a typedef).
- * /return the type referenced by the typedef, or a null pointer
- * if the current object is not an typedef
- */
- PrimitiveTypeEntry* referencedTypeEntry() const { return m_referencedTypeEntry; }
-
- /**
- * Defines type referenced by this entry.
- * /param referencedTypeEntry type referenced by this entry
- */
- void setReferencedTypeEntry(PrimitiveTypeEntry* referencedTypeEntry)
- {
- m_referencedTypeEntry = referencedTypeEntry;
- }
-
- /**
- * Finds the most basic primitive type that the typedef represents,
- * i.e. a type that is not an typedef'ed.
- * /return the most basic non-typedef'ed primitive type represented
- * by this typedef
- */
- PrimitiveTypeEntry* basicReferencedTypeEntry() const;
-
- bool preferredTargetLangType() const
- {
- return m_preferredTargetLangType;
- }
- void setPreferredTargetLangType(bool b)
- {
- m_preferredTargetLangType = b;
- }
-
- TypeEntry *clone() const override;
-
-protected:
- PrimitiveTypeEntry(const PrimitiveTypeEntry &);
-
-private:
- QString m_targetLangApiName;
- QString m_defaultConstructor;
- uint m_preferredTargetLangType : 1;
- PrimitiveTypeEntry* m_referencedTypeEntry = nullptr;
-};
-
-class EnumValueTypeEntry;
-
-class EnumTypeEntry : public TypeEntry
-{
-public:
- explicit EnumTypeEntry(const QString &entryName,
- const QVersionNumber &vr,
- const TypeEntry *parent);
-
- QString targetLangQualifier() const;
-
- QString targetLangApiName() const override;
-
- QString qualifier() const;
-
- const EnumValueTypeEntry *nullValue() const { return m_nullValue; }
- void setNullValue(const EnumValueTypeEntry *n) { m_nullValue = n; }
-
- void setFlags(FlagsTypeEntry *flags)
- {
- m_flags = flags;
- }
- FlagsTypeEntry *flags() const
- {
- return m_flags;
- }
-
- bool isEnumValueRejected(const QString &name) const
- {
- return m_rejectedEnums.contains(name);
- }
- void addEnumValueRejection(const QString &name)
- {
- m_rejectedEnums << name;
- }
- QStringList enumValueRejections() const
- {
- return m_rejectedEnums;
- }
-
- TypeEntry *clone() const override;
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-protected:
- EnumTypeEntry(const EnumTypeEntry &);
-
-private:
- const EnumValueTypeEntry *m_nullValue = nullptr;
-
- QStringList m_rejectedEnums;
-
- FlagsTypeEntry *m_flags = nullptr;
-};
-
-// EnumValueTypeEntry is used for resolving integer type templates
-// like array<EnumValue>. Note: Dummy entries for integer values will
-// be created for non-type template parameters, where m_enclosingEnum==nullptr.
-class EnumValueTypeEntry : public TypeEntry
-{
-public:
- explicit EnumValueTypeEntry(const QString& name, const QString& value,
- const EnumTypeEntry* enclosingEnum,
- bool isScopedEnum, const QVersionNumber &vr);
-
- QString value() const { return m_value; }
- const EnumTypeEntry* enclosingEnum() const { return m_enclosingEnum; }
-
- TypeEntry *clone() const override;
-
-protected:
- EnumValueTypeEntry(const EnumValueTypeEntry &);
-
-private:
- QString m_value;
- const EnumTypeEntry* m_enclosingEnum;
-};
-
-class FlagsTypeEntry : public TypeEntry
-{
-public:
- explicit FlagsTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- QString targetLangApiName() const override;
-
- QString originalName() const
- {
- return m_originalName;
- }
- void setOriginalName(const QString &s)
- {
- m_originalName = s;
- }
-
- QString flagsName() const
- {
- return m_flagsName;
- }
- void setFlagsName(const QString &name)
- {
- m_flagsName = name;
- }
-
- EnumTypeEntry *originator() const
- {
- return m_enum;
- }
- void setOriginator(EnumTypeEntry *e)
- {
- m_enum = e;
- }
-
- TypeEntry *clone() const override;
-
-protected:
- FlagsTypeEntry(const FlagsTypeEntry &);
-
- QString buildTargetLangName() const override;
-
-private:
- QString m_originalName;
- QString m_flagsName;
- EnumTypeEntry *m_enum = nullptr;
-};
-
-// For primitive values, typically to provide a dummy type for
-// example the '2' in non-type template 'Array<2>'.
-class ConstantValueTypeEntry : public TypeEntry
-{
-public:
- explicit ConstantValueTypeEntry(const QString& name,
- const TypeEntry *parent);
-
- TypeEntry *clone() const override;
-
-protected:
- ConstantValueTypeEntry(const ConstantValueTypeEntry &);
-};
-
-class ComplexTypeEntry : public TypeEntry
-{
-public:
- enum TypeFlag {
- Deprecated = 0x4
- };
- Q_DECLARE_FLAGS(TypeFlags, TypeFlag)
-
- enum CopyableFlag {
- CopyableSet,
- NonCopyableSet,
- Unknown
- };
-
- explicit ComplexTypeEntry(const QString &entryName, Type t, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- bool isComplex() const override;
-
- QString targetLangApiName() const override;
-
- void setTypeFlags(TypeFlags flags)
- {
- m_typeFlags = flags;
- }
-
- TypeFlags typeFlags() const
- {
- return m_typeFlags;
- }
-
- FunctionModificationList functionModifications() const
- {
- return m_functionMods;
- }
- void setFunctionModifications(const FunctionModificationList &functionModifications)
- {
- m_functionMods = functionModifications;
- }
- void addFunctionModification(const FunctionModification &functionModification)
- {
- m_functionMods << functionModification;
- }
- FunctionModificationList functionModifications(const QString &signature) const;
-
- AddedFunctionList addedFunctions() const
- {
- return m_addedFunctions;
- }
- void setAddedFunctions(const AddedFunctionList &addedFunctions)
- {
- m_addedFunctions = addedFunctions;
- }
- void addNewFunction(const AddedFunctionPtr &addedFunction)
- {
- m_addedFunctions << addedFunction;
- }
-
- FieldModification fieldModification(const QString &name) const;
- void setFieldModifications(const FieldModificationList &mods)
- {
- m_fieldMods = mods;
- }
- FieldModificationList fieldModifications() const
- {
- return m_fieldMods;
- }
-
- QString defaultSuperclass() const
- {
- return m_defaultSuperclass;
- }
- void setDefaultSuperclass(const QString &sc)
- {
- m_defaultSuperclass = sc;
- }
-
- QString qualifiedCppName() const override
- {
- return m_qualifiedCppName;
- }
-
-
- void setIsPolymorphicBase(bool on)
- {
- m_polymorphicBase = on;
- }
- bool isPolymorphicBase() const
- {
- return m_polymorphicBase;
- }
-
- void setPolymorphicIdValue(const QString &value)
- {
- m_polymorphicIdValue = value;
- }
- QString polymorphicIdValue() const
- {
- return m_polymorphicIdValue;
- }
-
- QString targetType() const
- {
- return m_targetType;
- }
- void setTargetType(const QString &code)
- {
- m_targetType = code;
- }
-
- bool isGenericClass() const
- {
- return m_genericClass;
- }
- void setGenericClass(bool isGeneric)
- {
- m_genericClass = isGeneric;
- }
-
- bool deleteInMainThread() const { return m_deleteInMainThread; }
- void setDeleteInMainThread(bool d) { m_deleteInMainThread = d; }
-
- CopyableFlag copyable() const
- {
- return m_copyableFlag;
- }
- void setCopyable(CopyableFlag flag)
- {
- m_copyableFlag = flag;
- }
-
- QString hashFunction() const
- {
- return m_hashFunction;
- }
- void setHashFunction(const QString &hashFunction)
- {
- m_hashFunction = hashFunction;
- }
-
- void setBaseContainerType(const ComplexTypeEntry *baseContainer)
- {
- m_baseContainerType = baseContainer;
- }
-
- const ComplexTypeEntry* baseContainerType() const
- {
- return m_baseContainerType;
- }
-
- TypeSystem::ExceptionHandling exceptionHandling() const { return m_exceptionHandling; }
- void setExceptionHandling(TypeSystem::ExceptionHandling e) { m_exceptionHandling = e; }
-
- TypeSystem::AllowThread allowThread() const { return m_allowThread; }
- void setAllowThread(TypeSystem::AllowThread allowThread) { m_allowThread = allowThread; }
-
- QString defaultConstructor() const;
- void setDefaultConstructor(const QString& defaultConstructor);
- bool hasDefaultConstructor() const;
-
- TypeEntry *clone() const override;
-
- void useAsTypedef(const ComplexTypeEntry *source);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-protected:
- ComplexTypeEntry(const ComplexTypeEntry &);
-
-private:
- AddedFunctionList m_addedFunctions;
- FunctionModificationList m_functionMods;
- FieldModificationList m_fieldMods;
- QString m_defaultConstructor;
- QString m_defaultSuperclass;
- QString m_qualifiedCppName;
-
- uint m_polymorphicBase : 1;
- uint m_genericClass : 1;
- uint m_deleteInMainThread : 1;
-
- QString m_polymorphicIdValue;
- QString m_targetType;
- TypeFlags m_typeFlags;
- CopyableFlag m_copyableFlag = Unknown;
- QString m_hashFunction;
-
- const ComplexTypeEntry* m_baseContainerType = nullptr;
- // For class functions
- TypeSystem::ExceptionHandling m_exceptionHandling = TypeSystem::ExceptionHandling::Unspecified;
- TypeSystem::AllowThread m_allowThread = TypeSystem::AllowThread::Unspecified;
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(ComplexTypeEntry::TypeFlags)
-
-class TypedefEntry : public ComplexTypeEntry
-{
-public:
- explicit TypedefEntry(const QString &entryName,
- const QString &sourceType,
- const QVersionNumber &vr,
- const TypeEntry *parent);
-
- QString sourceType() const { return m_sourceType; }
- void setSourceType(const QString &s) { m_sourceType =s; }
-
- TypeEntry *clone() const override;
-
- ComplexTypeEntry *source() const { return m_source; }
- void setSource(ComplexTypeEntry *source) { m_source = source; }
-
- ComplexTypeEntry *target() const { return m_target; }
- void setTarget(ComplexTypeEntry *target) { m_target = target; }
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-protected:
- TypedefEntry(const TypedefEntry &);
-
-private:
- QString m_sourceType;
- ComplexTypeEntry *m_source = nullptr;
- ComplexTypeEntry *m_target = nullptr;
-};
-
-class ContainerTypeEntry : public ComplexTypeEntry
-{
- Q_GADGET
-public:
- enum ContainerKind {
- NoContainer,
- ListContainer,
- StringListContainer,
- LinkedListContainer,
- VectorContainer,
- StackContainer,
- QueueContainer,
- SetContainer,
- MapContainer,
- MultiMapContainer,
- HashContainer,
- MultiHashContainer,
- PairContainer,
- };
- Q_ENUM(ContainerKind)
-
- explicit ContainerTypeEntry(const QString &entryName, ContainerKind containerKind,
- const QVersionNumber &vr, const TypeEntry *parent);
-
- ContainerKind containerKind() const
- {
- return m_containerKind;
- }
-
- QString typeName() const;
- QString qualifiedCppName() const override;
-
- TypeEntry *clone() const override;
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-protected:
- ContainerTypeEntry(const ContainerTypeEntry &);
-
-private:
- ContainerKind m_containerKind;
-};
-
-class SmartPointerTypeEntry : public ComplexTypeEntry
-{
-public:
- using Instantiations = QVector<const TypeEntry *>;
-
- explicit SmartPointerTypeEntry(const QString &entryName,
- const QString &getterName,
- const QString &smartPointerType,
- const QString &refCountMethodName,
- const QVersionNumber &vr,
- const TypeEntry *parent);
-
- QString getter() const
- {
- return m_getterName;
- }
-
- QString refCountMethodName() const
- {
- return m_refCountMethodName;
- }
-
- TypeEntry *clone() const override;
-
- Instantiations instantiations() const { return m_instantiations; }
- void setInstantiations(const Instantiations &i) { m_instantiations = i; }
- bool matchesInstantiation(const TypeEntry *e) const;
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-protected:
- SmartPointerTypeEntry(const SmartPointerTypeEntry &);
-
-private:
- QString m_getterName;
- QString m_smartPointerType;
- QString m_refCountMethodName;
- Instantiations m_instantiations;
-};
-
-class NamespaceTypeEntry : public ComplexTypeEntry
-{
-public:
- explicit NamespaceTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- TypeEntry *clone() const override;
-
- const NamespaceTypeEntry *extends() const { return m_extends; }
- void setExtends(const NamespaceTypeEntry *e) { m_extends = e; }
-
- const QRegularExpression &filePattern() const { return m_filePattern; } // restrict files
- void setFilePattern(const QRegularExpression &r);
-
- bool hasPattern() const { return m_hasPattern; }
-
- bool matchesFile(const QString &needle) const;
-
- bool isVisible() const;
- void setVisibility(TypeSystem::Visibility v) { m_visibility = v; }
-
- // C++ 11 inline namespace, from code model
- bool isInlineNamespace() const { return m_inlineNamespace; }
- void setInlineNamespace(bool i) { m_inlineNamespace = i; }
-
- static bool isVisibleScope(const TypeEntry *e);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &d) const override;
-#endif
-
-protected:
- NamespaceTypeEntry(const NamespaceTypeEntry &);
-
-private:
- QRegularExpression m_filePattern;
- const NamespaceTypeEntry *m_extends = nullptr;
- TypeSystem::Visibility m_visibility = TypeSystem::Visibility::Auto;
- bool m_hasPattern = false;
- bool m_inlineNamespace = false;
-};
-
-class ValueTypeEntry : public ComplexTypeEntry
-{
-public:
- explicit ValueTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- bool isValue() const override;
-
- TypeEntry *clone() const override;
-
-protected:
- explicit ValueTypeEntry(const QString &entryName, Type t, const QVersionNumber &vr,
- const TypeEntry *parent);
- ValueTypeEntry(const ValueTypeEntry &);
-};
-
-class FunctionTypeEntry : public TypeEntry
-{
-public:
- explicit FunctionTypeEntry(const QString& name, const QString& signature,
- const QVersionNumber &vr,
- const TypeEntry *parent);
- void addSignature(const QString& signature)
- {
- m_signatures << signature;
- }
-
- QStringList signatures() const
- {
- return m_signatures;
- }
-
- bool hasSignature(const QString& signature) const
- {
- return m_signatures.contains(signature);
- }
-
- TypeEntry *clone() const override;
-
-protected:
- FunctionTypeEntry(const FunctionTypeEntry &);
-
-private:
- QStringList m_signatures;
-};
-
-class ObjectTypeEntry : public ComplexTypeEntry
-{
-public:
- explicit ObjectTypeEntry(const QString &entryName, const QVersionNumber &vr,
- const TypeEntry *parent);
-
- TypeEntry *clone() const override;
-
-protected:
- ObjectTypeEntry(const ObjectTypeEntry &);
-};
-
-struct TypeRejection
-{
- enum MatchType
- {
- ExcludeClass, // Match className only
- Function, // Match className and function name
- Field, // Match className and field name
- Enum, // Match className and enum name
- ArgumentType, // Match className and argument type
- ReturnType, // Match className and return type
- Invalid
- };
-
- QRegularExpression className;
- QRegularExpression pattern;
- MatchType matchType = Invalid;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug d, const TypeRejection &r);
-#endif
-
-class CustomConversion
-{
-public:
- CustomConversion(TypeEntry* ownerType);
- ~CustomConversion();
-
- const TypeEntry* ownerType() const;
- QString nativeToTargetConversion() const;
- void setNativeToTargetConversion(const QString& nativeToTargetConversion);
-
- class TargetToNativeConversion
- {
- public:
- TargetToNativeConversion(const QString& sourceTypeName,
- const QString& sourceTypeCheck,
- const QString& conversion = QString());
- ~TargetToNativeConversion();
-
- const TypeEntry* sourceType() const;
- void setSourceType(const TypeEntry* sourceType);
- bool isCustomType() const;
- QString sourceTypeName() const;
- QString sourceTypeCheck() const;
- QString conversion() const;
- void setConversion(const QString& conversion);
- private:
- struct TargetToNativeConversionPrivate;
- TargetToNativeConversionPrivate* m_d;
- };
-
- /**
- * Returns true if the target to C++ custom conversions should
- * replace the original existing ones, and false if the custom
- * conversions should be added to the original.
- */
- bool replaceOriginalTargetToNativeConversions() const;
- void setReplaceOriginalTargetToNativeConversions(bool replaceOriginalTargetToNativeConversions);
-
- using TargetToNativeConversions = QVector<TargetToNativeConversion *>;
- bool hasTargetToNativeConversions() const;
- TargetToNativeConversions& targetToNativeConversions();
- const TargetToNativeConversions& targetToNativeConversions() const;
- void addTargetToNativeConversion(const QString& sourceTypeName,
- const QString& sourceTypeCheck,
- const QString& conversion = QString());
-private:
- struct CustomConversionPrivate;
- CustomConversionPrivate* m_d;
-};
-
-#endif // TYPESYSTEM_H
diff --git a/sources/shiboken2/ApiExtractor/typesystem_enums.h b/sources/shiboken2/ApiExtractor/typesystem_enums.h
deleted file mode 100644
index 120c9417f..000000000
--- a/sources/shiboken2/ApiExtractor/typesystem_enums.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TYPESYSTEM_ENUMS_H
-#define TYPESYSTEM_ENUMS_H
-
-namespace TypeSystem
-{
-enum Language {
- NoLanguage = 0x0000,
- TargetLangCode = 0x0001,
- NativeCode = 0x0002,
- ShellCode = 0x0004,
- ShellDeclaration = 0x0008,
- PackageInitializer = 0x0010,
- DestructorFunction = 0x0020,
- Constructors = 0x0040,
- Interface = 0x0080,
-
- // masks
- All = TargetLangCode
- | NativeCode
- | ShellCode
- | ShellDeclaration
- | PackageInitializer
- | Constructors
- | Interface
- | DestructorFunction,
-
- TargetLangAndNativeCode = TargetLangCode | NativeCode
-};
-
-enum class AllowThread {
- Allow,
- Disallow,
- Auto,
- Unspecified
-};
-
-enum Ownership {
- InvalidOwnership,
- DefaultOwnership,
- TargetLangOwnership,
- CppOwnership
-};
-
-enum CodeSnipPosition {
- CodeSnipPositionBeginning,
- CodeSnipPositionEnd,
- CodeSnipPositionAfterThis,
- // QtScript
- CodeSnipPositionDeclaration,
- CodeSnipPositionPrototypeInitialization,
- CodeSnipPositionConstructorInitialization,
- CodeSnipPositionConstructor,
- CodeSnipPositionAny,
- CodeSnipPositionInvalid
-};
-
-enum DocModificationMode {
- DocModificationAppend,
- DocModificationPrepend,
- DocModificationReplace,
- DocModificationXPathReplace,
- DocModificationInvalid
-};
-
-enum class ExceptionHandling {
- Unspecified,
- Off,
- AutoDefaultToOff,
- AutoDefaultToOn,
- On
-};
-
-enum Visibility { // For namespaces
- Unspecified,
- Visible,
- Invisible,
- Auto
-};
-
-} // namespace TypeSystem
-
-#endif // TYPESYSTEM_ENUMS_H
diff --git a/sources/shiboken2/ApiExtractor/typesystem_typedefs.h b/sources/shiboken2/ApiExtractor/typesystem_typedefs.h
deleted file mode 100644
index 73f92b294..000000000
--- a/sources/shiboken2/ApiExtractor/typesystem_typedefs.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TYPESYSTEM_TYPEDEFS_H
-#define TYPESYSTEM_TYPEDEFS_H
-
-#include <QtCore/QHash>
-#include <QtCore/QList>
-#include <QtCore/QSharedPointer>
-#include <QtCore/QVector>
-
-class CodeSnip;
-class DocModification;
-
-struct AddedFunction;
-struct FieldModification;
-struct FunctionModification;
-class TypeEntry;
-
-using AddedFunctionPtr = QSharedPointer<AddedFunction>;
-using AddedFunctionList = QVector<AddedFunctionPtr>;
-using CodeSnipList = QVector<CodeSnip>;
-using DocModificationList = QVector<DocModification>;
-using FieldModificationList = QVector<FieldModification>;
-using FunctionModificationList = QVector<FunctionModification>;
-using TypeEntries = QVector<const TypeEntry *>;
-
-#endif // TYPESYSTEM_TYPEDEFS_H
diff --git a/sources/shiboken2/ApiExtractor/typesystemparser.cpp b/sources/shiboken2/ApiExtractor/typesystemparser.cpp
deleted file mode 100644
index 9fdf81821..000000000
--- a/sources/shiboken2/ApiExtractor/typesystemparser.cpp
+++ /dev/null
@@ -1,3076 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "typesystemparser.h"
-#include "typedatabase.h"
-#include "messages.h"
-#include "reporthandler.h"
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QFileInfo>
-#include <QtCore/QRegularExpression>
-#include <QtCore/QSet>
-#include <QtCore/QStringView>
-#include <QtCore/QStringAlgorithms>
-#include <QtCore/QXmlStreamAttributes>
-#include <QtCore/QXmlStreamReader>
-#include <QtCore/QXmlStreamEntityResolver>
-
-#include <algorithm>
-
-const char *TARGET_CONVERSION_RULE_FLAG = "0";
-const char *NATIVE_CONVERSION_RULE_FLAG = "1";
-
-static inline QString allowThreadAttribute() { return QStringLiteral("allow-thread"); }
-static inline QString colonColon() { return QStringLiteral("::"); }
-static inline QString copyableAttribute() { return QStringLiteral("copyable"); }
-static inline QString accessAttribute() { return QStringLiteral("access"); }
-static inline QString actionAttribute() { return QStringLiteral("action"); }
-static inline QString quoteAfterLineAttribute() { return QStringLiteral("quote-after-line"); }
-static inline QString quoteBeforeLineAttribute() { return QStringLiteral("quote-before-line"); }
-static inline QString textAttribute() { return QStringLiteral("text"); }
-static inline QString nameAttribute() { return QStringLiteral("name"); }
-static inline QString sinceAttribute() { return QStringLiteral("since"); }
-static inline QString untilAttribute() { return QStringLiteral("until"); }
-static inline QString defaultSuperclassAttribute() { return QStringLiteral("default-superclass"); }
-static inline QString deleteInMainThreadAttribute() { return QStringLiteral("delete-in-main-thread"); }
-static inline QString deprecatedAttribute() { return QStringLiteral("deprecated"); }
-static inline QString exceptionHandlingAttribute() { return QStringLiteral("exception-handling"); }
-static inline QString extensibleAttribute() { return QStringLiteral("extensible"); }
-static inline QString fileNameAttribute() { return QStringLiteral("file-name"); }
-static inline QString flagsAttribute() { return QStringLiteral("flags"); }
-static inline QString forceAbstractAttribute() { return QStringLiteral("force-abstract"); }
-static inline QString forceIntegerAttribute() { return QStringLiteral("force-integer"); }
-static inline QString formatAttribute() { return QStringLiteral("format"); }
-static inline QString classAttribute() { return QStringLiteral("class"); }
-static inline QString generateAttribute() { return QStringLiteral("generate"); }
-static inline QString genericClassAttribute() { return QStringLiteral("generic-class"); }
-static inline QString indexAttribute() { return QStringLiteral("index"); }
-static inline QString invalidateAfterUseAttribute() { return QStringLiteral("invalidate-after-use"); }
-static inline QString locationAttribute() { return QStringLiteral("location"); }
-static inline QString modifiedTypeAttribute() { return QStringLiteral("modified-type"); }
-static inline QString modifierAttribute() { return QStringLiteral("modifier"); }
-static inline QString ownershipAttribute() { return QStringLiteral("owner"); }
-static inline QString packageAttribute() { return QStringLiteral("package"); }
-static inline QString positionAttribute() { return QStringLiteral("position"); }
-static inline QString preferredConversionAttribute() { return QStringLiteral("preferred-conversion"); }
-static inline QString preferredTargetLangTypeAttribute() { return QStringLiteral("preferred-target-lang-type"); }
-static inline QString removeAttribute() { return QStringLiteral("remove"); }
-static inline QString renameAttribute() { return QStringLiteral("rename"); }
-static inline QString readAttribute() { return QStringLiteral("read"); }
-static inline QString targetLangNameAttribute() { return QStringLiteral("target-lang-name"); }
-static inline QString writeAttribute() { return QStringLiteral("write"); }
-static inline QString replaceAttribute() { return QStringLiteral("replace"); }
-static inline QString toAttribute() { return QStringLiteral("to"); }
-static inline QString signatureAttribute() { return QStringLiteral("signature"); }
-static inline QString snippetAttribute() { return QStringLiteral("snippet"); }
-static inline QString staticAttribute() { return QStringLiteral("static"); }
-static inline QString threadAttribute() { return QStringLiteral("thread"); }
-static inline QString sourceAttribute() { return QStringLiteral("source"); }
-static inline QString streamAttribute() { return QStringLiteral("stream"); }
-static inline QString xPathAttribute() { return QStringLiteral("xpath"); }
-static inline QString virtualSlotAttribute() { return QStringLiteral("virtual-slot"); }
-static inline QString visibleAttribute() { return QStringLiteral("visible"); }
-static inline QString enumIdentifiedByValueAttribute() { return QStringLiteral("identified-by-value"); }
-
-static inline QString noAttributeValue() { return QStringLiteral("no"); }
-static inline QString yesAttributeValue() { return QStringLiteral("yes"); }
-static inline QString trueAttributeValue() { return QStringLiteral("true"); }
-static inline QString falseAttributeValue() { return QStringLiteral("false"); }
-
-static QVector<CustomConversion *> customConversionsForReview;
-
-// Set a regular expression for rejection from text. By legacy, those are fixed
-// strings, except for '*' meaning 'match all'. Enclosing in "^..$"
-// indicates regular expression.
-static bool setRejectionRegularExpression(const QString &patternIn,
- QRegularExpression *re,
- QString *errorMessage)
-{
- QString pattern;
- if (patternIn.startsWith(QLatin1Char('^')) && patternIn.endsWith(QLatin1Char('$')))
- pattern = patternIn;
- else if (patternIn == QLatin1String("*"))
- pattern = QStringLiteral("^.*$");
- else
- pattern = QLatin1Char('^') + QRegularExpression::escape(patternIn) + QLatin1Char('$');
- re->setPattern(pattern);
- if (!re->isValid()) {
- *errorMessage = msgInvalidRegularExpression(patternIn, re->errorString());
- return false;
- }
- return true;
-}
-
-// Extract a snippet from a file within annotation "// @snippet label".
-static QString extractSnippet(const QString &code, const QString &snippetLabel)
-{
- if (snippetLabel.isEmpty())
- return code;
- const QString pattern = QStringLiteral(R"(^\s*//\s*@snippet\s+)")
- + QRegularExpression::escape(snippetLabel)
- + QStringLiteral(R"(\s*$)");
- const QRegularExpression snippetRe(pattern);
- Q_ASSERT(snippetRe.isValid());
-
- bool useLine = false;
- QString result;
- const auto lines = code.splitRef(QLatin1Char('\n'));
- for (const QStringRef &line : lines) {
- if (snippetRe.match(line).hasMatch()) {
- useLine = !useLine;
- if (!useLine)
- break; // End of snippet reached
- } else if (useLine)
- result += line.toString() + QLatin1Char('\n');
- }
- return result;
-}
-
-template <class EnumType, Qt::CaseSensitivity cs = Qt::CaseInsensitive>
-struct EnumLookup
-{
- QStringView name;
- EnumType value;
-};
-
-template <class EnumType, Qt::CaseSensitivity cs>
-bool operator==(const EnumLookup<EnumType, cs> &e1, const EnumLookup<EnumType, cs> &e2)
-{
- return e1.name.compare(e2.name, cs) == 0;
-}
-
-template <class EnumType, Qt::CaseSensitivity cs>
-bool operator<(const EnumLookup<EnumType, cs> &e1, const EnumLookup<EnumType, cs> &e2)
-{
- return e1.name.compare(e2.name, cs) < 0;
-}
-
-// Helper macros to define lookup functions that take a QStringView needle
-// and an optional default return value.
-#define ENUM_LOOKUP_BEGIN(EnumType, caseSensitivity, functionName, defaultReturnValue) \
-static EnumType functionName(QStringView needle, EnumType defaultValue = defaultReturnValue) \
-{ \
- typedef EnumLookup<EnumType, caseSensitivity> HaystackEntry; \
- static const HaystackEntry haystack[] =
-
-#define ENUM_LOOKUP_LINEAR_SEARCH() \
- const auto end = haystack + sizeof(haystack) / sizeof(haystack[0]); \
- const auto it = std::find(haystack, end, HaystackEntry{needle, defaultValue}); \
- return it != end ? it->value : defaultValue; \
-}
-
-#define ENUM_LOOKUP_BINARY_SEARCH() \
- const auto end = haystack + sizeof(haystack) / sizeof(haystack[0]); \
- const HaystackEntry needleEntry{needle, defaultValue}; \
- const auto lb = std::lower_bound(haystack, end, needleEntry); \
- return lb != end && *lb == needleEntry ? lb->value : defaultValue; \
-}
-
-ENUM_LOOKUP_BEGIN(TypeSystem::AllowThread, Qt::CaseInsensitive,
- allowThreadFromAttribute, TypeSystem::AllowThread::Unspecified)
- {
- {u"yes", TypeSystem::AllowThread::Allow},
- {u"true", TypeSystem::AllowThread::Allow},
- {u"auto", TypeSystem::AllowThread::Auto},
- {u"no", TypeSystem::AllowThread::Disallow},
- {u"false", TypeSystem::AllowThread::Disallow},
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(TypeSystem::Language, Qt::CaseInsensitive,
- languageFromAttribute, TypeSystem::NoLanguage)
- {
- {u"all", TypeSystem::All}, // sorted!
- {u"constructors", TypeSystem::Constructors},
- {u"destructor-function", TypeSystem::DestructorFunction},
- {u"interface", TypeSystem::Interface},
- {u"library-initializer", TypeSystem::PackageInitializer},
- {u"native", TypeSystem::NativeCode}, // em algum lugar do cpp
- {u"shell", TypeSystem::ShellCode}, // coloca no header, mas antes da declaracao da classe
- {u"shell-declaration", TypeSystem::ShellDeclaration},
- {u"target", TypeSystem::TargetLangCode} // em algum lugar do cpp
- };
-ENUM_LOOKUP_BINARY_SEARCH()
-
-ENUM_LOOKUP_BEGIN(TypeSystem::Ownership, Qt::CaseInsensitive,
- ownershipFromFromAttribute, TypeSystem::InvalidOwnership)
- {
- {u"target", TypeSystem::TargetLangOwnership},
- {u"c++", TypeSystem::CppOwnership},
- {u"default", TypeSystem::DefaultOwnership}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(AddedFunction::Access, Qt::CaseInsensitive,
- addedFunctionAccessFromAttribute, AddedFunction::InvalidAccess)
- {
- {u"public", AddedFunction::Public},
- {u"protected", AddedFunction::Protected},
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(Modification::Modifiers, Qt::CaseSensitive,
- modifierFromAttribute, Modification::InvalidModifier)
- {
- {u"private", Modification::Private},
- {u"public", Modification::Public},
- {u"protected", Modification::Protected},
- {u"friendly", Modification::Friendly},
- {u"rename", Modification::Rename},
- {u"final", Modification::Final},
- {u"non-final", Modification::NonFinal}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(ReferenceCount::Action, Qt::CaseInsensitive,
- referenceCountFromAttribute, ReferenceCount::Invalid)
- {
- {u"add", ReferenceCount::Add},
- {u"add-all", ReferenceCount::AddAll},
- {u"remove", ReferenceCount::Remove},
- {u"set", ReferenceCount::Set},
- {u"ignore", ReferenceCount::Ignore}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(ArgumentOwner::Action, Qt::CaseInsensitive,
- argumentOwnerActionFromAttribute, ArgumentOwner::Invalid)
- {
- {u"add", ArgumentOwner::Add},
- {u"remove", ArgumentOwner::Remove}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(TypeSystem::CodeSnipPosition, Qt::CaseInsensitive,
- codeSnipPositionFromAttribute, TypeSystem::CodeSnipPositionInvalid)
- {
- {u"beginning", TypeSystem::CodeSnipPositionBeginning},
- {u"end", TypeSystem::CodeSnipPositionEnd},
- {u"declaration", TypeSystem::CodeSnipPositionDeclaration},
- {u"prototype-initialization", TypeSystem::CodeSnipPositionPrototypeInitialization},
- {u"constructor-initialization", TypeSystem::CodeSnipPositionConstructorInitialization},
- {u"constructor", TypeSystem::CodeSnipPositionConstructor}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(Include::IncludeType, Qt::CaseInsensitive,
- locationFromAttribute, Include::InvalidInclude)
- {
- {u"global", Include::IncludePath},
- {u"local", Include::LocalPath},
- {u"target", Include::TargetLangImport}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(TypeSystem::DocModificationMode, Qt::CaseInsensitive,
- docModificationFromAttribute, TypeSystem::DocModificationInvalid)
- {
- {u"append", TypeSystem::DocModificationAppend},
- {u"prepend", TypeSystem::DocModificationPrepend},
- {u"replace", TypeSystem::DocModificationReplace}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(ContainerTypeEntry::ContainerKind, Qt::CaseSensitive,
- containerTypeFromAttribute, ContainerTypeEntry::NoContainer)
- {
- {u"list", ContainerTypeEntry::ListContainer},
- {u"string-list", ContainerTypeEntry::StringListContainer},
- {u"linked-list", ContainerTypeEntry::LinkedListContainer},
- {u"vector", ContainerTypeEntry::VectorContainer},
- {u"stack", ContainerTypeEntry::StackContainer},
- {u"queue", ContainerTypeEntry::QueueContainer},
- {u"set", ContainerTypeEntry::SetContainer},
- {u"map", ContainerTypeEntry::MapContainer},
- {u"multi-map", ContainerTypeEntry::MultiMapContainer},
- {u"hash", ContainerTypeEntry::HashContainer},
- {u"multi-hash", ContainerTypeEntry::MultiHashContainer},
- {u"pair", ContainerTypeEntry::PairContainer}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(TypeRejection::MatchType, Qt::CaseSensitive,
- typeRejectionFromAttribute, TypeRejection::Invalid)
- {
- {u"class", TypeRejection::ExcludeClass},
- {u"function-name", TypeRejection::Function},
- {u"field-name", TypeRejection::Field},
- {u"enum-name", TypeRejection::Enum },
- {u"argument-type", TypeRejection::ArgumentType},
- {u"return-type", TypeRejection::ReturnType}
- };
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(TypeSystem::ExceptionHandling, Qt::CaseSensitive,
- exceptionHandlingFromAttribute, TypeSystem::ExceptionHandling::Unspecified)
-{
- {u"no", TypeSystem::ExceptionHandling::Off},
- {u"false", TypeSystem::ExceptionHandling::Off},
- {u"auto-off", TypeSystem::ExceptionHandling::AutoDefaultToOff},
- {u"auto-on", TypeSystem::ExceptionHandling::AutoDefaultToOn},
- {u"yes", TypeSystem::ExceptionHandling::On},
- {u"true", TypeSystem::ExceptionHandling::On},
-};
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-ENUM_LOOKUP_BEGIN(StackElement::ElementType, Qt::CaseInsensitive,
- elementFromTag, StackElement::None)
- {
- {u"access", StackElement::Access}, // sorted!
- {u"add-conversion", StackElement::AddConversion},
- {u"add-function", StackElement::AddFunction},
- {u"argument-map", StackElement::ArgumentMap},
- {u"array", StackElement::Array},
- {u"container-type", StackElement::ContainerTypeEntry},
- {u"conversion-rule", StackElement::ConversionRule},
- {u"custom-constructor", StackElement::CustomMetaConstructor},
- {u"custom-destructor", StackElement::CustomMetaDestructor},
- {u"custom-type", StackElement::CustomTypeEntry},
- {u"define-ownership", StackElement::DefineOwnership},
- {u"enum-type", StackElement::EnumTypeEntry},
- {u"extra-includes", StackElement::ExtraIncludes},
- {u"function", StackElement::FunctionTypeEntry},
- {u"include", StackElement::Include},
- {u"inject-code", StackElement::InjectCode},
- {u"inject-documentation", StackElement::InjectDocumentation},
- {u"insert-template", StackElement::TemplateInstanceEnum},
- {u"interface-type", StackElement::InterfaceTypeEntry},
- {u"load-typesystem", StackElement::LoadTypesystem},
- {u"modify-argument", StackElement::ModifyArgument},
- {u"modify-documentation", StackElement::ModifyDocumentation},
- {u"modify-field", StackElement::ModifyField},
- {u"modify-function", StackElement::ModifyFunction},
- {u"namespace-type", StackElement::NamespaceTypeEntry},
- {u"native-to-target", StackElement::NativeToTarget},
- {u"no-null-pointer", StackElement::NoNullPointers},
- {u"object-type", StackElement::ObjectTypeEntry},
- {u"parent", StackElement::ParentOwner},
- {u"primitive-type", StackElement::PrimitiveTypeEntry},
- {u"reference-count", StackElement::ReferenceCount},
- {u"reject-enum-value", StackElement::RejectEnumValue},
- {u"rejection", StackElement::Rejection},
- {u"remove", StackElement::Removal},
- {u"remove-argument", StackElement::RemoveArgument},
- {u"remove-default-expression", StackElement::RemoveDefaultExpression},
- {u"rename", StackElement::Rename},
- {u"replace", StackElement::Replace},
- {u"replace-default-expression", StackElement::ReplaceDefaultExpression},
- {u"replace-type", StackElement::ReplaceType},
- {u"smart-pointer-type", StackElement::SmartPointerTypeEntry},
- {u"suppress-warning", StackElement::SuppressedWarning},
- {u"system-include", StackElement::SystemInclude},
- {u"target-to-native", StackElement::TargetToNative},
- {u"template", StackElement::Template},
- {u"typedef-type", StackElement::TypedefTypeEntry},
- {u"typesystem", StackElement::Root},
- {u"value-type", StackElement::ValueTypeEntry},
- };
-ENUM_LOOKUP_BINARY_SEARCH()
-
-ENUM_LOOKUP_BEGIN(TypeSystem::Visibility, Qt::CaseSensitive,
- visibilityFromAttribute, TypeSystem::Visibility::Unspecified)
-{
- {u"no", TypeSystem::Visibility::Invisible},
- {u"false", TypeSystem::Visibility::Invisible},
- {u"auto", TypeSystem::Visibility::Auto},
- {u"yes", TypeSystem::Visibility::Visible},
- {u"true", TypeSystem::Visibility::Visible},
-};
-ENUM_LOOKUP_LINEAR_SEARCH()
-
-static int indexOfAttribute(const QXmlStreamAttributes &atts,
- QStringView name)
-{
- for (int i = 0, size = atts.size(); i < size; ++i) {
- if (atts.at(i).qualifiedName() == name)
- return i;
- }
- return -1;
-}
-
-static QString msgMissingAttribute(const QString &a)
-{
- return QLatin1String("Required attribute '") + a
- + QLatin1String("' missing.");
-}
-
-QTextStream &operator<<(QTextStream &str, const QXmlStreamAttribute &attribute)
-{
- str << attribute.qualifiedName() << "=\"" << attribute.value() << '"';
- return str;
-}
-
-static QString msgInvalidAttributeValue(const QXmlStreamAttribute &attribute)
-{
- QString result;
- QTextStream(&result) << "Invalid attribute value:" << attribute;
- return result;
-}
-
-static QString msgUnusedAttributes(const QStringRef &tag, const QXmlStreamAttributes &attributes)
-{
- QString result;
- QTextStream str(&result);
- str << attributes.size() << " attributes(s) unused on <" << tag << ">: ";
- for (int i = 0, size = attributes.size(); i < size; ++i) {
- if (i)
- str << ", ";
- str << attributes.at(i);
- }
- return result;
-}
-
-// QXmlStreamEntityResolver::resolveEntity(publicId, systemId) is not
-// implemented; resolve via undeclared entities instead.
-class TypeSystemEntityResolver : public QXmlStreamEntityResolver
-{
-public:
- explicit TypeSystemEntityResolver(const QString &currentPath) :
- m_currentPath(currentPath) {}
-
- QString resolveUndeclaredEntity(const QString &name) override;
-
-private:
- QString readFile(const QString &entityName, QString *errorMessage) const;
-
- const QString m_currentPath;
- QHash<QString, QString> m_cache;
-};
-
-QString TypeSystemEntityResolver::readFile(const QString &entityName, QString *errorMessage) const
-{
- QString fileName = entityName;
- if (!fileName.contains(QLatin1Char('.')))
- fileName += QLatin1String(".xml");
- QString path = TypeDatabase::instance()->modifiedTypesystemFilepath(fileName, m_currentPath);
- if (!QFileInfo::exists(path)) // PySide2-specific hack
- fileName.prepend(QLatin1String("typesystem_"));
- path = TypeDatabase::instance()->modifiedTypesystemFilepath(fileName, m_currentPath);
- if (!QFileInfo::exists(path)) {
- *errorMessage = QLatin1String("Unable to resolve: ") + entityName;
- return QString();
- }
- QFile file(path);
- if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- *errorMessage = msgCannotOpenForReading(file);
- return QString();
- }
- QString result = QString::fromUtf8(file.readAll()).trimmed();
- // Remove license header comments on which QXmlStreamReader chokes
- if (result.startsWith(QLatin1String("<!--"))) {
- const int commentEnd = result.indexOf(QLatin1String("-->"));
- if (commentEnd != -1) {
- result.remove(0, commentEnd + 3);
- result = result.trimmed();
- }
- }
- return result;
-}
-
-QString TypeSystemEntityResolver::resolveUndeclaredEntity(const QString &name)
-{
- auto it = m_cache.find(name);
- if (it == m_cache.end()) {
- QString errorMessage;
- it = m_cache.insert(name, readFile(name, &errorMessage));
- if (it.value().isEmpty()) { // The parser will fail and display the line number.
- qCWarning(lcShiboken, "%s",
- qPrintable(msgCannotResolveEntity(name, errorMessage)));
- }
- }
- return it.value();
-}
-
-TypeSystemParser::TypeSystemParser(TypeDatabase *database, bool generate) :
- m_database(database),
- m_generate(generate ? TypeEntry::GenerateAll : TypeEntry::GenerateForSubclass)
-{
-}
-
-TypeSystemParser::~TypeSystemParser() = default;
-
-static QString readerFileName(const QXmlStreamReader &reader)
-{
- const auto *file = qobject_cast<const QFile *>(reader.device());
- return file != nullptr ? file->fileName() : QString();
-}
-
-static QString msgReaderMessage(const QXmlStreamReader &reader,
- const char *type,
- const QString &what)
-{
- QString message;
- QTextStream str(&message);
- str << type << ": ";
- const QString fileName = readerFileName(reader);
- if (fileName.isEmpty())
- str << "<stdin>:";
- else
- str << QDir::toNativeSeparators(fileName) << ':';
- str << reader.lineNumber() << ':' << reader.columnNumber()
- << ": " << what;
- return message;
-}
-
-static QString msgReaderWarning(const QXmlStreamReader &reader, const QString &what)
-{
- return msgReaderMessage(reader, "Warning", what);
-}
-
-static QString msgReaderError(const QXmlStreamReader &reader, const QString &what)
-{
- return msgReaderMessage(reader, "Error", what);
-}
-
-static QString msgUnimplementedElementWarning(const QXmlStreamReader &reader,
- const QStringRef &name)
-{
- const QString message = QLatin1String("The element \"") +
- name + QLatin1String("\" is not implemented.");
- return msgReaderMessage(reader, "Warning", message);
-}
-
-static QString msgUnimplementedAttributeWarning(const QXmlStreamReader &reader,
- const QStringRef &name)
-{
- const QString message = QLatin1String("The attribute \"") +
- name + QLatin1String("\" is not implemented.");
- return msgReaderMessage(reader, "Warning", message);
-}
-
-static inline QString msgUnimplementedAttributeWarning(const QXmlStreamReader &reader,
- const QXmlStreamAttribute &attribute)
-{
- return msgUnimplementedAttributeWarning(reader, attribute.qualifiedName());
-}
-
-static QString
- msgUnimplementedAttributeValueWarning(const QXmlStreamReader &reader,
- QStringView name, QStringView value)
-{
- QString message;
- QTextStream(&message) << "The value \"" << value
- << "\" of the attribute \"" << name << "\" is not implemented.";
- return msgReaderMessage(reader, "Warning", message);
-}
-
-static inline
- QString msgUnimplementedAttributeValueWarning(const QXmlStreamReader &reader,
- const QXmlStreamAttribute &attribute)
-{
- return msgUnimplementedAttributeValueWarning(reader,
- attribute.qualifiedName(),
- attribute.value());
-}
-
-static bool addRejection(TypeDatabase *database, QXmlStreamAttributes *attributes,
- QString *errorMessage)
-{
- const int classIndex = indexOfAttribute(*attributes, classAttribute());
- if (classIndex == -1) {
- *errorMessage = msgMissingAttribute(classAttribute());
- return false;
- }
-
- TypeRejection rejection;
- const QString className = attributes->takeAt(classIndex).value().toString();
- if (!setRejectionRegularExpression(className, &rejection.className, errorMessage))
- return false;
-
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- const TypeRejection::MatchType type = typeRejectionFromAttribute(name);
- switch (type) {
- case TypeRejection::Function:
- case TypeRejection::Field:
- case TypeRejection::Enum:
- case TypeRejection::ArgumentType:
- case TypeRejection::ReturnType: {
- const QString pattern = attributes->takeAt(i).value().toString();
- if (!setRejectionRegularExpression(pattern, &rejection.pattern, errorMessage))
- return false;
- rejection.matchType = type;
- database->addRejection(rejection);
- return true;
- }
- default:
- break;
- }
- }
-
- // Special case: When all fields except class are empty, completely exclude class
- if (className == QLatin1String("*")) {
- *errorMessage = QLatin1String("bad reject entry, neither 'class', 'function-name'"
- " nor 'field' specified");
- return false;
- }
- rejection.matchType = TypeRejection::ExcludeClass;
- database->addRejection(rejection);
- return true;
-}
-
-bool TypeSystemParser::parse(QXmlStreamReader &reader)
-{
- m_error.clear();
- m_currentPath.clear();
- m_smartPointerInstantiations.clear();
- const bool result = parseXml(reader) && setupSmartPointerInstantiations();
- m_smartPointerInstantiations.clear();
- return result;
-}
-
-bool TypeSystemParser::parseXml(QXmlStreamReader &reader)
-{
- const QString fileName = readerFileName(reader);
- if (!fileName.isEmpty())
- m_currentPath = QFileInfo(fileName).absolutePath();
- m_entityResolver.reset(new TypeSystemEntityResolver(m_currentPath));
- reader.setEntityResolver(m_entityResolver.data());
-
- while (!reader.atEnd()) {
- switch (reader.readNext()) {
- case QXmlStreamReader::NoToken:
- case QXmlStreamReader::Invalid:
- m_error = msgReaderError(reader, reader.errorString());
- return false;
- case QXmlStreamReader::StartElement:
- if (!startElement(reader)) {
- m_error = msgReaderError(reader, m_error);
- return false;
- }
-
- break;
- case QXmlStreamReader::EndElement:
- if (!endElement(reader.name())) {
- m_error = msgReaderError(reader, m_error);
- return false;
- }
- break;
- case QXmlStreamReader::Characters:
- if (!characters(reader.text())) {
- m_error = msgReaderError(reader, m_error);
- return false;
- }
- break;
- case QXmlStreamReader::StartDocument:
- case QXmlStreamReader::EndDocument:
- case QXmlStreamReader::Comment:
- case QXmlStreamReader::DTD:
- case QXmlStreamReader::EntityReference:
- case QXmlStreamReader::ProcessingInstruction:
- break;
- }
- }
- return true;
-}
-
-// Split a type list potentially with template types
-// "A<B,C>,D" -> ("A<B,C>", "D")
-static QStringList splitTypeList(const QString &s)
-{
- QStringList result;
- int templateDepth = 0;
- int lastPos = 0;
- const int size = s.size();
- for (int i = 0; i < size; ++i) {
- switch (s.at(i).toLatin1()) {
- case '<':
- ++templateDepth;
- break;
- case '>':
- --templateDepth;
- break;
- case ',':
- if (templateDepth == 0) {
- result.append(s.mid(lastPos, i - lastPos).trimmed());
- lastPos = i + 1;
- }
- break;
- }
- }
- if (lastPos < size)
- result.append(s.mid(lastPos, size - lastPos).trimmed());
- return result;
-}
-
-bool TypeSystemParser::setupSmartPointerInstantiations()
-{
- for (auto it = m_smartPointerInstantiations.cbegin(),
- end = m_smartPointerInstantiations.cend(); it != end; ++it) {
- auto smartPointerEntry = it.key();
- const auto instantiationNames = splitTypeList(it.value());
- SmartPointerTypeEntry::Instantiations instantiations;
- instantiations.reserve(instantiationNames.size());
- for (const auto &instantiationName : instantiationNames) {
- const auto types = m_database->findCppTypes(instantiationName);
- if (types.isEmpty()) {
- m_error =
- msgCannotFindTypeEntryForSmartPointer(instantiationName,
- smartPointerEntry->name());
- return false;
- }
- if (types.size() > 1) {
- m_error = msgAmbiguousTypesFound(instantiationName, types);
- return false;
- }
- instantiations.append(types.constFirst());
- }
- smartPointerEntry->setInstantiations(instantiations);
- }
- return true;
-}
-
-bool TypeSystemParser::endElement(const QStringRef &localName)
-{
- if (m_ignoreDepth) {
- --m_ignoreDepth;
- return true;
- }
-
- if (m_currentDroppedEntry) {
- if (m_currentDroppedEntryDepth == 1) {
- m_current = m_currentDroppedEntry->parent;
- delete m_currentDroppedEntry;
- m_currentDroppedEntry = nullptr;
- m_currentDroppedEntryDepth = 0;
- } else {
- --m_currentDroppedEntryDepth;
- }
- return true;
- }
-
- if (!localName.compare(QLatin1String("import-file"), Qt::CaseInsensitive))
- return true;
-
- if (!m_current)
- return true;
-
- switch (m_current->type) {
- case StackElement::Root:
- if (m_generate == TypeEntry::GenerateAll) {
- TypeDatabase::instance()->addGlobalUserFunctions(m_contextStack.top()->addedFunctions);
- TypeDatabase::instance()->addGlobalUserFunctionModifications(m_contextStack.top()->functionMods);
- for (CustomConversion *customConversion : qAsConst(customConversionsForReview)) {
- const CustomConversion::TargetToNativeConversions &toNatives = customConversion->targetToNativeConversions();
- for (CustomConversion::TargetToNativeConversion *toNative : toNatives)
- toNative->setSourceType(m_database->findType(toNative->sourceTypeName()));
- }
- }
- break;
- case StackElement::ObjectTypeEntry:
- case StackElement::ValueTypeEntry:
- case StackElement::InterfaceTypeEntry:
- case StackElement::NamespaceTypeEntry: {
- auto *centry = static_cast<ComplexTypeEntry *>(m_current->entry);
- centry->setAddedFunctions(m_contextStack.top()->addedFunctions);
- centry->setFunctionModifications(m_contextStack.top()->functionMods);
- centry->setFieldModifications(m_contextStack.top()->fieldMods);
- centry->setCodeSnips(m_contextStack.top()->codeSnips);
- centry->setDocModification(m_contextStack.top()->docModifications);
- }
- break;
- case StackElement::AddFunction: {
- // Leaving add-function: Assign all modifications to the added function
- StackElementContext *top = m_contextStack.top();
- const int modIndex = top->addedFunctionModificationIndex;
- top->addedFunctionModificationIndex = -1;
- Q_ASSERT(modIndex >= 0);
- Q_ASSERT(!top->addedFunctions.isEmpty());
- while (modIndex < top->functionMods.size())
- top->addedFunctions.last()->modifications.append(top->functionMods.takeAt(modIndex));
- }
- break;
- case StackElement::NativeToTarget:
- case StackElement::AddConversion: {
- CustomConversion* customConversion = static_cast<TypeEntry*>(m_current->entry)->customConversion();
- if (!customConversion) {
- m_error = QLatin1String("CustomConversion object is missing.");
- return false;
- }
-
- QString code = m_contextStack.top()->codeSnips.takeLast().code();
- if (m_current->type == StackElement::AddConversion) {
- if (customConversion->targetToNativeConversions().isEmpty()) {
- m_error = QLatin1String("CustomConversion's target to native conversions missing.");
- return false;
- }
- customConversion->targetToNativeConversions().last()->setConversion(code);
- } else {
- customConversion->setNativeToTargetConversion(code);
- }
- }
- break;
- case StackElement::CustomMetaConstructor: {
- m_current->entry->setCustomConstructor(*m_current->value.customFunction);
- delete m_current->value.customFunction;
- }
- break;
- case StackElement::CustomMetaDestructor: {
- m_current->entry->setCustomDestructor(*m_current->value.customFunction);
- delete m_current->value.customFunction;
- }
- break;
- case StackElement::EnumTypeEntry:
- m_current->entry->setDocModification(m_contextStack.top()->docModifications);
- m_contextStack.top()->docModifications = DocModificationList();
- m_currentEnum = nullptr;
- break;
- case StackElement::Template:
- m_database->addTemplate(m_current->value.templateEntry);
- break;
- case StackElement::TemplateInstanceEnum:
- switch (m_current->parent->type) {
- case StackElement::InjectCode:
- if (m_current->parent->parent->type == StackElement::Root) {
- CodeSnipList snips = m_current->parent->entry->codeSnips();
- CodeSnip snip = snips.takeLast();
- snip.addTemplateInstance(m_current->value.templateInstance);
- snips.append(snip);
- m_current->parent->entry->setCodeSnips(snips);
- break;
- }
- Q_FALLTHROUGH();
- case StackElement::NativeToTarget:
- case StackElement::AddConversion:
- m_contextStack.top()->codeSnips.last().addTemplateInstance(m_current->value.templateInstance);
- break;
- case StackElement::Template:
- m_current->parent->value.templateEntry->addTemplateInstance(m_current->value.templateInstance);
- break;
- case StackElement::CustomMetaConstructor:
- case StackElement::CustomMetaDestructor:
- m_current->parent->value.customFunction->addTemplateInstance(m_current->value.templateInstance);
- break;
- case StackElement::ConversionRule:
- m_contextStack.top()->functionMods.last().argument_mods.last().conversion_rules.last().addTemplateInstance(m_current->value.templateInstance);
- break;
- case StackElement::InjectCodeInFunction:
- m_contextStack.top()->functionMods.last().snips.last().addTemplateInstance(m_current->value.templateInstance);
- break;
- default:
- break; // nada
- }
- break;
- default:
- break;
- }
-
- switch (m_current->type) {
- case StackElement::Root:
- case StackElement::NamespaceTypeEntry:
- case StackElement::InterfaceTypeEntry:
- case StackElement::ObjectTypeEntry:
- case StackElement::ValueTypeEntry:
- case StackElement::PrimitiveTypeEntry:
- case StackElement::TypedefTypeEntry:
- delete m_contextStack.pop();
- break;
- default:
- break;
- }
-
- StackElement *child = m_current;
- m_current = m_current->parent;
- delete(child);
-
- return true;
-}
-
-template <class String> // QString/QStringRef
-bool TypeSystemParser::characters(const String &ch)
-{
- if (m_currentDroppedEntry || m_ignoreDepth)
- return true;
-
- if (m_current->type == StackElement::Template) {
- m_current->value.templateEntry->addCode(ch);
- return true;
- }
-
- if (m_current->type == StackElement::CustomMetaConstructor || m_current->type == StackElement::CustomMetaDestructor) {
- m_current->value.customFunction->addCode(ch);
- return true;
- }
-
- if (m_current->type == StackElement::ConversionRule
- && m_current->parent->type == StackElement::ModifyArgument) {
- m_contextStack.top()->functionMods.last().argument_mods.last().conversion_rules.last().addCode(ch);
- return true;
- }
-
- if (m_current->type == StackElement::NativeToTarget || m_current->type == StackElement::AddConversion) {
- m_contextStack.top()->codeSnips.last().addCode(ch);
- return true;
- }
-
- if (m_current->parent) {
- if ((m_current->type & StackElement::CodeSnipMask)) {
- CodeSnipList snips;
- switch (m_current->parent->type) {
- case StackElement::Root:
- snips = m_current->parent->entry->codeSnips();
- snips.last().addCode(ch);
- m_current->parent->entry->setCodeSnips(snips);
- break;
- case StackElement::ModifyFunction:
- case StackElement::AddFunction:
- m_contextStack.top()->functionMods.last().snips.last().addCode(ch);
- m_contextStack.top()->functionMods.last().modifiers |= FunctionModification::CodeInjection;
- break;
- case StackElement::NamespaceTypeEntry:
- case StackElement::ObjectTypeEntry:
- case StackElement::ValueTypeEntry:
- case StackElement::InterfaceTypeEntry:
- m_contextStack.top()->codeSnips.last().addCode(ch);
- break;
- default:
- Q_ASSERT(false);
- }
- return true;
- }
- }
-
- if (m_current->type & StackElement::DocumentationMask)
- m_contextStack.top()->docModifications.last().setCode(ch);
-
- return true;
-}
-
-bool TypeSystemParser::importFileElement(const QXmlStreamAttributes &atts)
-{
- const QString fileName = atts.value(nameAttribute()).toString();
- if (fileName.isEmpty()) {
- m_error = QLatin1String("Required attribute 'name' missing for include-file tag.");
- return false;
- }
-
- QFile file(fileName);
- if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- file.setFileName(QLatin1String(":/trolltech/generator/") + fileName);
- if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- m_error = QString::fromLatin1("Could not open file: '%1'").arg(QDir::toNativeSeparators(fileName));
- return false;
- }
- }
-
- const QStringRef quoteFrom = atts.value(quoteAfterLineAttribute());
- bool foundFromOk = quoteFrom.isEmpty();
- bool from = quoteFrom.isEmpty();
-
- const QStringRef quoteTo = atts.value(quoteBeforeLineAttribute());
- bool foundToOk = quoteTo.isEmpty();
- bool to = true;
-
- QTextStream in(&file);
- while (!in.atEnd()) {
- QString line = in.readLine();
- if (from && to && line.contains(quoteTo)) {
- to = false;
- foundToOk = true;
- break;
- }
- if (from && to)
- characters(line + QLatin1Char('\n'));
- if (!from && line.contains(quoteFrom)) {
- from = true;
- foundFromOk = true;
- }
- }
- if (!foundFromOk || !foundToOk) {
- QString fromError = QStringLiteral("Could not find quote-after-line='%1' in file '%2'.")
- .arg(quoteFrom.toString(), fileName);
- QString toError = QStringLiteral("Could not find quote-before-line='%1' in file '%2'.")
- .arg(quoteTo.toString(), fileName);
-
- if (!foundToOk)
- m_error = toError;
- if (!foundFromOk)
- m_error = fromError;
- if (!foundFromOk && !foundToOk)
- m_error = fromError + QLatin1Char(' ') + toError;
- return false;
- }
-
- return true;
-}
-
-static bool convertBoolean(QStringView value, const QString &attributeName, bool defaultValue)
-{
-#ifdef QTBUG_69389_FIXED
- if (value.compare(trueAttributeValue(), Qt::CaseInsensitive) == 0
- || value.compare(yesAttributeValue(), Qt::CaseInsensitive) == 0) {
- return true;
- }
- if (value.compare(falseAttributeValue(), Qt::CaseInsensitive) == 0
- || value.compare(noAttributeValue(), Qt::CaseInsensitive) == 0) {
- return false;
- }
-#else
- if (QtPrivate::compareStrings(value, trueAttributeValue(), Qt::CaseInsensitive) == 0
- || QtPrivate::compareStrings(value, yesAttributeValue(), Qt::CaseInsensitive) == 0) {
- return true;
- }
- if (QtPrivate::compareStrings(value, falseAttributeValue(), Qt::CaseInsensitive) == 0
- || QtPrivate::compareStrings(value, noAttributeValue(), Qt::CaseInsensitive) == 0) {
- return false;
- }
-#endif
- const QString warn = QStringLiteral("Boolean value '%1' not supported in attribute '%2'. Use 'yes' or 'no'. Defaulting to '%3'.")
- .arg(value)
- .arg(attributeName,
- defaultValue ? yesAttributeValue() : noAttributeValue());
-
- qCWarning(lcShiboken).noquote().nospace() << warn;
- return defaultValue;
-}
-
-static bool convertRemovalAttribute(QStringView remove, Modification& mod, QString& errorMsg)
-{
- if (remove.isEmpty())
- return true;
-#ifdef QTBUG_69389_FIXED
- if (remove.compare(u"all", Qt::CaseInsensitive) == 0) {
-#else
- if (QtPrivate::compareStrings(remove, u"all", Qt::CaseInsensitive) == 0) {
-#endif
- mod.removal = TypeSystem::All;
- return true;
- }
-#ifdef QTBUG_69389_FIXED
- if (remove.compare(u"target", Qt::CaseInsensitive) == 0) {
-#else
- if (QtPrivate::compareStrings(remove, u"target", Qt::CaseInsensitive) == 0) {
-#endif
- mod.removal = TypeSystem::TargetLangAndNativeCode;
- return true;
- }
- errorMsg = QString::fromLatin1("Bad removal type '%1'").arg(remove);
- return false;
-}
-
-static void getNamePrefixRecursive(StackElement* element, QStringList& names)
-{
- if (!element->parent || !element->parent->entry)
- return;
- getNamePrefixRecursive(element->parent, names);
- names << element->parent->entry->name();
-}
-
-static QString getNamePrefix(StackElement* element)
-{
- QStringList names;
- getNamePrefixRecursive(element, names);
- return names.join(QLatin1Char('.'));
-}
-
-// Returns empty string if there's no error.
-static QString checkSignatureError(const QString& signature, const QString& tag)
-{
- QString funcName = signature.left(signature.indexOf(QLatin1Char('('))).trimmed();
- static const QRegularExpression whiteSpace(QStringLiteral("\\s"));
- Q_ASSERT(whiteSpace.isValid());
- if (!funcName.startsWith(QLatin1String("operator ")) && funcName.contains(whiteSpace)) {
- return QString::fromLatin1("Error in <%1> tag signature attribute '%2'.\n"
- "White spaces aren't allowed in function names, "
- "and return types should not be part of the signature.")
- .arg(tag, signature);
- }
- return QString();
-}
-
-inline const TypeEntry *TypeSystemParser::currentParentTypeEntry() const
-{
- return m_current ? m_current->entry : nullptr;
-}
-
-bool TypeSystemParser::checkRootElement()
-{
- const bool ok = currentParentTypeEntry() != nullptr;
- if (!ok)
- m_error = msgNoRootTypeSystemEntry();
- return ok;
-}
-
-void TypeSystemParser::applyCommonAttributes(TypeEntry *type, QXmlStreamAttributes *attributes) const
-{
- type->setCodeGeneration(m_generate);
- const int revisionIndex =
- indexOfAttribute(*attributes, u"revision");
- if (revisionIndex != -1)
- type->setRevision(attributes->takeAt(revisionIndex).value().toInt());
-}
-
-FlagsTypeEntry *
- TypeSystemParser::parseFlagsEntry(const QXmlStreamReader &,
- EnumTypeEntry *enumEntry, QString flagName,
- const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-
-{
- if (!checkRootElement())
- return nullptr;
- auto ftype = new FlagsTypeEntry(QLatin1String("QFlags<") + enumEntry->name() + QLatin1Char('>'),
- since,
- currentParentTypeEntry()->typeSystemTypeEntry());
- ftype->setOriginator(enumEntry);
- ftype->setTargetLangPackage(enumEntry->targetLangPackage());
- // Try toenumEntry get the guess the qualified flag name
- if (!flagName.contains(colonColon())) {
- auto eq = enumEntry->qualifier();
- if (!eq.isEmpty())
- flagName.prepend(eq + colonColon());
- }
-
- ftype->setOriginalName(flagName);
- applyCommonAttributes(ftype, attributes);
-
- QStringList lst = flagName.split(colonColon());
- const QString targetLangFlagName = QStringList(lst.mid(0, lst.size() - 1)).join(QLatin1Char('.'));
- const QString &targetLangQualifier = enumEntry->targetLangQualifier();
- if (targetLangFlagName != targetLangQualifier) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("enum %1 and flags %2 (%3) differ in qualifiers")
- .arg(targetLangQualifier, lst.constFirst(), targetLangFlagName);
- }
-
- ftype->setFlagsName(lst.constLast());
- enumEntry->setFlags(ftype);
-
- m_database->addFlagsType(ftype);
- m_database->addType(ftype);
-
- const int revisionIndex =
- indexOfAttribute(*attributes, u"flags-revision");
- ftype->setRevision(revisionIndex != -1
- ? attributes->takeAt(revisionIndex).value().toInt()
- : enumEntry->revision());
- return ftype;
-}
-
-SmartPointerTypeEntry *
- TypeSystemParser::parseSmartPointerEntry(const QXmlStreamReader &,
- const QString &name, const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- if (!checkRootElement())
- return nullptr;
- QString smartPointerType;
- QString getter;
- QString refCountMethodName;
- QString instantiations;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == QLatin1String("type")) {
- smartPointerType = attributes->takeAt(i).value().toString();
- } else if (name == QLatin1String("getter")) {
- getter = attributes->takeAt(i).value().toString();
- } else if (name == QLatin1String("ref-count-method")) {
- refCountMethodName = attributes->takeAt(i).value().toString();
- } else if (name == QLatin1String("instantiations")) {
- instantiations = attributes->takeAt(i).value().toString();
- }
- }
-
- if (smartPointerType.isEmpty()) {
- m_error = QLatin1String("No type specified for the smart pointer. Currently supported types: 'shared',");
- return nullptr;
- }
- if (smartPointerType != QLatin1String("shared")) {
- m_error = QLatin1String("Currently only the 'shared' type is supported.");
- return nullptr;
- }
-
- if (getter.isEmpty()) {
- m_error = QLatin1String("No function getter name specified for getting the raw pointer held by the smart pointer.");
- return nullptr;
- }
-
- QString signature = getter + QLatin1String("()");
- signature = TypeDatabase::normalizedSignature(signature);
- if (signature.isEmpty()) {
- m_error = QLatin1String("No signature for the smart pointer getter found.");
- return nullptr;
- }
-
- QString errorString = checkSignatureError(signature,
- QLatin1String("smart-pointer-type"));
- if (!errorString.isEmpty()) {
- m_error = errorString;
- return nullptr;
- }
-
- auto *type = new SmartPointerTypeEntry(name, getter, smartPointerType,
- refCountMethodName, since, currentParentTypeEntry());
- applyCommonAttributes(type, attributes);
- m_smartPointerInstantiations.insert(type, instantiations);
- return type;
-}
-
-PrimitiveTypeEntry *
- TypeSystemParser::parsePrimitiveTypeEntry(const QXmlStreamReader &reader,
- const QString &name, const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- if (!checkRootElement())
- return nullptr;
- auto *type = new PrimitiveTypeEntry(name, since, currentParentTypeEntry());
- applyCommonAttributes(type, attributes);
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == targetLangNameAttribute()) {
- type->setTargetLangName(attributes->takeAt(i).value().toString());
- } else if (name == QLatin1String("target-lang-api-name")) {
- type->setTargetLangApiName(attributes->takeAt(i).value().toString());
- } else if (name == preferredConversionAttribute()) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- } else if (name == preferredTargetLangTypeAttribute()) {
- const bool v = convertBoolean(attributes->takeAt(i).value(),
- preferredTargetLangTypeAttribute(), true);
- type->setPreferredTargetLangType(v);
- } else if (name == QLatin1String("default-constructor")) {
- type->setDefaultConstructor(attributes->takeAt(i).value().toString());
- }
- }
-
- if (type->targetLangApiName().isEmpty())
- type->setTargetLangApiName(type->name());
- type->setTargetLangPackage(m_defaultPackage);
- return type;
-}
-
-ContainerTypeEntry *
- TypeSystemParser::parseContainerTypeEntry(const QXmlStreamReader &,
- const QString &name, const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- if (!checkRootElement())
- return nullptr;
- const int typeIndex = indexOfAttribute(*attributes, u"type");
- if (typeIndex == -1) {
- m_error = QLatin1String("no 'type' attribute specified");
- return nullptr;
- }
- const QStringRef typeName = attributes->takeAt(typeIndex).value();
- ContainerTypeEntry::ContainerKind containerType = containerTypeFromAttribute(typeName);
- if (containerType == ContainerTypeEntry::NoContainer) {
- m_error = QLatin1String("there is no container of type ") + typeName.toString();
- return nullptr;
- }
- auto *type = new ContainerTypeEntry(name, containerType, since, currentParentTypeEntry());
- applyCommonAttributes(type, attributes);
- return type;
-}
-
-EnumTypeEntry *
- TypeSystemParser::parseEnumTypeEntry(const QXmlStreamReader &reader,
- const QString &name, const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- if (!checkRootElement())
- return nullptr;
- auto *entry = new EnumTypeEntry(name, since, currentParentTypeEntry());
- applyCommonAttributes(entry, attributes);
- entry->setTargetLangPackage(m_defaultPackage);
-
- QString flagNames;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == QLatin1String("upper-bound")) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- } else if (name == QLatin1String("lower-bound")) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- } else if (name == forceIntegerAttribute()) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- } else if (name == extensibleAttribute()) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- } else if (name == flagsAttribute()) {
- flagNames = attributes->takeAt(i).value().toString();
- }
- }
-
- // put in the flags parallel...
- if (!flagNames.isEmpty()) {
- const QStringList &flagNameList = flagNames.split(QLatin1Char(','));
- for (const QString &flagName : flagNameList)
- parseFlagsEntry(reader, entry, flagName.trimmed(), since, attributes);
- }
- return entry;
-}
-
-
-NamespaceTypeEntry *
- TypeSystemParser::parseNamespaceTypeEntry(const QXmlStreamReader &reader,
- const QString &name, const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- if (!checkRootElement())
- return nullptr;
- QScopedPointer<NamespaceTypeEntry> result(new NamespaceTypeEntry(name, since, currentParentTypeEntry()));
- auto visibility = TypeSystem::Visibility::Unspecified;
- applyCommonAttributes(result.data(), attributes);
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef attributeName = attributes->at(i).qualifiedName();
- if (attributeName == QLatin1String("files")) {
- const QString pattern = attributes->takeAt(i).value().toString();
- QRegularExpression re(pattern);
- if (!re.isValid()) {
- m_error = msgInvalidRegularExpression(pattern, re.errorString());
- return nullptr;
- }
- result->setFilePattern(re);
- } else if (attributeName == QLatin1String("extends")) {
- const auto extendsPackageName = attributes->takeAt(i).value();
- auto allEntries = TypeDatabase::instance()->findNamespaceTypes(name);
- auto extendsIt = std::find_if(allEntries.cbegin(), allEntries.cend(),
- [extendsPackageName] (const NamespaceTypeEntry *e) {
- return e->targetLangPackage() == extendsPackageName;
- });
- if (extendsIt == allEntries.cend()) {
- m_error = msgCannotFindNamespaceToExtend(name, extendsPackageName);
- return nullptr;
- }
- result->setExtends(*extendsIt);
- } else if (attributeName == visibleAttribute()) {
- const auto attribute = attributes->takeAt(i);
- visibility = visibilityFromAttribute(attribute.value());
- if (visibility == TypeSystem::Visibility::Unspecified) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgInvalidAttributeValue(attribute)));
- }
- } else if (attributeName == generateAttribute()) {
- if (!convertBoolean(attributes->takeAt(i).value(), generateAttribute(), true))
- visibility = TypeSystem::Visibility::Invisible;
- }
- }
-
- if (visibility != TypeSystem::Visibility::Unspecified)
- result->setVisibility(visibility);
- // Handle legacy "generate" before the common handling
- applyComplexTypeAttributes(reader, result.data(), attributes);
-
- if (result->extends() && !result->hasPattern()) {
- m_error = msgExtendingNamespaceRequiresPattern(name);
- return nullptr;
- }
-
- return result.take();
-}
-
-ValueTypeEntry *
- TypeSystemParser::parseValueTypeEntry(const QXmlStreamReader &,
- const QString &name, const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- if (!checkRootElement())
- return nullptr;
- auto *typeEntry = new ValueTypeEntry(name, since, currentParentTypeEntry());
- applyCommonAttributes(typeEntry, attributes);
- const int defaultCtIndex =
- indexOfAttribute(*attributes, u"default-constructor");
- if (defaultCtIndex != -1)
- typeEntry->setDefaultConstructor(attributes->takeAt(defaultCtIndex).value().toString());
- return typeEntry;
-}
-
-FunctionTypeEntry *
- TypeSystemParser::parseFunctionTypeEntry(const QXmlStreamReader &,
- const QString &name, const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- if (!checkRootElement())
- return nullptr;
- const int signatureIndex = indexOfAttribute(*attributes, signatureAttribute());
- if (signatureIndex == -1) {
- m_error = msgMissingAttribute(signatureAttribute());
- return nullptr;
- }
- const QString signature =
- TypeDatabase::normalizedSignature(attributes->takeAt(signatureIndex).value().toString());
-
- TypeEntry *existingType = m_database->findType(name);
-
- if (!existingType) {
- auto *result = new FunctionTypeEntry(name, signature, since, currentParentTypeEntry());
- applyCommonAttributes(result, attributes);
- return result;
- }
-
- if (existingType->type() != TypeEntry::FunctionType) {
- m_error = QStringLiteral("%1 expected to be a function, but isn't! Maybe it was already declared as a class or something else.")
- .arg(name);
- return nullptr;
- }
-
- auto *result = reinterpret_cast<FunctionTypeEntry *>(existingType);
- result->addSignature(signature);
- return result;
-}
-
-TypedefEntry *
- TypeSystemParser::parseTypedefEntry(const QXmlStreamReader &, const QString &name,
- const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- if (!checkRootElement())
- return nullptr;
- if (m_current && m_current->type != StackElement::Root
- && m_current->type != StackElement::NamespaceTypeEntry) {
- m_error = QLatin1String("typedef entries must be nested in namespaces or type system.");
- return nullptr;
- }
- const int sourceIndex = indexOfAttribute(*attributes, sourceAttribute());
- if (sourceIndex == -1) {
- m_error = msgMissingAttribute(sourceAttribute());
- return nullptr;
- }
- const QString sourceType = attributes->takeAt(sourceIndex).value().toString();
- auto result = new TypedefEntry(name, sourceType, since, currentParentTypeEntry());
- applyCommonAttributes(result, attributes);
- return result;
-}
-
-void TypeSystemParser::applyComplexTypeAttributes(const QXmlStreamReader &reader,
- ComplexTypeEntry *ctype,
- QXmlStreamAttributes *attributes) const
-{
- bool generate = true;
- ctype->setCopyable(ComplexTypeEntry::Unknown);
- auto exceptionHandling = m_exceptionHandling;
- auto allowThread = m_allowThread;
-
- QString package = m_defaultPackage;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == streamAttribute()) {
- ctype->setStream(convertBoolean(attributes->takeAt(i).value(), streamAttribute(), false));
- } else if (name == generateAttribute()) {
- generate = convertBoolean(attributes->takeAt(i).value(), generateAttribute(), true);
- } else if (name ==packageAttribute()) {
- package = attributes->takeAt(i).value().toString();
- } else if (name == defaultSuperclassAttribute()) {
- ctype->setDefaultSuperclass(attributes->takeAt(i).value().toString());
- } else if (name == genericClassAttribute()) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- const bool v = convertBoolean(attributes->takeAt(i).value(), genericClassAttribute(), false);
- ctype->setGenericClass(v);
- } else if (name == targetLangNameAttribute()) {
- ctype->setTargetLangName(attributes->takeAt(i).value().toString());
- } else if (name == QLatin1String("polymorphic-base")) {
- ctype->setPolymorphicIdValue(attributes->takeAt(i).value().toString());
- } else if (name == QLatin1String("polymorphic-id-expression")) {
- ctype->setPolymorphicIdValue(attributes->takeAt(i).value().toString());
- } else if (name == copyableAttribute()) {
- const bool v = convertBoolean(attributes->takeAt(i).value(), copyableAttribute(), false);
- ctype->setCopyable(v ? ComplexTypeEntry::CopyableSet : ComplexTypeEntry::NonCopyableSet);
- } else if (name == exceptionHandlingAttribute()) {
- const auto attribute = attributes->takeAt(i);
- const auto v = exceptionHandlingFromAttribute(attribute.value());
- if (v != TypeSystem::ExceptionHandling::Unspecified) {
- exceptionHandling = v;
- } else {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgInvalidAttributeValue(attribute)));
- }
- } else if (name == allowThreadAttribute()) {
- const auto attribute = attributes->takeAt(i);
- const auto v = allowThreadFromAttribute(attribute.value());
- if (v != TypeSystem::AllowThread::Unspecified) {
- allowThread = v;
- } else {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgInvalidAttributeValue(attribute)));
- }
- } else if (name == QLatin1String("held-type")) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- } else if (name == QLatin1String("hash-function")) {
- ctype->setHashFunction(attributes->takeAt(i).value().toString());
- } else if (name == forceAbstractAttribute()) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- } else if (name == deprecatedAttribute()) {
- if (convertBoolean(attributes->takeAt(i).value(), deprecatedAttribute(), false))
- ctype->setTypeFlags(ctype->typeFlags() | ComplexTypeEntry::Deprecated);
- } else if (name == deleteInMainThreadAttribute()) {
- if (convertBoolean(attributes->takeAt(i).value(), deleteInMainThreadAttribute(), false))
- ctype->setDeleteInMainThread(true);
- } else if (name == QLatin1String("target-type")) {
- ctype->setTargetType(attributes->takeAt(i).value().toString());
- }
- }
-
- if (exceptionHandling != TypeSystem::ExceptionHandling::Unspecified)
- ctype->setExceptionHandling(exceptionHandling);
- if (allowThread != TypeSystem::AllowThread::Unspecified)
- ctype->setAllowThread(allowThread);
-
- // The generator code relies on container's package being empty.
- if (ctype->type() != TypeEntry::ContainerType)
- ctype->setTargetLangPackage(package);
-
- if (generate)
- ctype->setCodeGeneration(m_generate);
- else
- ctype->setCodeGeneration(TypeEntry::GenerateForSubclass);
-}
-
-bool TypeSystemParser::parseRenameFunction(const QXmlStreamReader &,
- QString *name, QXmlStreamAttributes *attributes)
-{
- QString signature;
- QString rename;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == signatureAttribute()) {
- // Do not remove as it is needed for the type entry later on
- signature = attributes->at(i).value().toString();
- } else if (name == renameAttribute()) {
- rename = attributes->takeAt(i).value().toString();
- }
- }
-
- if (signature.isEmpty()) {
- m_error = msgMissingAttribute(signatureAttribute());
- return false;
- }
-
- *name = signature.left(signature.indexOf(QLatin1Char('('))).trimmed();
-
- QString errorString = checkSignatureError(signature, QLatin1String("function"));
- if (!errorString.isEmpty()) {
- m_error = errorString;
- return false;
- }
-
- if (!rename.isEmpty()) {
- static const QRegularExpression functionNameRegExp(QLatin1String("^[a-zA-Z_][a-zA-Z0-9_]*$"));
- Q_ASSERT(functionNameRegExp.isValid());
- if (!functionNameRegExp.match(rename).hasMatch()) {
- m_error = QLatin1String("can not rename '") + signature + QLatin1String("', '")
- + rename + QLatin1String("' is not a valid function name");
- return false;
- }
- FunctionModification mod;
- if (!mod.setSignature(signature, &m_error))
- return false;
- mod.renamedToName = rename;
- mod.modifiers |= Modification::Rename;
- m_contextStack.top()->functionMods << mod;
- }
- return true;
-}
-
-bool TypeSystemParser::parseInjectDocumentation(const QXmlStreamReader &,
- QXmlStreamAttributes *attributes)
-{
- const int validParent = StackElement::TypeEntryMask
- | StackElement::ModifyFunction
- | StackElement::ModifyField;
- if (!m_current->parent || (m_current->parent->type & validParent) == 0) {
- m_error = QLatin1String("inject-documentation must be inside modify-function, "
- "modify-field or other tags that creates a type");
- return false;
- }
-
- TypeSystem::DocModificationMode mode = TypeSystem::DocModificationReplace;
- TypeSystem::Language lang = TypeSystem::NativeCode;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == QLatin1String("mode")) {
- const QStringRef modeName = attributes->takeAt(i).value();
- mode = docModificationFromAttribute(modeName);
- if (mode == TypeSystem::DocModificationInvalid) {
- m_error = QLatin1String("Unknown documentation injection mode: ") + modeName;
- return false;
- }
- } else if (name == formatAttribute()) {
- const QStringRef format = attributes->takeAt(i).value();
- lang = languageFromAttribute(format);
- if (lang != TypeSystem::TargetLangCode && lang != TypeSystem::NativeCode) {
- m_error = QStringLiteral("unsupported class attribute: '%1'").arg(format);
- return false;
- }
- }
- }
-
- QString signature = m_current->type & StackElement::TypeEntryMask
- ? QString() : m_currentSignature;
- DocModification mod(mode, signature);
- mod.setFormat(lang);
- m_contextStack.top()->docModifications << mod;
- return true;
-}
-
-bool TypeSystemParser::parseModifyDocumentation(const QXmlStreamReader &,
- QXmlStreamAttributes *attributes)
-{
- const int validParent = StackElement::TypeEntryMask
- | StackElement::ModifyFunction
- | StackElement::ModifyField;
- if (!m_current->parent || (m_current->parent->type & validParent) == 0) {
- m_error = QLatin1String("modify-documentation must be inside modify-function, "
- "modify-field or other tags that creates a type");
- return false;
- }
-
- const int xpathIndex = indexOfAttribute(*attributes, xPathAttribute());
- if (xpathIndex == -1) {
- m_error = msgMissingAttribute(xPathAttribute());
- return false;
- }
-
- const QString xpath = attributes->takeAt(xpathIndex).value().toString();
- QString signature = (m_current->type & StackElement::TypeEntryMask) ? QString() : m_currentSignature;
- m_contextStack.top()->docModifications
- << DocModification(xpath, signature);
- return true;
-}
-
-// m_exceptionHandling
-TypeSystemTypeEntry *TypeSystemParser::parseRootElement(const QXmlStreamReader &,
- const QVersionNumber &since,
- QXmlStreamAttributes *attributes)
-{
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == packageAttribute()) {
- m_defaultPackage = attributes->takeAt(i).value().toString();
- } else if (name == defaultSuperclassAttribute()) {
- m_defaultSuperclass = attributes->takeAt(i).value().toString();
- } else if (name == exceptionHandlingAttribute()) {
- const auto attribute = attributes->takeAt(i);
- const auto v = exceptionHandlingFromAttribute(attribute.value());
- if (v != TypeSystem::ExceptionHandling::Unspecified) {
- m_exceptionHandling = v;
- } else {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgInvalidAttributeValue(attribute)));
- }
- } else if (name == allowThreadAttribute()) {
- const auto attribute = attributes->takeAt(i);
- const auto v = allowThreadFromAttribute(attribute.value());
- if (v != TypeSystem::AllowThread::Unspecified) {
- m_allowThread = v;
- } else {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgInvalidAttributeValue(attribute)));
- }
- }
- }
-
- auto *moduleEntry =
- const_cast<TypeSystemTypeEntry *>(m_database->findTypeSystemType(m_defaultPackage));
- const bool add = moduleEntry == nullptr;
- if (add) {
- moduleEntry = new TypeSystemTypeEntry(m_defaultPackage, since,
- currentParentTypeEntry());
- }
- moduleEntry->setCodeGeneration(m_generate);
-
- if ((m_generate == TypeEntry::GenerateForSubclass ||
- m_generate == TypeEntry::GenerateNothing) && !m_defaultPackage.isEmpty())
- TypeDatabase::instance()->addRequiredTargetImport(m_defaultPackage);
-
- if (add)
- m_database->addTypeSystemType(moduleEntry);
- return moduleEntry;
-}
-
-bool TypeSystemParser::loadTypesystem(const QXmlStreamReader &,
- QXmlStreamAttributes *attributes)
-{
- QString typeSystemName;
- bool generateChild = true;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == nameAttribute())
- typeSystemName = attributes->takeAt(i).value().toString();
- else if (name == generateAttribute())
- generateChild = convertBoolean(attributes->takeAt(i).value(), generateAttribute(), true);
- }
- if (typeSystemName.isEmpty()) {
- m_error = QLatin1String("No typesystem name specified");
- return false;
- }
- const bool result =
- m_database->parseFile(typeSystemName, m_currentPath, generateChild
- && m_generate == TypeEntry::GenerateAll);
- if (!result)
- m_error = QStringLiteral("Failed to parse: '%1'").arg(typeSystemName);
- return result;
-}
-
-bool TypeSystemParser::parseRejectEnumValue(const QXmlStreamReader &,
- QXmlStreamAttributes *attributes)
-{
- if (!m_currentEnum) {
- m_error = QLatin1String("<reject-enum-value> node must be used inside a <enum-type> node");
- return false;
- }
- const int nameIndex = indexOfAttribute(*attributes, nameAttribute());
- if (nameIndex == -1) {
- m_error = msgMissingAttribute(nameAttribute());
- return false;
- }
- m_currentEnum->addEnumValueRejection(attributes->takeAt(nameIndex).value().toString());
- return true;
-}
-
-bool TypeSystemParser::parseReplaceArgumentType(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyArgument) {
- m_error = QLatin1String("Type replacement can only be specified for argument modifications");
- return false;
- }
- const int modifiedTypeIndex = indexOfAttribute(*attributes, modifiedTypeAttribute());
- if (modifiedTypeIndex == -1) {
- m_error = QLatin1String("Type replacement requires 'modified-type' attribute");
- return false;
- }
- m_contextStack.top()->functionMods.last().argument_mods.last().modified_type =
- attributes->takeAt(modifiedTypeIndex).value().toString();
- return true;
-}
-
-bool TypeSystemParser::parseCustomConversion(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyArgument
- && topElement.type != StackElement::ValueTypeEntry
- && topElement.type != StackElement::PrimitiveTypeEntry
- && topElement.type != StackElement::ContainerTypeEntry) {
- m_error = QLatin1String("Conversion rules can only be specified for argument modification, "
- "value-type, primitive-type or container-type conversion.");
- return false;
- }
-
- QString sourceFile;
- QString snippetLabel;
- TypeSystem::Language lang = TypeSystem::NativeCode;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == classAttribute()) {
- const QStringRef languageAttribute = attributes->takeAt(i).value();
- lang = languageFromAttribute(languageAttribute);
- if (lang != TypeSystem::TargetLangCode && lang != TypeSystem::NativeCode) {
- m_error = QStringLiteral("unsupported class attribute: '%1'").arg(languageAttribute);
- return false;
- }
- } else if (name == QLatin1String("file")) {
- sourceFile = attributes->takeAt(i).value().toString();
- } else if (name == snippetAttribute()) {
- snippetLabel = attributes->takeAt(i).value().toString();
- }
- }
-
- if (topElement.type == StackElement::ModifyArgument) {
- CodeSnip snip;
- snip.language = lang;
- m_contextStack.top()->functionMods.last().argument_mods.last().conversion_rules.append(snip);
- return true;
- }
-
- if (topElement.entry->hasConversionRule() || topElement.entry->hasCustomConversion()) {
- m_error = QLatin1String("Types can have only one conversion rule");
- return false;
- }
-
- // The old conversion rule tag that uses a file containing the conversion
- // will be kept temporarily for compatibility reasons.
- if (!sourceFile.isEmpty()) {
- if (m_generate != TypeEntry::GenerateForSubclass
- && m_generate != TypeEntry::GenerateNothing) {
-
- const char* conversionFlag = NATIVE_CONVERSION_RULE_FLAG;
- if (lang == TypeSystem::TargetLangCode)
- conversionFlag = TARGET_CONVERSION_RULE_FLAG;
-
- QFile conversionSource(sourceFile);
- if (conversionSource.open(QIODevice::ReadOnly | QIODevice::Text)) {
- const QString conversionRule =
- extractSnippet(QString::fromUtf8(conversionSource.readAll()), snippetLabel);
- topElement.entry->setConversionRule(QLatin1String(conversionFlag) + conversionRule);
- } else {
- qCWarning(lcShiboken).noquote().nospace()
- << "File containing conversion code for "
- << topElement.entry->name() << " type does not exist or is not readable: "
- << sourceFile;
- }
- }
- }
-
- auto *customConversion = new CustomConversion(m_current->entry);
- customConversionsForReview.append(customConversion);
- return true;
-}
-
-bool TypeSystemParser::parseNativeToTarget(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ConversionRule) {
- m_error = QLatin1String("Native to Target conversion code can only be specified for custom conversion rules.");
- return false;
- }
- CodeSnip snip;
- if (!readFileSnippet(attributes, &snip))
- return false;
- m_contextStack.top()->codeSnips.append(snip);
- return true;
-}
-
-bool TypeSystemParser::parseAddConversion(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::TargetToNative) {
- m_error = QLatin1String("Target to Native conversions can only be added inside 'target-to-native' tags.");
- return false;
- }
- QString sourceTypeName;
- QString typeCheck;
- CodeSnip snip;
- if (!readFileSnippet(attributes, &snip))
- return false;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == QLatin1String("type"))
- sourceTypeName = attributes->takeAt(i).value().toString();
- else if (name == QLatin1String("check"))
- typeCheck = attributes->takeAt(i).value().toString();
- }
- if (sourceTypeName.isEmpty()) {
- m_error = QLatin1String("Target to Native conversions must specify the input type with the 'type' attribute.");
- return false;
- }
- m_current->entry->customConversion()->addTargetToNativeConversion(sourceTypeName, typeCheck);
- m_contextStack.top()->codeSnips.append(snip);
- return true;
-}
-
-static bool parseIndex(const QString &index, int *result, QString *errorMessage)
-{
- bool ok = false;
- *result = index.toInt(&ok);
- if (!ok)
- *errorMessage = QStringLiteral("Cannot convert '%1' to integer").arg(index);
- return ok;
-}
-
-static bool parseArgumentIndex(const QString &index, int *result, QString *errorMessage)
-{
- if (index == QLatin1String("return")) {
- *result = 0;
- return true;
- }
- if (index == QLatin1String("this")) {
- *result = -1;
- return true;
- }
- return parseIndex(index, result, errorMessage);
-}
-
-bool TypeSystemParser::parseModifyArgument(const QXmlStreamReader &,
- const StackElement &topElement, QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyFunction
- && topElement.type != StackElement::AddFunction) {
- m_error = QString::fromLatin1("argument modification requires function"
- " modification as parent, was %1")
- .arg(topElement.type, 0, 16);
- return false;
- }
-
- QString index;
- QString replaceValue;
- bool resetAfterUse = false;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == indexAttribute()) {
- index = attributes->takeAt(i).value().toString();
- } else if (name == QLatin1String("replace-value")) {
- replaceValue = attributes->takeAt(i).value().toString();
- } else if (name == invalidateAfterUseAttribute()) {
- resetAfterUse = convertBoolean(attributes->takeAt(i).value(),
- invalidateAfterUseAttribute(), false);
- }
- }
-
- if (index.isEmpty()) {
- m_error = msgMissingAttribute(indexAttribute());
- return false;
- }
-
- int idx;
- if (!parseArgumentIndex(index, &idx, &m_error))
- return false;
-
- if (!replaceValue.isEmpty() && idx) {
- m_error = QLatin1String("replace-value is only supported for return values (index=0).");
- return false;
- }
-
- ArgumentModification argumentModification = ArgumentModification(idx);
- argumentModification.replace_value = replaceValue;
- argumentModification.resetAfterUse = resetAfterUse;
- m_contextStack.top()->functionMods.last().argument_mods.append(argumentModification);
- return true;
-}
-
-bool TypeSystemParser::parseNoNullPointer(const QXmlStreamReader &reader,
- const StackElement &topElement, QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyArgument) {
- m_error = QLatin1String("no-null-pointer requires argument modification as parent");
- return false;
- }
-
- ArgumentModification &lastArgMod = m_contextStack.top()->functionMods.last().argument_mods.last();
- lastArgMod.noNullPointers = true;
-
- const int defaultValueIndex =
- indexOfAttribute(*attributes, u"default-value");
- if (defaultValueIndex != -1) {
- const QXmlStreamAttribute attribute = attributes->takeAt(defaultValueIndex);
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, attribute)));
- }
- return true;
-}
-
-bool TypeSystemParser::parseDefineOwnership(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyArgument) {
- m_error = QLatin1String("define-ownership requires argument modification as parent");
- return false;
- }
-
- TypeSystem::Language lang = TypeSystem::TargetLangCode;
- QString ownership;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == classAttribute()) {
- const QStringRef className = attributes->takeAt(i).value();
- lang = languageFromAttribute(className);
- if (lang != TypeSystem::TargetLangCode && lang != TypeSystem::NativeCode) {
- m_error = QStringLiteral("unsupported class attribute: '%1'").arg(className);
- return false;
- }
- } else if (name == ownershipAttribute()) {
- ownership = attributes->takeAt(i).value().toString();
- }
- }
- const TypeSystem::Ownership owner = ownershipFromFromAttribute(ownership);
- if (owner == TypeSystem::InvalidOwnership) {
- m_error = QStringLiteral("unsupported owner attribute: '%1'").arg(ownership);
- return false;
- }
- m_contextStack.top()->functionMods.last().argument_mods.last().ownerships[lang] = owner;
- return true;
-}
-
-bool TypeSystemParser::parseArgumentMap(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (!(topElement.type & StackElement::CodeSnipMask)) {
- m_error = QLatin1String("Argument maps requires code injection as parent");
- return false;
- }
-
- int pos = 1;
- QString metaName;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == indexAttribute()) {
- if (!parseIndex(attributes->takeAt(i).value().toString(), &pos, &m_error))
- return false;
- if (pos <= 0) {
- m_error = QStringLiteral("Argument position %1 must be a positive number").arg(pos);
- return false;
- }
- } else if (name == QLatin1String("meta-name")) {
- metaName = attributes->takeAt(i).value().toString();
- }
- }
-
- if (metaName.isEmpty())
- qCWarning(lcShiboken) << "Empty meta name in argument map";
-
- if (topElement.type == StackElement::InjectCodeInFunction) {
- m_contextStack.top()->functionMods.last().snips.last().argumentMap[pos] = metaName;
- } else {
- qCWarning(lcShiboken) << "Argument maps are only useful for injection of code "
- "into functions.";
- }
- return true;
-}
-
-bool TypeSystemParser::parseRemoval(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyFunction) {
- m_error = QLatin1String("Function modification parent required");
- return false;
- }
-
- TypeSystem::Language lang = TypeSystem::All;
- const int classIndex = indexOfAttribute(*attributes, classAttribute());
- if (classIndex != -1) {
- const QStringRef value = attributes->takeAt(classIndex).value();
- lang = languageFromAttribute(value);
- if (lang == TypeSystem::TargetLangCode) // "target" means TargetLangAndNativeCode here
- lang = TypeSystem::TargetLangAndNativeCode;
- if (lang != TypeSystem::TargetLangAndNativeCode && lang != TypeSystem::All) {
- m_error = QStringLiteral("unsupported class attribute: '%1'").arg(value);
- return false;
- }
- }
- m_contextStack.top()->functionMods.last().removal = lang;
- return true;
-}
-
-bool TypeSystemParser::parseRename(const QXmlStreamReader &reader,
- StackElement::ElementType type,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyField
- && topElement.type != StackElement::ModifyFunction
- && topElement.type != StackElement::ModifyArgument) {
- m_error = QLatin1String("Function, field or argument modification parent required");
- return false;
- }
-
- Modification *mod = nullptr;
- if (topElement.type == StackElement::ModifyFunction)
- mod = &m_contextStack.top()->functionMods.last();
- else if (topElement.type == StackElement::ModifyField)
- mod = &m_contextStack.top()->fieldMods.last();
-
- Modification::Modifiers modifierFlag = Modification::Rename;
- if (type == StackElement::Rename) {
- const int toIndex = indexOfAttribute(*attributes, toAttribute());
- if (toIndex == -1) {
- m_error = msgMissingAttribute(toAttribute());
- return false;
- }
- const QString renamed_to = attributes->takeAt(toIndex).value().toString();
- if (topElement.type == StackElement::ModifyFunction)
- mod->setRenamedTo(renamed_to);
- else if (topElement.type == StackElement::ModifyField)
- mod->setRenamedTo(renamed_to);
- else
- m_contextStack.top()->functionMods.last().argument_mods.last().renamed_to = renamed_to;
- } else {
- const int modifierIndex = indexOfAttribute(*attributes, modifierAttribute());
- if (modifierIndex == -1) {
- m_error = msgMissingAttribute(modifierAttribute());
- return false;
- }
- const QStringRef modifier = attributes->takeAt(modifierIndex).value();
- modifierFlag = modifierFromAttribute(modifier);
- if (modifierFlag == Modification::InvalidModifier) {
- m_error = QStringLiteral("Unknown access modifier: '%1'").arg(modifier);
- return false;
- }
- if (modifierFlag == Modification::Friendly) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeValueWarning(reader, modifierAttribute(), modifier)));
- }
- }
-
- if (mod)
- mod->modifiers |= modifierFlag;
- return true;
-}
-
-bool TypeSystemParser::parseModifyField(const QXmlStreamReader &reader,
- QXmlStreamAttributes *attributes)
-{
- FieldModification fm;
- fm.modifiers = FieldModification::Readable | FieldModification::Writable;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == nameAttribute()) {
- fm.name = attributes->takeAt(i).value().toString();
- } else if (name == removeAttribute()) {
- if (!convertRemovalAttribute(attributes->takeAt(i).value(), fm, m_error))
- return false;
- } else if (name == readAttribute()) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- if (!convertBoolean(attributes->takeAt(i).value(), readAttribute(), true))
- fm.modifiers &= ~FieldModification::Readable;
- } else if (name == writeAttribute()) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- if (!convertBoolean(attributes->takeAt(i).value(), writeAttribute(), true))
- fm.modifiers &= ~FieldModification::Writable;
- }
- }
- if (fm.name.isEmpty()) {
- m_error = msgMissingAttribute(nameAttribute());
- return false;
- }
- m_contextStack.top()->fieldMods << fm;
- return true;
-}
-
-bool TypeSystemParser::parseAddFunction(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (!(topElement.type & (StackElement::ComplexTypeEntryMask | StackElement::Root))) {
- m_error = QString::fromLatin1("Add function requires a complex type or a root tag as parent"
- ", was=%1").arg(topElement.type, 0, 16);
- return false;
- }
- QString originalSignature;
- QString returnType = QLatin1String("void");
- bool staticFunction = false;
- QString access;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == QLatin1String("signature")) {
- originalSignature = attributes->takeAt(i).value().toString();
- } else if (name == QLatin1String("return-type")) {
- returnType = attributes->takeAt(i).value().toString();
- } else if (name == staticAttribute()) {
- staticFunction = convertBoolean(attributes->takeAt(i).value(),
- staticAttribute(), false);
- } else if (name == accessAttribute()) {
- access = attributes->takeAt(i).value().toString();
- }
- }
-
- QString signature = TypeDatabase::normalizedSignature(originalSignature);
- if (signature.isEmpty()) {
- m_error = QLatin1String("No signature for the added function");
- return false;
- }
-
- QString errorString = checkSignatureError(signature, QLatin1String("add-function"));
- if (!errorString.isEmpty()) {
- m_error = errorString;
- return false;
- }
-
- AddedFunctionPtr func(new AddedFunction(signature, returnType));
- func->setStatic(staticFunction);
- if (!signature.contains(QLatin1Char('(')))
- signature += QLatin1String("()");
- m_currentSignature = signature;
-
- if (!access.isEmpty()) {
- const AddedFunction::Access a = addedFunctionAccessFromAttribute(access);
- if (a == AddedFunction::InvalidAccess) {
- m_error = QString::fromLatin1("Bad access type '%1'").arg(access);
- return false;
- }
- func->setAccess(a);
- }
-
- m_contextStack.top()->addedFunctions << func;
- m_contextStack.top()->addedFunctionModificationIndex =
- m_contextStack.top()->functionMods.size();
-
- FunctionModification mod;
- if (!mod.setSignature(m_currentSignature, &m_error))
- return false;
- mod.setOriginalSignature(originalSignature);
- m_contextStack.top()->functionMods << mod;
- return true;
-}
-
-bool TypeSystemParser::parseModifyFunction(const QXmlStreamReader &reader,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (!(topElement.type & StackElement::ComplexTypeEntryMask)) {
- m_error = QString::fromLatin1("Modify function requires complex type as parent"
- ", was=%1").arg(topElement.type, 0, 16);
- return false;
- }
-
- QString originalSignature;
- QString access;
- QString removal;
- QString rename;
- QString association;
- bool deprecated = false;
- bool isThread = false;
- TypeSystem::ExceptionHandling exceptionHandling = TypeSystem::ExceptionHandling::Unspecified;
- TypeSystem::AllowThread allowThread = TypeSystem::AllowThread::Unspecified;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == QLatin1String("signature")) {
- originalSignature = attributes->takeAt(i).value().toString();
- } else if (name == accessAttribute()) {
- access = attributes->takeAt(i).value().toString();
- } else if (name == renameAttribute()) {
- rename = attributes->takeAt(i).value().toString();
- } else if (name == QLatin1String("associated-to")) {
- association = attributes->takeAt(i).value().toString();
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- } else if (name == removeAttribute()) {
- removal = attributes->takeAt(i).value().toString();
- } else if (name == deprecatedAttribute()) {
- deprecated = convertBoolean(attributes->takeAt(i).value(),
- deprecatedAttribute(), false);
- } else if (name == threadAttribute()) {
- isThread = convertBoolean(attributes->takeAt(i).value(),
- threadAttribute(), false);
- } else if (name == allowThreadAttribute()) {
- const QXmlStreamAttribute attribute = attributes->takeAt(i);
- allowThread = allowThreadFromAttribute(attribute.value());
- if (allowThread == TypeSystem::AllowThread::Unspecified) {
- m_error = msgInvalidAttributeValue(attribute);
- return false;
- }
- } else if (name == exceptionHandlingAttribute()) {
- const auto attribute = attributes->takeAt(i);
- exceptionHandling = exceptionHandlingFromAttribute(attribute.value());
- if (exceptionHandling == TypeSystem::ExceptionHandling::Unspecified) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgInvalidAttributeValue(attribute)));
- }
- } else if (name == virtualSlotAttribute()) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeWarning(reader, name)));
- }
- }
-
- const QString signature = TypeDatabase::normalizedSignature(originalSignature);
- if (signature.isEmpty()) {
- m_error = QLatin1String("No signature for modified function");
- return false;
- }
-
- QString errorString = checkSignatureError(signature, QLatin1String("modify-function"));
- if (!errorString.isEmpty()) {
- m_error = errorString;
- return false;
- }
-
- FunctionModification mod;
- if (!mod.setSignature(signature, &m_error))
- return false;
- mod.setOriginalSignature(originalSignature);
- mod.setExceptionHandling(exceptionHandling);
- m_currentSignature = signature;
-
- if (!access.isEmpty()) {
- const Modification::Modifiers m = modifierFromAttribute(access);
- if ((m & (Modification::AccessModifierMask | Modification::FinalMask)) == 0) {
- m_error = QString::fromLatin1("Bad access type '%1'").arg(access);
- return false;
- }
- if (m == Modification::Final || m == Modification::NonFinal) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeValueWarning(reader,
- accessAttribute(), access)));
- }
- mod.modifiers |= m;
- }
-
- if (deprecated)
- mod.modifiers |= Modification::Deprecated;
-
- if (!removal.isEmpty() && !convertRemovalAttribute(removal, mod, m_error))
- return false;
-
- if (!rename.isEmpty()) {
- mod.renamedToName = rename;
- mod.modifiers |= Modification::Rename;
- }
-
- if (!association.isEmpty())
- mod.association = association;
-
- mod.setIsThread(isThread);
- if (allowThread != TypeSystem::AllowThread::Unspecified)
- mod.setAllowThread(allowThread);
-
- m_contextStack.top()->functionMods << mod;
- return true;
-}
-
-bool TypeSystemParser::parseReplaceDefaultExpression(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (!(topElement.type & StackElement::ModifyArgument)) {
- m_error = QLatin1String("Replace default expression only allowed as child of argument modification");
- return false;
- }
- const int withIndex = indexOfAttribute(*attributes, u"with");
- if (withIndex == -1 || attributes->at(withIndex).value().isEmpty()) {
- m_error = QLatin1String("Default expression replaced with empty string. Use remove-default-expression instead.");
- return false;
- }
-
- m_contextStack.top()->functionMods.last().argument_mods.last().replacedDefaultExpression =
- attributes->takeAt(withIndex).value().toString();
- return true;
-}
-
-CustomFunction *
- TypeSystemParser::parseCustomMetaConstructor(const QXmlStreamReader &,
- StackElement::ElementType type,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- QString functionName = topElement.entry->name().toLower()
- + (type == StackElement::CustomMetaConstructor
- ? QLatin1String("_create") : QLatin1String("_delete"));
- QString paramName = QLatin1String("copy");
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == nameAttribute())
- functionName = attributes->takeAt(i).value().toString();
- else if (name == QLatin1String("param-name"))
- paramName = attributes->takeAt(i).value().toString();
- }
- auto *func = new CustomFunction(functionName);
- func->paramName = paramName;
- return func;
-}
-
-bool TypeSystemParser::parseReferenceCount(const QXmlStreamReader &reader,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyArgument) {
- m_error = QLatin1String("reference-count must be child of modify-argument");
- return false;
- }
-
- ReferenceCount rc;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == actionAttribute()) {
- const QXmlStreamAttribute attribute = attributes->takeAt(i);
- rc.action = referenceCountFromAttribute(attribute.value());
- switch (rc.action) {
- case ReferenceCount::Invalid:
- m_error = QLatin1String("unrecognized value '") + attribute.value()
- + QLatin1String("' for action attribute.");
- return false;
- case ReferenceCount::AddAll:
- case ReferenceCount::Ignore:
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedAttributeValueWarning(reader, attribute)));
- break;
- default:
- break;
- }
- } else if (name == QLatin1String("variable-name")) {
- rc.varName = attributes->takeAt(i).value().toString();
- }
- }
-
- m_contextStack.top()->functionMods.last().argument_mods.last().referenceCounts.append(rc);
- return true;
-}
-
-bool TypeSystemParser::parseParentOwner(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::ModifyArgument) {
- m_error = QLatin1String("parent-policy must be child of modify-argument");
- return false;
- }
- ArgumentOwner ao;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == indexAttribute()) {
- const QString index = attributes->takeAt(i).value().toString();
- if (!parseArgumentIndex(index, &ao.index, &m_error))
- return false;
- } else if (name == actionAttribute()) {
- const QStringRef action = attributes->takeAt(i).value();
- ao.action = argumentOwnerActionFromAttribute(action);
- if (ao.action == ArgumentOwner::Invalid) {
- m_error = QLatin1String("Invalid parent actionr '") + action + QLatin1String("'.");
- return false;
- }
- }
- }
- m_contextStack.top()->functionMods.last().argument_mods.last().owner = ao;
- return true;
-}
-
-bool TypeSystemParser::readFileSnippet(QXmlStreamAttributes *attributes, CodeSnip *snip)
-{
- QString fileName;
- QString snippetLabel;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == QLatin1String("file")) {
- fileName = attributes->takeAt(i).value().toString();
- } else if (name == snippetAttribute()) {
- snippetLabel = attributes->takeAt(i).value().toString();
- }
- }
- if (fileName.isEmpty())
- return true;
- const QString resolved = m_database->modifiedTypesystemFilepath(fileName, m_currentPath);
- if (!QFile::exists(resolved)) {
- m_error = QLatin1String("File for inject code not exist: ")
- + QDir::toNativeSeparators(fileName);
- return false;
- }
- QFile codeFile(resolved);
- if (!codeFile.open(QIODevice::Text | QIODevice::ReadOnly)) {
- m_error = msgCannotOpenForReading(codeFile);
- return false;
- }
- QString source = fileName;
- if (!snippetLabel.isEmpty())
- source += QLatin1String(" (") + snippetLabel + QLatin1Char(')');
- QString content;
- QTextStream str(&content);
- str << "// ========================================================================\n"
- "// START of custom code block [file: "
- << source << "]\n"
- << extractSnippet(QString::fromUtf8(codeFile.readAll()), snippetLabel)
- << "\n// END of custom code block [file: " << source
- << "]\n// ========================================================================\n";
- snip->addCode(content);
- return true;
-}
-
-bool TypeSystemParser::parseInjectCode(const QXmlStreamReader &,
- const StackElement &topElement,
- StackElement* element, QXmlStreamAttributes *attributes)
-{
- if (!(topElement.type & StackElement::ComplexTypeEntryMask)
- && (topElement.type != StackElement::AddFunction)
- && (topElement.type != StackElement::ModifyFunction)
- && (topElement.type != StackElement::Root)) {
- m_error = QLatin1String("wrong parent type for code injection");
- return false;
- }
-
- TypeSystem::CodeSnipPosition position = TypeSystem::CodeSnipPositionBeginning;
- TypeSystem::Language lang = TypeSystem::TargetLangCode;
- CodeSnip snip;
- if (!readFileSnippet(attributes, &snip))
- return false;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == classAttribute()) {
- const QStringRef className = attributes->takeAt(i).value();
- lang = languageFromAttribute(className);
- if (lang == TypeSystem::NoLanguage) {
- m_error = QStringLiteral("Invalid class specifier: '%1'").arg(className);
- return false;
- }
- } else if (name == positionAttribute()) {
- const QStringRef value = attributes->takeAt(i).value();
- position = codeSnipPositionFromAttribute(value);
- if (position == TypeSystem::CodeSnipPositionInvalid) {
- m_error = QStringLiteral("Invalid position: '%1'").arg(value);
- return false;
- }
- }
- }
-
- snip.position = position;
- snip.language = lang;
-
- if (snip.language == TypeSystem::Interface
- && topElement.type != StackElement::InterfaceTypeEntry) {
- m_error = QLatin1String("Interface code injections must be direct child of an interface type entry");
- return false;
- }
-
- if (topElement.type == StackElement::ModifyFunction
- || topElement.type == StackElement::AddFunction) {
- if (snip.language == TypeSystem::ShellDeclaration) {
- m_error = QLatin1String("no function implementation in shell declaration in which to inject code");
- return false;
- }
-
- FunctionModification &mod = m_contextStack.top()->functionMods.last();
- mod.snips << snip;
- if (!snip.code().isEmpty())
- mod.modifiers |= FunctionModification::CodeInjection;
- element->type = StackElement::InjectCodeInFunction;
- } else if (topElement.type == StackElement::Root) {
- element->entry->addCodeSnip(snip);
- } else if (topElement.type != StackElement::Root) {
- m_contextStack.top()->codeSnips << snip;
- }
- return true;
-}
-
-bool TypeSystemParser::parseInclude(const QXmlStreamReader &,
- const StackElement &topElement,
- TypeEntry *entry, QXmlStreamAttributes *attributes)
-{
- QString fileName;
- QString location;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == fileNameAttribute())
- fileName = attributes->takeAt(i).value().toString();
- else if (name == locationAttribute())
- location = attributes->takeAt(i).value().toString();
- }
- const Include::IncludeType loc = locationFromAttribute(location);
- if (loc == Include::InvalidInclude) {
- m_error = QStringLiteral("Location not recognized: '%1'").arg(location);
- return false;
- }
-
- Include inc(loc, fileName);
- if (topElement.type
- & (StackElement::ComplexTypeEntryMask | StackElement::PrimitiveTypeEntry)) {
- entry->setInclude(inc);
- } else if (topElement.type == StackElement::ExtraIncludes) {
- entry->addExtraInclude(inc);
- } else {
- m_error = QLatin1String("Only supported parent tags are primitive-type, complex types or extra-includes");
- return false;
- }
- return true;
-}
-
-bool TypeSystemParser::parseSystemInclude(const QXmlStreamReader &,
- QXmlStreamAttributes *attributes)
-{
- const int index = indexOfAttribute(*attributes, fileNameAttribute());
- if (index == -1) {
- m_error = msgMissingAttribute(fileNameAttribute());
- return false;
- }
- TypeDatabase::instance()->addSystemInclude(attributes->takeAt(index).value().toString());
- return true;
-}
-
-TemplateInstance *
- TypeSystemParser::parseTemplateInstanceEnum(const QXmlStreamReader &,
- const StackElement &topElement,
- QXmlStreamAttributes *attributes)
-{
- if (!(topElement.type & StackElement::CodeSnipMask) &&
- (topElement.type != StackElement::Template) &&
- (topElement.type != StackElement::CustomMetaConstructor) &&
- (topElement.type != StackElement::CustomMetaDestructor) &&
- (topElement.type != StackElement::NativeToTarget) &&
- (topElement.type != StackElement::AddConversion) &&
- (topElement.type != StackElement::ConversionRule)) {
- m_error = QLatin1String("Can only insert templates into code snippets, templates, custom-constructors, "\
- "custom-destructors, conversion-rule, native-to-target or add-conversion tags.");
- return nullptr;
- }
- const int nameIndex = indexOfAttribute(*attributes, nameAttribute());
- if (nameIndex == -1) {
- m_error = msgMissingAttribute(nameAttribute());
- return nullptr;
- }
- return new TemplateInstance(attributes->takeAt(nameIndex).value().toString());
-}
-
-bool TypeSystemParser::parseReplace(const QXmlStreamReader &,
- const StackElement &topElement,
- StackElement *element, QXmlStreamAttributes *attributes)
-{
- if (topElement.type != StackElement::TemplateInstanceEnum) {
- m_error = QLatin1String("Can only insert replace rules into insert-template.");
- return false;
- }
- QString from;
- QString to;
- for (int i = attributes->size() - 1; i >= 0; --i) {
- const QStringRef name = attributes->at(i).qualifiedName();
- if (name == QLatin1String("from"))
- from = attributes->takeAt(i).value().toString();
- else if (name == toAttribute())
- to = attributes->takeAt(i).value().toString();
- }
- element->parent->value.templateInstance->addReplaceRule(from, to);
- return true;
-}
-
-static bool parseVersion(const QString &versionSpec, const QString &package,
- QVersionNumber *result, QString *errorMessage)
-{
- *result = QVersionNumber::fromString(versionSpec);
- if (result->isNull()) {
- *errorMessage = msgInvalidVersion(versionSpec, package);
- return false;
- }
- return true;
-}
-
-bool TypeSystemParser::startElement(const QXmlStreamReader &reader)
-{
- if (m_ignoreDepth) {
- ++m_ignoreDepth;
- return true;
- }
-
- const QStringRef tagName = reader.name();
- QXmlStreamAttributes attributes = reader.attributes();
-
- VersionRange versionRange;
- for (int i = attributes.size() - 1; i >= 0; --i) {
- const QStringRef name = attributes.at(i).qualifiedName();
- if (name == sinceAttribute()) {
- if (!parseVersion(attributes.takeAt(i).value().toString(),
- m_defaultPackage, &versionRange.since, &m_error)) {
- return false;
- }
- } else if (name == untilAttribute()) {
- if (!parseVersion(attributes.takeAt(i).value().toString(),
- m_defaultPackage, &versionRange.until, &m_error)) {
- return false;
- }
- }
- }
-
- if (!m_defaultPackage.isEmpty() && !versionRange.isNull()) {
- TypeDatabase* td = TypeDatabase::instance();
- if (!td->checkApiVersion(m_defaultPackage, versionRange)) {
- ++m_ignoreDepth;
- return true;
- }
- }
-
- if (tagName.compare(QLatin1String("import-file"), Qt::CaseInsensitive) == 0)
- return importFileElement(attributes);
-
- const StackElement::ElementType elementType = elementFromTag(tagName);
- if (elementType == StackElement::None) {
- m_error = QStringLiteral("Unknown tag name: '%1'").arg(tagName);
- return false;
- }
-
- if (m_currentDroppedEntry) {
- ++m_currentDroppedEntryDepth;
- return true;
- }
-
- auto *element = new StackElement(m_current);
- element->type = elementType;
-
- if (element->type == StackElement::Root && m_generate == TypeEntry::GenerateAll)
- customConversionsForReview.clear();
-
- if (element->type == StackElement::CustomMetaConstructor
- || element->type == StackElement::CustomMetaDestructor) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedElementWarning(reader, tagName)));
- }
-
- switch (element->type) {
- case StackElement::Root:
- case StackElement::NamespaceTypeEntry:
- case StackElement::InterfaceTypeEntry:
- case StackElement::ObjectTypeEntry:
- case StackElement::ValueTypeEntry:
- case StackElement::PrimitiveTypeEntry:
- case StackElement::TypedefTypeEntry:
- m_contextStack.push(new StackElementContext());
- break;
- default:
- break;
- }
-
- if (element->type & StackElement::TypeEntryMask) {
- QString name;
- if (element->type != StackElement::FunctionTypeEntry) {
- const int nameIndex = indexOfAttribute(attributes, nameAttribute());
- if (nameIndex != -1) {
- name = attributes.takeAt(nameIndex).value().toString();
- } else if (element->type != StackElement::EnumTypeEntry) { // anonymous enum?
- m_error = msgMissingAttribute(nameAttribute());
- return false;
- }
- }
- // Allow for primitive and/or std:: types only, else require proper nesting.
- if (element->type != StackElement::PrimitiveTypeEntry && name.contains(QLatin1Char(':'))
- && !name.contains(QLatin1String("std::"))) {
- m_error = msgIncorrectlyNestedName(name);
- return false;
- }
-
- if (m_database->hasDroppedTypeEntries()) {
- QString identifier = getNamePrefix(element) + QLatin1Char('.');
- identifier += element->type == StackElement::FunctionTypeEntry
- ? attributes.value(signatureAttribute()).toString()
- : name;
- if (m_database->shouldDropTypeEntry(identifier)) {
- m_currentDroppedEntry = element;
- m_currentDroppedEntryDepth = 1;
- if (ReportHandler::isDebug(ReportHandler::SparseDebug)) {
- qCInfo(lcShiboken, "Type system entry '%s' was intentionally dropped from generation.",
- qPrintable(identifier));
- }
- return true;
- }
- }
-
- // The top level tag 'function' has only the 'signature' tag
- // and we should extract the 'name' value from it.
- if (element->type == StackElement::FunctionTypeEntry
- && !parseRenameFunction(reader, &name, &attributes)) {
- return false;
- }
-
- // We need to be able to have duplicate primitive type entries,
- // or it's not possible to cover all primitive target language
- // types (which we need to do in order to support fake meta objects)
- if (element->type != StackElement::PrimitiveTypeEntry
- && element->type != StackElement::FunctionTypeEntry) {
- TypeEntry *tmp = m_database->findType(name);
- if (tmp && !tmp->isNamespace())
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("Duplicate type entry: '%1'").arg(name);
- }
-
- if (element->type == StackElement::EnumTypeEntry) {
- const int enumIdentifiedByIndex = indexOfAttribute(attributes, enumIdentifiedByValueAttribute());
- const QString identifiedByValue = enumIdentifiedByIndex != -1
- ? attributes.takeAt(enumIdentifiedByIndex).value().toString() : QString();
- if (name.isEmpty()) {
- name = identifiedByValue;
- } else if (!identifiedByValue.isEmpty()) {
- m_error = QLatin1String("can't specify both 'name' and 'identified-by-value' attributes");
- return false;
- }
- }
-
- if (name.isEmpty()) {
- m_error = QLatin1String("no 'name' attribute specified");
- return false;
- }
-
- switch (element->type) {
- case StackElement::CustomTypeEntry:
- if (!checkRootElement())
- return false;
- element->entry = new TypeEntry(name, TypeEntry::CustomType, versionRange.since, m_current->entry);
- break;
- case StackElement::PrimitiveTypeEntry:
- element->entry = parsePrimitiveTypeEntry(reader, name, versionRange.since, &attributes);
- if (Q_UNLIKELY(!element->entry))
- return false;
- break;
- case StackElement::ContainerTypeEntry:
- if (ContainerTypeEntry *ce = parseContainerTypeEntry(reader, name, versionRange.since, &attributes)) {
- applyComplexTypeAttributes(reader, ce, &attributes);
- element->entry = ce;
- } else {
- return false;
- }
- break;
-
- case StackElement::SmartPointerTypeEntry:
- if (SmartPointerTypeEntry *se = parseSmartPointerEntry(reader, name, versionRange.since, &attributes)) {
- applyComplexTypeAttributes(reader, se, &attributes);
- element->entry = se;
- } else {
- return false;
- }
- break;
- case StackElement::EnumTypeEntry:
- m_currentEnum = parseEnumTypeEntry(reader, name, versionRange.since, &attributes);
- if (Q_UNLIKELY(!m_currentEnum))
- return false;
- element->entry = m_currentEnum;
- break;
-
- case StackElement::ValueTypeEntry:
- if (ValueTypeEntry *ve = parseValueTypeEntry(reader, name, versionRange.since, &attributes)) {
- applyComplexTypeAttributes(reader, ve, &attributes);
- element->entry = ve;
- } else {
- return false;
- }
- break;
- case StackElement::NamespaceTypeEntry:
- if (auto entry = parseNamespaceTypeEntry(reader, name, versionRange.since, &attributes))
- element->entry = entry;
- else
- return false;
- break;
- case StackElement::ObjectTypeEntry:
- case StackElement::InterfaceTypeEntry:
- if (!checkRootElement())
- return false;
- element->entry = new ObjectTypeEntry(name, versionRange.since, currentParentTypeEntry());
- applyCommonAttributes(element->entry, &attributes);
- applyComplexTypeAttributes(reader, static_cast<ComplexTypeEntry *>(element->entry), &attributes);
- break;
- case StackElement::FunctionTypeEntry:
- element->entry = parseFunctionTypeEntry(reader, name, versionRange.since, &attributes);
- if (Q_UNLIKELY(!element->entry))
- return false;
- break;
- case StackElement::TypedefTypeEntry:
- if (TypedefEntry *te = parseTypedefEntry(reader, name, versionRange.since, &attributes)) {
- applyComplexTypeAttributes(reader, te, &attributes);
- element->entry = te;
- } else {
- return false;
- }
- break;
- default:
- Q_ASSERT(false);
- }
-
- if (element->entry) {
- if (!m_database->addType(element->entry, &m_error))
- return false;
- } else {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("Type: %1 was rejected by typesystem").arg(name);
- }
-
- } else if (element->type == StackElement::InjectDocumentation) {
- if (!parseInjectDocumentation(reader, &attributes))
- return false;
- } else if (element->type == StackElement::ModifyDocumentation) {
- if (!parseModifyDocumentation(reader, &attributes))
- return false;
- } else if (element->type != StackElement::None) {
- bool topLevel = element->type == StackElement::Root
- || element->type == StackElement::SuppressedWarning
- || element->type == StackElement::Rejection
- || element->type == StackElement::LoadTypesystem
- || element->type == StackElement::InjectCode
- || element->type == StackElement::ExtraIncludes
- || element->type == StackElement::SystemInclude
- || element->type == StackElement::ConversionRule
- || element->type == StackElement::AddFunction
- || element->type == StackElement::Template;
-
- if (!topLevel && m_current->type == StackElement::Root) {
- m_error = QStringLiteral("Tag requires parent: '%1'").arg(tagName);
- return false;
- }
-
- StackElement topElement = !m_current ? StackElement(nullptr) : *m_current;
- element->entry = topElement.entry;
-
- switch (element->type) {
- case StackElement::Root:
- element->entry = parseRootElement(reader, versionRange.since, &attributes);
- element->type = StackElement::Root;
- break;
- case StackElement::LoadTypesystem:
- if (!loadTypesystem(reader, &attributes))
- return false;
- break;
- case StackElement::RejectEnumValue:
- if (!parseRejectEnumValue(reader, &attributes))
- return false;
- break;
- case StackElement::ReplaceType:
- if (!parseReplaceArgumentType(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::ConversionRule:
- if (!TypeSystemParser::parseCustomConversion(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::NativeToTarget:
- if (!parseNativeToTarget(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::TargetToNative: {
- if (topElement.type != StackElement::ConversionRule) {
- m_error = QLatin1String("Target to Native conversions can only be specified for custom conversion rules.");
- return false;
- }
- const int replaceIndex = indexOfAttribute(attributes, replaceAttribute());
- const bool replace = replaceIndex == -1
- || convertBoolean(attributes.takeAt(replaceIndex).value(),
- replaceAttribute(), true);
- m_current->entry->customConversion()->setReplaceOriginalTargetToNativeConversions(replace);
- }
- break;
- case StackElement::AddConversion:
- if (!parseAddConversion(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::ModifyArgument:
- if (!parseModifyArgument(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::NoNullPointers:
- if (!parseNoNullPointer(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::DefineOwnership:
- if (!parseDefineOwnership(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::SuppressedWarning: {
- const int textIndex = indexOfAttribute(attributes, textAttribute());
- if (textIndex == -1) {
- qCWarning(lcShiboken) << "Suppressed warning with no text specified";
- } else {
- const QString suppressedWarning =
- attributes.takeAt(textIndex).value().toString();
- if (!m_database->addSuppressedWarning(suppressedWarning, &m_error))
- return false;
- }
- }
- break;
- case StackElement::ArgumentMap:
- qCWarning(lcShiboken, "%s",
- qPrintable(msgUnimplementedElementWarning(reader, tagName)));
- if (!parseArgumentMap(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::Removal:
- if (!parseRemoval(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::Rename:
- case StackElement::Access:
- if (!parseRename(reader, element->type, topElement, &attributes))
- return false;
- break;
- case StackElement::RemoveArgument:
- if (topElement.type != StackElement::ModifyArgument) {
- m_error = QLatin1String("Removing argument requires argument modification as parent");
- return false;
- }
-
- m_contextStack.top()->functionMods.last().argument_mods.last().removed = true;
- break;
-
- case StackElement::ModifyField:
- if (!parseModifyField(reader, &attributes))
- return false;
- break;
- case StackElement::AddFunction:
- if (!parseAddFunction(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::ModifyFunction:
- if (!parseModifyFunction(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::ReplaceDefaultExpression:
- if (!parseReplaceDefaultExpression(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::RemoveDefaultExpression:
- m_contextStack.top()->functionMods.last().argument_mods.last().removedDefaultExpression = true;
- break;
- case StackElement::CustomMetaConstructor:
- case StackElement::CustomMetaDestructor:
- element->value.customFunction =
- parseCustomMetaConstructor(reader, element->type, topElement, &attributes);
- break;
- case StackElement::ReferenceCount:
- if (!parseReferenceCount(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::ParentOwner:
- if (!parseParentOwner(reader, topElement, &attributes))
- return false;
- break;
- case StackElement::Array:
- if (topElement.type != StackElement::ModifyArgument) {
- m_error = QLatin1String("array must be child of modify-argument");
- return false;
- }
- m_contextStack.top()->functionMods.last().argument_mods.last().array = true;
- break;
- case StackElement::InjectCode:
- if (!parseInjectCode(reader, topElement, element, &attributes))
- return false;
- break;
- case StackElement::Include:
- if (!parseInclude(reader, topElement, element->entry, &attributes))
- return false;
- break;
- case StackElement::Rejection:
- if (!addRejection(m_database, &attributes, &m_error))
- return false;
- break;
- case StackElement::SystemInclude:
- if (!parseSystemInclude(reader, &attributes))
- return false;
- break;
- case StackElement::Template: {
- const int nameIndex = indexOfAttribute(attributes, nameAttribute());
- if (nameIndex == -1) {
- m_error = msgMissingAttribute(nameAttribute());
- return false;
- }
- element->value.templateEntry =
- new TemplateEntry(attributes.takeAt(nameIndex).value().toString());
- }
- break;
- case StackElement::TemplateInstanceEnum:
- element->value.templateInstance =
- parseTemplateInstanceEnum(reader, topElement, &attributes);
- if (!element->value.templateInstance)
- return false;
- break;
- case StackElement::Replace:
- if (!parseReplace(reader, topElement, element, &attributes))
- return false;
- break;
- default:
- break; // nada
- }
- }
-
- if (!attributes.isEmpty()) {
- const QString message = msgUnusedAttributes(tagName, attributes);
- qCWarning(lcShiboken, "%s", qPrintable(msgReaderWarning(reader, message)));
- }
-
- m_current = element;
- return true;
-}
diff --git a/sources/shiboken2/ApiExtractor/typesystemparser.h b/sources/shiboken2/ApiExtractor/typesystemparser.h
deleted file mode 100644
index b4be2765c..000000000
--- a/sources/shiboken2/ApiExtractor/typesystemparser.h
+++ /dev/null
@@ -1,279 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef TYPESYSTEMPARSER_H
-#define TYPESYSTEMPARSER_H
-
-#include "typesystem.h"
-
-#include <QtCore/QStack>
-#include <QtCore/QHash>
-#include <QtCore/QScopedPointer>
-
-QT_FORWARD_DECLARE_CLASS(QXmlStreamAttributes)
-QT_FORWARD_DECLARE_CLASS(QXmlStreamReader)
-
-class TypeSystemEntityResolver;
-class TypeDatabase;
-class StackElement
-{
- public:
- enum ElementType {
- None = 0x0,
-
- // Type tags (0x1, ... , 0xff)
- ObjectTypeEntry = 0x1,
- ValueTypeEntry = 0x2,
- InterfaceTypeEntry = 0x3,
- NamespaceTypeEntry = 0x4,
- ComplexTypeEntryMask = 0x7,
-
- // Non-complex type tags (0x8, 0x9, ... , 0xf)
- PrimitiveTypeEntry = 0x8,
- EnumTypeEntry = 0x9,
- ContainerTypeEntry = 0xa,
- FunctionTypeEntry = 0xb,
- CustomTypeEntry = 0xc,
- SmartPointerTypeEntry = 0xd,
- TypedefTypeEntry = 0xe,
- TypeEntryMask = 0xf,
-
- // Documentation tags
- InjectDocumentation = 0x10,
- ModifyDocumentation = 0x20,
- DocumentationMask = 0xf0,
-
- // Simple tags (0x100, 0x200, ... , 0xf00)
- ExtraIncludes = 0x0100,
- Include = 0x0200,
- ModifyFunction = 0x0300,
- ModifyField = 0x0400,
- Root = 0x0500,
- CustomMetaConstructor = 0x0600,
- CustomMetaDestructor = 0x0700,
- ArgumentMap = 0x0800,
- SuppressedWarning = 0x0900,
- Rejection = 0x0a00,
- LoadTypesystem = 0x0b00,
- RejectEnumValue = 0x0c00,
- Template = 0x0d00,
- TemplateInstanceEnum = 0x0e00,
- Replace = 0x0f00,
- AddFunction = 0x1000,
- NativeToTarget = 0x1100,
- TargetToNative = 0x1200,
- AddConversion = 0x1300,
- SystemInclude = 0x1400,
- SimpleMask = 0x3f00,
-
- // Code snip tags (0x1000, 0x2000, ... , 0xf000)
- InjectCode = 0x4000,
- InjectCodeInFunction = 0x8000,
- CodeSnipMask = 0xc000,
-
- // Function modifier tags (0x010000, 0x020000, ... , 0xf00000)
- Access = 0x010000,
- Removal = 0x020000,
- Rename = 0x040000,
- ModifyArgument = 0x080000,
- Thread = 0x100000,
- FunctionModifiers = 0xff0000,
-
- // Argument modifier tags (0x01000000 ... 0xf0000000)
- ConversionRule = 0x01000000,
- ReplaceType = 0x02000000,
- ReplaceDefaultExpression = 0x04000000,
- RemoveArgument = 0x08000000,
- DefineOwnership = 0x10000000,
- RemoveDefaultExpression = 0x20000000,
- NoNullPointers = 0x40000000,
- ReferenceCount = 0x80000000,
- ParentOwner = 0x90000000,
- Array = 0xA0000000,
- ArgumentModifiers = 0xff000000
- };
-
- StackElement(StackElement *p) : entry(nullptr), type(None), parent(p) { }
-
- TypeEntry* entry;
- ElementType type;
- StackElement *parent;
-
- union {
- TemplateInstance* templateInstance;
- TemplateEntry* templateEntry;
- CustomFunction* customFunction;
- } value;
-};
-
-struct StackElementContext
-{
- CodeSnipList codeSnips;
- AddedFunctionList addedFunctions;
- FunctionModificationList functionMods;
- FieldModificationList fieldMods;
- DocModificationList docModifications;
- int addedFunctionModificationIndex = -1;
-};
-
-class TypeSystemParser
-{
-public:
- Q_DISABLE_COPY(TypeSystemParser)
-
- TypeSystemParser(TypeDatabase* database, bool generate);
- ~TypeSystemParser();
-
- bool parse(QXmlStreamReader &reader);
-
- QString errorString() const { return m_error; }
-
-private:
- bool parseXml(QXmlStreamReader &reader);
- bool setupSmartPointerInstantiations();
- bool startElement(const QXmlStreamReader &reader);
- SmartPointerTypeEntry *parseSmartPointerEntry(const QXmlStreamReader &,
- const QString &name,
- const QVersionNumber &since,
- QXmlStreamAttributes *attributes);
- bool endElement(const QStringRef& localName);
- template <class String> // QString/QStringRef
- bool characters(const String &ch);
-
- bool importFileElement(const QXmlStreamAttributes &atts);
-
- const TypeEntry *currentParentTypeEntry() const;
- bool checkRootElement();
- void applyCommonAttributes(TypeEntry *type, QXmlStreamAttributes *attributes) const;
- PrimitiveTypeEntry *
- parsePrimitiveTypeEntry(const QXmlStreamReader &, const QString &name,
- const QVersionNumber &since, QXmlStreamAttributes *);
- ContainerTypeEntry *
- parseContainerTypeEntry(const QXmlStreamReader &, const QString &name,
- const QVersionNumber &since, QXmlStreamAttributes *);
- EnumTypeEntry *
- parseEnumTypeEntry(const QXmlStreamReader &, const QString &name,
- const QVersionNumber &since, QXmlStreamAttributes *);
- FlagsTypeEntry *
- parseFlagsEntry(const QXmlStreamReader &, EnumTypeEntry *enumEntry,
- QString flagName, const QVersionNumber &since,
- QXmlStreamAttributes *);
-
- NamespaceTypeEntry *
- parseNamespaceTypeEntry(const QXmlStreamReader &,
- const QString &name, const QVersionNumber &since,
- QXmlStreamAttributes *attributes);
-
- ValueTypeEntry *
- parseValueTypeEntry(const QXmlStreamReader &, const QString &name,
- const QVersionNumber &since, QXmlStreamAttributes *);
- FunctionTypeEntry *
- parseFunctionTypeEntry(const QXmlStreamReader &, const QString &name,
- const QVersionNumber &since, QXmlStreamAttributes *);
- TypedefEntry *
- parseTypedefEntry(const QXmlStreamReader &, const QString &name,
- const QVersionNumber &since, QXmlStreamAttributes *);
- void applyComplexTypeAttributes(const QXmlStreamReader &, ComplexTypeEntry *ctype,
- QXmlStreamAttributes *) const;
- bool parseRenameFunction(const QXmlStreamReader &, QString *name,
- QXmlStreamAttributes *);
- bool parseInjectDocumentation(const QXmlStreamReader &, QXmlStreamAttributes *);
- bool parseModifyDocumentation(const QXmlStreamReader &, QXmlStreamAttributes *);
- TypeSystemTypeEntry *
- parseRootElement(const QXmlStreamReader &, const QVersionNumber &since,
- QXmlStreamAttributes *);
- bool loadTypesystem(const QXmlStreamReader &, QXmlStreamAttributes *);
- bool parseRejectEnumValue(const QXmlStreamReader &, QXmlStreamAttributes *);
- bool parseReplaceArgumentType(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseCustomConversion(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseAddConversion(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseNativeToTarget(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *attributes);
- bool parseModifyArgument(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *attributes);
- bool parseNoNullPointer(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *attributes);
- bool parseDefineOwnership(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseArgumentMap(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseRemoval(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseRename(const QXmlStreamReader &, StackElement::ElementType type,
- const StackElement &topElement, QXmlStreamAttributes *);
- bool parseModifyField(const QXmlStreamReader &, QXmlStreamAttributes *);
- bool parseAddFunction(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseModifyFunction(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseReplaceDefaultExpression(const QXmlStreamReader &,
- const StackElement &topElement, QXmlStreamAttributes *);
- CustomFunction *
- parseCustomMetaConstructor(const QXmlStreamReader &,
- StackElement::ElementType type,
- const StackElement &topElement, QXmlStreamAttributes *);
- bool parseReferenceCount(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseParentOwner(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool readFileSnippet(QXmlStreamAttributes *attributes, CodeSnip *snip);
- bool parseInjectCode(const QXmlStreamReader &, const StackElement &topElement,
- StackElement* element, QXmlStreamAttributes *);
- bool parseInclude(const QXmlStreamReader &, const StackElement &topElement,
- TypeEntry *entry, QXmlStreamAttributes *);
- bool parseSystemInclude(const QXmlStreamReader &, QXmlStreamAttributes *);
- TemplateInstance
- *parseTemplateInstanceEnum(const QXmlStreamReader &, const StackElement &topElement,
- QXmlStreamAttributes *);
- bool parseReplace(const QXmlStreamReader &, const StackElement &topElement,
- StackElement *element, QXmlStreamAttributes *);
-
- TypeDatabase* m_database;
- StackElement* m_current = nullptr;
- StackElement* m_currentDroppedEntry = nullptr;
- int m_currentDroppedEntryDepth = 0;
- int m_ignoreDepth = 0;
- QString m_defaultPackage;
- QString m_defaultSuperclass;
- TypeSystem::ExceptionHandling m_exceptionHandling = TypeSystem::ExceptionHandling::Unspecified;
- TypeSystem::AllowThread m_allowThread = TypeSystem::AllowThread::Unspecified;
- QString m_error;
- const TypeEntry::CodeGeneration m_generate;
-
- EnumTypeEntry* m_currentEnum = nullptr;
- QStack<StackElementContext*> m_contextStack;
-
- QString m_currentSignature;
- QString m_currentPath;
- QScopedPointer<TypeSystemEntityResolver> m_entityResolver;
- QHash<SmartPointerTypeEntry *, QString> m_smartPointerInstantiations;
-};
-
-#endif // TYPESYSTEMPARSER_H
diff --git a/sources/shiboken2/ApiExtractor/xmlutils.cpp b/sources/shiboken2/ApiExtractor/xmlutils.cpp
deleted file mode 100644
index a179412a7..000000000
--- a/sources/shiboken2/ApiExtractor/xmlutils.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "xmlutils.h"
-
-#include "xmlutils_qt.h"
-#include "xmlutils_libxslt.h"
-
-XQuery::XQuery() = default;
-
-XQuery::~XQuery() = default;
-
-QString XQuery::evaluate(QString xPathExpression, QString *errorMessage)
-{
- // XQuery can't have invalid XML characters
- xPathExpression.replace(QLatin1Char('&'), QLatin1String("&amp;"));
- xPathExpression.replace(QLatin1Char('<'), QLatin1String("&lt;"));
- return doEvaluate(xPathExpression, errorMessage);
-}
-
-QSharedPointer<XQuery> XQuery::create(const QString &focus, QString *errorMessage)
-{
-#if defined(HAVE_LIBXSLT)
- return libXml_createXQuery(focus, errorMessage);
-#elif defined(HAVE_QTXMLPATTERNS)
- return qt_createXQuery(focus, errorMessage);
-#else
- *errorMessage = QLatin1String(__FUNCTION__) + QLatin1String(" is not implemented.");
- return QSharedPointer<XQuery>();
-#endif
-}
-
-QString xsl_transform(const QString &xml, const QString &xsl, QString *errorMessage)
-{
-#if defined(HAVE_LIBXSLT)
- return libXslt_transform(xml, xsl, errorMessage);
-#elif defined(HAVE_QTXMLPATTERNS)
- return qt_xsl_transform(xml, xsl, errorMessage);
-#else
- *errorMessage = QLatin1String(__FUNCTION__) + QLatin1String(" is not implemented.");
- return xml;
-#endif
-}
diff --git a/sources/shiboken2/ApiExtractor/xmlutils.h b/sources/shiboken2/ApiExtractor/xmlutils.h
deleted file mode 100644
index 879b7757a..000000000
--- a/sources/shiboken2/ApiExtractor/xmlutils.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef XMLUTILS_H
-#define XMLUTILS_H
-
-#include <QtCore/QSharedPointer>
-#include <QtCore/QString>
-
-class XQuery
-{
-public:
- Q_DISABLE_COPY(XQuery);
-
- virtual ~XQuery();
-
- QString evaluate(QString xPathExpression, QString *errorMessage);
-
- static QSharedPointer<XQuery> create(const QString &focus, QString *errorMessage);
-
-protected:
- XQuery();
-
- virtual QString doEvaluate(const QString &xPathExpression, QString *errorMessage) = 0;
-};
-
-QString xsl_transform(const QString &xml, const QString &xsl, QString *errorMessage);
-
-#endif // XMLUTILS_H
diff --git a/sources/shiboken2/ApiExtractor/xmlutils_libxslt.cpp b/sources/shiboken2/ApiExtractor/xmlutils_libxslt.cpp
deleted file mode 100644
index e1e185130..000000000
--- a/sources/shiboken2/ApiExtractor/xmlutils_libxslt.cpp
+++ /dev/null
@@ -1,231 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "xmlutils_libxslt.h"
-#include "xmlutils.h"
-
-#include <QtCore/QByteArray>
-#include <QtCore/QCoreApplication>
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QString>
-
-#include <libxslt/xsltutils.h>
-#include <libxslt/transform.h>
-
-#include <libxml/xmlsave.h>
-#include <libxml/xpath.h>
-
-#include <cstdlib>
-#include <memory>
-
-static void cleanup()
-{
- xsltCleanupGlobals();
- xmlCleanupParser();
-}
-
-static void ensureInitialized()
-{
- static bool initialized = false;
- if (!initialized) {
- initialized = true;
- xmlInitParser();
- xsltInit();
- qAddPostRoutine(cleanup);
- }
-}
-
-namespace {
-
-// RAI Helpers for cleaning up libxml2/libxslt data
-
-struct XmlDocDeleter // for std::unique_ptr<xmlDoc>
-{
- void operator()(xmlDocPtr xmlDoc) { xmlFreeDoc(xmlDoc); }
-};
-
-struct XmlXPathObjectDeleter
-{
- void operator()(xmlXPathObjectPtr xPathObject) { xmlXPathFreeObject(xPathObject); }
-};
-
-struct XmlStyleSheetDeleter // for std::unique_ptr<xsltStylesheet>
-{
- void operator()(xsltStylesheetPtr xslt) { xsltFreeStylesheet(xslt); }
-};
-
-struct XmlXPathContextDeleter
-{
- void operator()(xmlXPathContextPtr xPathContext) { xmlXPathFreeContext(xPathContext); }
-};
-
-} // namespace
-
-using XmlDocUniquePtr = std::unique_ptr<xmlDoc, XmlDocDeleter>;
-using XmlPathObjectUniquePtr = std::unique_ptr<xmlXPathObject, XmlXPathObjectDeleter>;
-using XmlStyleSheetUniquePtr = std::unique_ptr<xsltStylesheet, XmlStyleSheetDeleter>;
-using XmlXPathContextUniquePtr = std::unique_ptr<xmlXPathContext, XmlXPathContextDeleter>;
-
-// Helpers for formatting nodes obtained from XPATH queries
-
-static int qbXmlOutputWriteCallback(void *context, const char *buffer, int len)
-{
- static_cast<QByteArray *>(context)->append(buffer, len);
- return len;
-}
-
-static int qbXmlOutputCloseCallback(void * /* context */) { return 0; }
-
-static QByteArray formatNode(xmlNodePtr node, QString *errorMessage)
-{
- QByteArray result;
- xmlSaveCtxtPtr saveContext =
- xmlSaveToIO(qbXmlOutputWriteCallback, qbXmlOutputCloseCallback,
- &result, "UTF-8", 0);
- if (!saveContext) {
- *errorMessage = QLatin1String("xmlSaveToIO() failed.");
- return result;
- }
- const long saveResult = xmlSaveTree(saveContext, node);
- xmlSaveClose(saveContext);
- if (saveResult < 0)
- *errorMessage = QLatin1String("xmlSaveTree() failed.");
- return result;
-}
-
-// XPath expressions
-class LibXmlXQuery : public XQuery
-{
-public:
- explicit LibXmlXQuery(XmlDocUniquePtr &doc, XmlXPathContextUniquePtr &xpathContext) :
- m_doc(std::move(doc)), m_xpathContext(std::move(xpathContext))
- {
- ensureInitialized();
- }
-
-protected:
- QString doEvaluate(const QString &xPathExpression, QString *errorMessage) override;
-
-private:
- XmlDocUniquePtr m_doc;
- XmlXPathContextUniquePtr m_xpathContext;
-};
-
-QString LibXmlXQuery::doEvaluate(const QString &xPathExpression, QString *errorMessage)
-{
- const QByteArray xPathExpressionB = xPathExpression.toUtf8();
- auto xPathExpressionX = reinterpret_cast<const xmlChar *>(xPathExpressionB.constData());
-
- XmlPathObjectUniquePtr xPathObject(xmlXPathEvalExpression(xPathExpressionX, m_xpathContext.get()));
- if (!xPathObject) {
- *errorMessage = QLatin1String("xmlXPathEvalExpression() failed for \"") + xPathExpression
- + QLatin1Char('"');
- return QString();
- }
- QString result;
- if (xmlNodeSetPtr nodeSet = xPathObject->nodesetval) {
- for (int n = 0, count = nodeSet->nodeNr; n < count; ++n) {
- auto node = nodeSet->nodeTab[n];
- if (node->type == XML_ELEMENT_NODE) {
- result += QString::fromLocal8Bit(formatNode(node, errorMessage));
- if (!errorMessage->isEmpty())
- return QString();
- }
- }
- }
- return result;
-}
-
-QSharedPointer<XQuery> libXml_createXQuery(const QString &focus, QString *errorMessage)
-{
- XmlDocUniquePtr doc(xmlParseFile(QFile::encodeName(focus).constData()));
- if (!doc) {
- *errorMessage = QLatin1String("libxml2: Cannot set focus to ") + QDir::toNativeSeparators(focus);
- return {};
- }
- XmlXPathContextUniquePtr xpathContext(xmlXPathNewContext(doc.get()));
- if (!xpathContext) {
- *errorMessage = QLatin1String("libxml2: xmlXPathNewContext() failed");
- return {};
- }
- return QSharedPointer<XQuery>(new LibXmlXQuery(doc, xpathContext));
-}
-
-// XSLT transformation
-
-static const char xsltPrefix[] = R"(<?xml version="1.0" encoding="UTF-8" ?>
- <xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
-)";
-
-QString libXslt_transform(const QString &xml, QString xsl, QString *errorMessage)
-{
- ensureInitialized();
- // Read XML data
- if (!xsl.startsWith(QLatin1String("<?xml"))) {
- xsl.prepend(QLatin1String(xsltPrefix));
- xsl.append(QLatin1String("</xsl:transform>"));
- }
- const QByteArray xmlData = xml.toUtf8();
- XmlDocUniquePtr xmlDoc(xmlParseMemory(xmlData.constData(), xmlData.size()));
- if (!xmlDoc) {
- *errorMessage = QLatin1String("xmlParseMemory() failed for XML.");
- return xml;
- }
-
- // Read XSL data as a XML file
- const QByteArray xslData = xsl.toUtf8();
- // xsltFreeStylesheet will delete this pointer
- xmlDocPtr xslDoc = xmlParseMemory(xslData.constData(), xslData.size());
- if (!xslDoc) {
- *errorMessage = QLatin1String("xmlParseMemory() failed for XSL \"")
- + xsl + QLatin1String("\".");
- return xml;
- };
-
- // Parse XSL data
- XmlStyleSheetUniquePtr xslt(xsltParseStylesheetDoc(xslDoc));
- if (!xslt) {
- *errorMessage = QLatin1String("xsltParseStylesheetDoc() failed.");
- return xml;
- }
-
- // Apply XSL
- XmlDocUniquePtr xslResult(xsltApplyStylesheet(xslt.get(), xmlDoc.get(), nullptr));
- xmlChar *buffer = nullptr;
- int bufferSize;
- QString result;
- if (xsltSaveResultToString(&buffer, &bufferSize, xslResult.get(), xslt.get()) == 0) {
- result = QString::fromUtf8(reinterpret_cast<char*>(buffer), bufferSize);
- std::free(buffer);
- } else {
- *errorMessage = QLatin1String("xsltSaveResultToString() failed.");
- result = xml;
- }
- return result.trimmed();
-}
diff --git a/sources/shiboken2/ApiExtractor/xmlutils_libxslt.h b/sources/shiboken2/ApiExtractor/xmlutils_libxslt.h
deleted file mode 100644
index c32b3901d..000000000
--- a/sources/shiboken2/ApiExtractor/xmlutils_libxslt.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef XMLUTILS_LIBXSLT_H
-#define XMLUTILS_LIBXSLT_H
-
-#include <QtCore/QString>
-#include <QtCore/QSharedPointer>
-
-class XQuery;
-
-QSharedPointer<XQuery> libXml_createXQuery(const QString &focus, QString *errorMessage);
-
-QString libXslt_transform(const QString &xml, QString xsl, QString *errorMessage);
-
-#endif // XMLUTILS_LIBXSLT_H
diff --git a/sources/shiboken2/ApiExtractor/xmlutils_qt.cpp b/sources/shiboken2/ApiExtractor/xmlutils_qt.cpp
deleted file mode 100644
index f703bc5f9..000000000
--- a/sources/shiboken2/ApiExtractor/xmlutils_qt.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "xmlutils.h"
-#include "xmlutils_qt.h"
-
-#include <QtXmlPatterns/QXmlQuery>
-
-#include <QtCore/QDir>
-#include <QtCore/QUrl>
-
-class QtXQuery : public XQuery
-{
-public:
- QtXQuery() = default;
-
- bool setFocus(const QString &fileName)
- { return m_xquery.setFocus(QUrl::fromLocalFile(fileName)); }
-
-protected:
- QString doEvaluate(const QString &xPathExpression, QString *errorMessage) override;
-
-private:
- QXmlQuery m_xquery;
-};
-
-QString QtXQuery::doEvaluate(const QString &xPathExpression, QString *errorMessage)
-{
- m_xquery.setQuery(xPathExpression);
- if (!m_xquery.isValid()) {
- *errorMessage = QLatin1String("QXmlQuery: Bad query: \"") + xPathExpression
- + QLatin1Char('"');
- return QString();
- }
-
- QString result;
- m_xquery.evaluateTo(&result);
- return result;
-}
-
-QSharedPointer<XQuery> qt_createXQuery(const QString &focus, QString *errorMessage)
-{
- QSharedPointer<QtXQuery> result(new QtXQuery);
- if (!result->setFocus(focus)) {
- *errorMessage = QLatin1String("QXmlQuery: Cannot set focus to ") + QDir::toNativeSeparators(focus);
- result.reset();
- }
- return std::move(result);
-}
-
-// XSLT transformation
-
-static const char xsltPrefix[] = R"(<?xml version="1.0" encoding="UTF-8"?>
- <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
-)";
-
-QString qt_xsl_transform(const QString &xml, QString xsl, QString *errorMessage)
-{
- QXmlQuery query(QXmlQuery::XSLT20);
- if (!xsl.startsWith(QLatin1String("<?xml"))) {
- xsl.prepend(QLatin1String(xsltPrefix));
- xsl.append(QLatin1String("</xsl:stylesheet>"));
- }
- query.setFocus(xml);
- query.setQuery(xsl);
- if (!query.isValid()) {
- *errorMessage = QLatin1String("QXmlQuery: Invalid query \"") + xsl
- + QLatin1String("\".");
- return xml;
- }
- QString result;
- if (!query.evaluateTo(&result)) {
- *errorMessage = QLatin1String("QXmlQuery: evaluate() failed.");
- return xml;
- }
- return result.trimmed();
-}
diff --git a/sources/shiboken2/ApiExtractor/xmlutils_qt.h b/sources/shiboken2/ApiExtractor/xmlutils_qt.h
deleted file mode 100644
index a9c9adfa2..000000000
--- a/sources/shiboken2/ApiExtractor/xmlutils_qt.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef XMLUTILS_QT_H
-#define XMLUTILS_QT_H
-
-#include <QtCore/QString>
-#include <QtCore/QSharedPointer>
-
-class XQuery;
-
-QSharedPointer<XQuery> qt_createXQuery(const QString &focus, QString *errorMessage);
-
-QString qt_xsl_transform(const QString &xml, QString xsl, QString *errorMessage);
-
-#endif // XMLUTILS_QT_H
diff --git a/sources/shiboken2/CMakeLists.txt b/sources/shiboken2/CMakeLists.txt
deleted file mode 100644
index 5877971a9..000000000
--- a/sources/shiboken2/CMakeLists.txt
+++ /dev/null
@@ -1,229 +0,0 @@
-Include(icecc.cmake)
-
-cmake_minimum_required(VERSION 3.1)
-cmake_policy(VERSION 3.1)
-
-set(CMAKE_BUILD_TYPE Release CACHE STRING "Build Type")
-
-project(shiboken2)
-include(CheckIncludeFileCXX)
-
-list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../cmake_helpers/")
-list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/data/")
-
-include(helpers)
-include(shiboken_helpers)
-
-option(BUILD_TESTS "Build tests." TRUE)
-option(USE_PYTHON_VERSION "Use specific python version to build shiboken2." "")
-option(DISABLE_DOCSTRINGS "Disable documentation extraction." FALSE)
-
-set (QT_MAJOR_VERSION 5)
-message(STATUS "Using Qt ${QT_MAJOR_VERSION}")
-find_package(Qt${QT_MAJOR_VERSION} 5.12 REQUIRED COMPONENTS Core)
-
-if (QUIET_BUILD)
- set_quiet_build()
-endif()
-
-if (USE_PYTHON_VERSION)
- shiboken_find_required_python(${USE_PYTHON_VERSION})
-else()
- shiboken_find_required_python()
-endif()
-
-if (NOT PYTHON_ARCH)
- get_python_arch()
-endif()
-
-setup_clang()
-
-set(SHIBOKEN_VERSION_FILE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/shiboken_version.py")
-set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
- ${SHIBOKEN_VERSION_FILE_PATH}
-)
-execute_process(
- COMMAND ${PYTHON_EXECUTABLE} "${SHIBOKEN_VERSION_FILE_PATH}"
- OUTPUT_VARIABLE SHIBOKEN_VERSION_OUTPUT
- ERROR_VARIABLE SHIBOKEN_VERSION_OUTPUT_ERROR
- OUTPUT_STRIP_TRAILING_WHITESPACE)
-if (NOT SHIBOKEN_VERSION_OUTPUT)
- message(FATAL_ERROR "Could not identify shiboken version. \
- Error: ${SHIBOKEN_VERSION_OUTPUT_ERROR}")
-endif()
-
-list(GET SHIBOKEN_VERSION_OUTPUT 0 shiboken_MAJOR_VERSION)
-list(GET SHIBOKEN_VERSION_OUTPUT 1 shiboken_MINOR_VERSION)
-list(GET SHIBOKEN_VERSION_OUTPUT 2 shiboken_MICRO_VERSION)
-# a - alpha, b - beta, rc - rc
-list(GET SHIBOKEN_VERSION_OUTPUT 3 shiboken_PRE_RELEASE_VERSION_TYPE)
-# the number of the pre release (alpha1, beta3, rc7, etc.)
-list(GET SHIBOKEN_VERSION_OUTPUT 4 shiboken_PRE_RELEASE_VERSION)
-
-set(shiboken2_VERSION "${shiboken_MAJOR_VERSION}.${shiboken_MINOR_VERSION}.${shiboken_MICRO_VERSION}")
-set(shiboken2_library_so_version "${shiboken_MAJOR_VERSION}.${shiboken_MINOR_VERSION}")
-
-compute_config_py_values(shiboken2_VERSION)
-
-## For debugging the PYTHON* variables
-message("PYTHONLIBS_FOUND: " ${PYTHONLIBS_FOUND})
-message("PYTHON_LIBRARIES: " ${PYTHON_LIBRARIES})
-message("PYTHON_INCLUDE_DIRS: " ${PYTHON_INCLUDE_DIRS})
-message("PYTHON_DEBUG_LIBRARIES: " ${PYTHON_DEBUG_LIBRARIES})
-message("PYTHONINTERP_FOUND: " ${PYTHONINTERP_FOUND})
-message("PYTHON_EXECUTABLE: " ${PYTHON_EXECUTABLE})
-message("PYTHON_VERSION: " ${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}.${PYTHON_VERSION_PATCH})
-
-if (NOT PYTHON_EXTENSION_SUFFIX)
- get_python_extension_suffix()
-endif()
-
-option(FORCE_LIMITED_API "Enable the limited API." "yes")
-set(PYTHON_LIMITED_API 0)
-
-shiboken_check_if_limited_api()
-
-if (PYTHON_LIMITED_API)
- set_limited_api()
-endif()
-
-if (NOT PYTHON_CONFIG_SUFFIX)
- set_python_config_suffix()
-endif()
-
-if (NOT PYTHON_SHARED_LIBRARY_SUFFIX)
- set_python_shared_library_suffix()
-endif()
-
-if (NOT PYTHON_CONFIG_SUFFIX)
- message(FATAL_ERROR
- "PYTHON_CONFIG_SUFFIX is empty. It should never be empty. Please file a bug report.")
-endif()
-
-message(STATUS "PYTHON_EXTENSION_SUFFIX: ${PYTHON_EXTENSION_SUFFIX}")
-message(STATUS "PYTHON_CONFIG_SUFFIX: ${PYTHON_CONFIG_SUFFIX}")
-message(STATUS "PYTHON_SHARED_LIBRARY_SUFFIX: ${PYTHON_SHARED_LIBRARY_SUFFIX}")
-
-
-if (NOT PYTHON_SITE_PACKAGES)
- set_python_site_packages()
-endif()
-
-set_cmake_cxx_flags()
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D QT_NO_CAST_FROM_ASCII -D QT_NO_CAST_TO_ASCII")
-
-# Force usage of the C++11 standard, without a silent fallback
-# to C++98 if the compiler does not support C++11.
-if(${QT_MAJOR_VERSION} GREATER_EQUAL 6)
- set(CMAKE_CXX_STANDARD 17)
-else()
- set(CMAKE_CXX_STANDARD 11)
-endif()
-set(CMAKE_CXX_STANDARD_REQUIRED ON)
-
-set(LIB_SUFFIX "" CACHE STRING "Define suffix of directory name (32/64)" )
-set(LIB_INSTALL_DIR "lib${LIB_SUFFIX}" CACHE PATH "The subdirectory relative to the install \
- prefix where libraries will be installed (default is /lib${LIB_SUFFIX})" FORCE)
-set(BIN_INSTALL_DIR "bin" CACHE PATH "The subdirectory relative to the install prefix where \
- dlls will be installed (default is /bin)" FORCE)
-
-if (WIN32)
- set(PATH_SEP "\;")
-else()
- set(PATH_SEP ":")
-endif()
-
-if(CMAKE_HOST_APPLE)
- set(OSX_USE_LIBCPP "OFF" CACHE BOOL "Explicitly link the libc++ standard library \
- (useful for osx deployment targets lower than 10.9.")
- if(OSX_USE_LIBCPP)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
- endif()
-endif()
-
-# Build with Address sanitizer enabled if requested.
-# This may break things, so use at your own risk.
-if (SANITIZE_ADDRESS AND NOT MSVC)
- set_sanitize_address()
-endif()
-
-# Detect if the python libs were compiled in debug mode
-# On Linux distros there is no standard way to check that.
-execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "if True:
- is_py_debug = False
- import sys
- try:
- sys_py_debug = sys.pydebug
- if sys_py_debug:
- is_py_debug = True
- except:
- pass
-
- try:
- from distutils import sysconfig
- config_py_debug = sysconfig.get_config_var('Py_DEBUG')
- if config_py_debug:
- is_py_debug = True
- except:
- pass
-
- print(bool(is_py_debug))
- "
- OUTPUT_VARIABLE PYTHON_WITH_DEBUG
- OUTPUT_STRIP_TRAILING_WHITESPACE)
-
-# Detect if python interpeter was compiled with COUNT_ALLOCS define
-# Linux distros are inconsistent in setting the sysconfig.get_config_var('COUNT_ALLOCS') value
-execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "if True:
- count_allocs = False
- import sys
- try:
- if sys.getcounts:
- count_allocs = True
- except:
- pass
-
- print(bool(count_allocs))
- "
- OUTPUT_VARIABLE PYTHON_WITH_COUNT_ALLOCS
- OUTPUT_STRIP_TRAILING_WHITESPACE)
-
-set(SHIBOKEN_BUILD_TYPE "${CMAKE_BUILD_TYPE}")
-
-if(CMAKE_BUILD_TYPE STREQUAL "Debug")
- set_debug_build()
-endif()
-
-######################################################################
-# Adding sub directories to build
-######################################################################
-add_subdirectory(ApiExtractor)
-
-set(generator_plugin_DIR ${LIB_INSTALL_DIR}/generatorrunner${generator_SUFFIX})
-
-# uninstall target
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake"
- "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
- IMMEDIATE @ONLY)
-add_custom_target(uninstall "${CMAKE_COMMAND}"
- -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake")
-
-add_subdirectory(libshiboken)
-add_subdirectory(doc)
-
-# deps found, compile the generator.
-if (Qt${QT_MAJOR_VERSION}Core_FOUND AND PYTHONINTERP_FOUND)
- add_subdirectory(generator)
- add_subdirectory(shibokenmodule)
-
- if (BUILD_TESTS)
- enable_testing()
- add_subdirectory(tests)
- endif()
-else()
- message(WARNING "Some dependencies were not found: shiboken2 generator compilation disabled!")
-endif()
-
-add_subdirectory(data)
diff --git a/sources/shiboken2/COPYING b/sources/shiboken2/COPYING
deleted file mode 100644
index 4ccd71466..000000000
--- a/sources/shiboken2/COPYING
+++ /dev/null
@@ -1,342 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- <signature of Ty Coon>, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Library General
-Public License instead of this License.
-
--------------------------------------------------------------------------
diff --git a/sources/shiboken2/COPYING.libsample b/sources/shiboken2/COPYING.libsample
deleted file mode 100644
index 9315102f7..000000000
--- a/sources/shiboken2/COPYING.libsample
+++ /dev/null
@@ -1,501 +0,0 @@
-GNU LESSER GENERAL PUBLIC LICENSE
- Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL. It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
- This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it. You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
- When we speak of free software, we are referring to freedom of use,
-not price. Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
- To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights. These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
- For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you. You must make sure that they, too, receive or can get the source
-code. If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it. And you must show them these terms so they know their rights.
-
- We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
- To protect each distributor, we want to make it very clear that
-there is no warranty for the free library. Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
- Finally, software patents pose a constant threat to the existence of
-any free program. We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder. Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
- Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License. This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License. We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
- When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library. The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom. The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
- We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License. It also provides other free software developers Less
-of an advantage over competing non-free programs. These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries. However, the Lesser license provides advantages in certain
-special circumstances.
-
- For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard. To achieve this, non-free programs must be
-allowed to use the library. A more frequent case is that a free
-library does the same job as widely used non-free libraries. In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
- In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software. For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
- Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
- The precise terms and conditions for copying, distribution and
-modification follow. Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library". The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
- GNU LESSER GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
- A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
- The "Library", below, refers to any such software library or work
-which has been distributed under these terms. A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language. (Hereinafter, translation is
-included without limitation in the term "modification".)
-
- "Source code" for a work means the preferred form of the work for
-making modifications to it. For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it). Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
- 1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
- You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
- 2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
-
- b) You must cause the files modified to carry prominent notices
- stating that you changed the files and the date of any change.
-
- c) You must cause the whole of the work to be licensed at no
- charge to all third parties under the terms of this License.
-
- d) If a facility in the modified Library refers to a function or a
- table of data to be supplied by an application program that uses
- the facility, other than as an argument passed when the facility
- is invoked, then you must make a good faith effort to ensure that,
- in the event an application does not supply such function or
- table, the facility still operates, and performs whatever part of
- its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has
- a purpose that is entirely well-defined independent of the
- application. Therefore, Subsection 2d requires that any
- application-supplied function or table used by this function must
- be optional: if the application does not supply it, the square
- root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library. To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License. (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.) Do not make any other change in
-these notices.
-
- Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
- This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
- 4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
- If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library". Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
- However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library". The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
- When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library. The
-threshold for this to be true is not precisely defined by law.
-
- If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work. (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
- Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
- 6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
- You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License. You must supply a copy of this License. If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License. Also, you must do one
-of these things:
-
- a) Accompany the work with the complete corresponding
- machine-readable source code for the Library including whatever
- changes were used in the work (which must be distributed under
- Sections 1 and 2 above); and, if the work is an executable linked
- with the Library, with the complete machine-readable "work that
- uses the Library", as object code and/or source code, so that the
- user can modify the Library and then relink to produce a modified
- executable containing the modified Library. (It is understood
- that the user who changes the contents of definitions files in the
- Library will not necessarily be able to recompile the application
- to use the modified definitions.)
-
- b) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (1) uses at run time a
- copy of the library already present on the user's computer system,
- rather than copying library functions into the executable, and (2)
- will operate properly with a modified version of the library, if
- the user installs one, as long as the modified version is
- interface-compatible with the version that the work was made with.
-
- c) Accompany the work with a written offer, valid for at
- least three years, to give the same user the materials
- specified in Subsection 6a, above, for a charge no more
- than the cost of performing this distribution.
-
- d) If distribution of the work is made by offering access to copy
- from a designated place, offer equivalent access to copy the above
- specified materials from the same place.
-
- e) Verify that the user has already received a copy of these
- materials or that you have already sent this user a copy.
-
- For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it. However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
- It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system. Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
- 7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work
- based on the Library, uncombined with any other library
- facilities. This must be distributed under the terms of the
- Sections above.
-
- b) Give prominent notice with the combined library of the fact
- that part of it is a work based on the Library, and explaining
- where to find the accompanying uncombined form of the same work.
-
- 8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License. Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License. However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
- 9. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Library or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
- 10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
- 11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all. For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded. In such case, this License incorporates the limitation as if
-written in the body of this License.
-
- 13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
- 14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission. For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this. Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
- NO WARRANTY
-
- 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Libraries
-
- If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change. You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
- To apply these terms, attach the following notices to the library. It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
- <one line to give the library's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
- library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
- <signature of Ty Coon>, 1 April 1990
- Ty Coon, President of Vice
-
diff --git a/sources/shiboken2/COPYING.libshiboken b/sources/shiboken2/COPYING.libshiboken
deleted file mode 100644
index 9315102f7..000000000
--- a/sources/shiboken2/COPYING.libshiboken
+++ /dev/null
@@ -1,501 +0,0 @@
-GNU LESSER GENERAL PUBLIC LICENSE
- Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL. It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
- This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it. You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
- When we speak of free software, we are referring to freedom of use,
-not price. Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
- To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights. These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
- For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you. You must make sure that they, too, receive or can get the source
-code. If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it. And you must show them these terms so they know their rights.
-
- We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
- To protect each distributor, we want to make it very clear that
-there is no warranty for the free library. Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
- Finally, software patents pose a constant threat to the existence of
-any free program. We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder. Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
- Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License. This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License. We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
- When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library. The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom. The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
- We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License. It also provides other free software developers Less
-of an advantage over competing non-free programs. These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries. However, the Lesser license provides advantages in certain
-special circumstances.
-
- For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard. To achieve this, non-free programs must be
-allowed to use the library. A more frequent case is that a free
-library does the same job as widely used non-free libraries. In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
- In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software. For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
- Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
- The precise terms and conditions for copying, distribution and
-modification follow. Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library". The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
- GNU LESSER GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
- A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
- The "Library", below, refers to any such software library or work
-which has been distributed under these terms. A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language. (Hereinafter, translation is
-included without limitation in the term "modification".)
-
- "Source code" for a work means the preferred form of the work for
-making modifications to it. For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it). Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
- 1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
- You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
- 2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
-
- b) You must cause the files modified to carry prominent notices
- stating that you changed the files and the date of any change.
-
- c) You must cause the whole of the work to be licensed at no
- charge to all third parties under the terms of this License.
-
- d) If a facility in the modified Library refers to a function or a
- table of data to be supplied by an application program that uses
- the facility, other than as an argument passed when the facility
- is invoked, then you must make a good faith effort to ensure that,
- in the event an application does not supply such function or
- table, the facility still operates, and performs whatever part of
- its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has
- a purpose that is entirely well-defined independent of the
- application. Therefore, Subsection 2d requires that any
- application-supplied function or table used by this function must
- be optional: if the application does not supply it, the square
- root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library. To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License. (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.) Do not make any other change in
-these notices.
-
- Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
- This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
- 4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
- If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library". Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
- However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library". The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
- When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library. The
-threshold for this to be true is not precisely defined by law.
-
- If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work. (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
- Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
- 6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
- You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License. You must supply a copy of this License. If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License. Also, you must do one
-of these things:
-
- a) Accompany the work with the complete corresponding
- machine-readable source code for the Library including whatever
- changes were used in the work (which must be distributed under
- Sections 1 and 2 above); and, if the work is an executable linked
- with the Library, with the complete machine-readable "work that
- uses the Library", as object code and/or source code, so that the
- user can modify the Library and then relink to produce a modified
- executable containing the modified Library. (It is understood
- that the user who changes the contents of definitions files in the
- Library will not necessarily be able to recompile the application
- to use the modified definitions.)
-
- b) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (1) uses at run time a
- copy of the library already present on the user's computer system,
- rather than copying library functions into the executable, and (2)
- will operate properly with a modified version of the library, if
- the user installs one, as long as the modified version is
- interface-compatible with the version that the work was made with.
-
- c) Accompany the work with a written offer, valid for at
- least three years, to give the same user the materials
- specified in Subsection 6a, above, for a charge no more
- than the cost of performing this distribution.
-
- d) If distribution of the work is made by offering access to copy
- from a designated place, offer equivalent access to copy the above
- specified materials from the same place.
-
- e) Verify that the user has already received a copy of these
- materials or that you have already sent this user a copy.
-
- For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it. However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
- It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system. Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
- 7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work
- based on the Library, uncombined with any other library
- facilities. This must be distributed under the terms of the
- Sections above.
-
- b) Give prominent notice with the combined library of the fact
- that part of it is a work based on the Library, and explaining
- where to find the accompanying uncombined form of the same work.
-
- 8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License. Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License. However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
- 9. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Library or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
- 10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
- 11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all. For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded. In such case, this License incorporates the limitation as if
-written in the body of this License.
-
- 13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
- 14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission. For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this. Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
- NO WARRANTY
-
- 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Libraries
-
- If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change. You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
- To apply these terms, attach the following notices to the library. It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
- <one line to give the library's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
- library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
- <signature of Ty Coon>, 1 April 1990
- Ty Coon, President of Vice
-
diff --git a/sources/shiboken2/Doxyfile b/sources/shiboken2/Doxyfile
deleted file mode 100644
index 9be56a0e4..000000000
--- a/sources/shiboken2/Doxyfile
+++ /dev/null
@@ -1,311 +0,0 @@
-# Doxyfile 1.5.7.1
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-DOXYFILE_ENCODING = UTF-8
-PROJECT_NAME = "Generator Runner"
-PROJECT_NUMBER = 0.1
-OUTPUT_DIRECTORY = doc
-CREATE_SUBDIRS = NO
-OUTPUT_LANGUAGE = English
-BRIEF_MEMBER_DESC = YES
-REPEAT_BRIEF = YES
-ABBREVIATE_BRIEF = "The $name class" \
- "The $name widget" \
- "The $name file" \
- is \
- provides \
- specifies \
- contains \
- represents \
- a \
- an \
- the
-ALWAYS_DETAILED_SEC = NO
-INLINE_INHERITED_MEMB = NO
-FULL_PATH_NAMES = YES
-STRIP_FROM_PATH = /tmp/src/generatorrunner/
-STRIP_FROM_INC_PATH =
-SHORT_NAMES = NO
-JAVADOC_AUTOBRIEF = YES
-QT_AUTOBRIEF = NO
-MULTILINE_CPP_IS_BRIEF = NO
-INHERIT_DOCS = YES
-SEPARATE_MEMBER_PAGES = NO
-TAB_SIZE = 8
-ALIASES =
-OPTIMIZE_OUTPUT_FOR_C = NO
-OPTIMIZE_OUTPUT_JAVA = NO
-OPTIMIZE_FOR_FORTRAN = NO
-OPTIMIZE_OUTPUT_VHDL = NO
-BUILTIN_STL_SUPPORT = NO
-CPP_CLI_SUPPORT = NO
-SIP_SUPPORT = NO
-IDL_PROPERTY_SUPPORT = YES
-DISTRIBUTE_GROUP_DOC = NO
-SUBGROUPING = YES
-TYPEDEF_HIDES_STRUCT = NO
-SYMBOL_CACHE_SIZE = 0
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-EXTRACT_ALL = YES
-EXTRACT_PRIVATE = YES
-EXTRACT_STATIC = YES
-EXTRACT_LOCAL_CLASSES = YES
-EXTRACT_LOCAL_METHODS = NO
-EXTRACT_ANON_NSPACES = NO
-HIDE_UNDOC_MEMBERS = NO
-HIDE_UNDOC_CLASSES = NO
-HIDE_FRIEND_COMPOUNDS = NO
-HIDE_IN_BODY_DOCS = NO
-INTERNAL_DOCS = NO
-CASE_SENSE_NAMES = YES
-HIDE_SCOPE_NAMES = NO
-SHOW_INCLUDE_FILES = YES
-INLINE_INFO = YES
-SORT_MEMBER_DOCS = YES
-SORT_BRIEF_DOCS = NO
-SORT_GROUP_NAMES = NO
-SORT_BY_SCOPE_NAME = NO
-GENERATE_TODOLIST = YES
-GENERATE_TESTLIST = YES
-GENERATE_BUGLIST = YES
-GENERATE_DEPRECATEDLIST= YES
-ENABLED_SECTIONS =
-MAX_INITIALIZER_LINES = 30
-SHOW_USED_FILES = YES
-SHOW_DIRECTORIES = NO
-SHOW_FILES = YES
-SHOW_NAMESPACES = YES
-FILE_VERSION_FILTER =
-LAYOUT_FILE =
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-QUIET = NO
-WARNINGS = YES
-WARN_IF_UNDOCUMENTED = YES
-WARN_IF_DOC_ERROR = YES
-WARN_NO_PARAMDOC = NO
-WARN_FORMAT = "$file:$line: $text"
-WARN_LOGFILE =
-#---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-INPUT = /tmp/src/generatorrunner
-INPUT_ENCODING = UTF-8
-FILE_PATTERNS = *.c \
- *.cc \
- *.cxx \
- *.cpp \
- *.c++ \
- *.d \
- *.java \
- *.ii \
- *.ixx \
- *.ipp \
- *.i++ \
- *.inl \
- *.h \
- *.hh \
- *.hxx \
- *.hpp \
- *.h++ \
- *.idl \
- *.odl \
- *.cs \
- *.php \
- *.php3 \
- *.inc \
- *.m \
- *.mm \
- *.dox \
- *.py \
- *.f90 \
- *.f \
- *.vhd \
- *.vhdl \
- *.C \
- *.CC \
- *.C++ \
- *.II \
- *.I++ \
- *.H \
- *.HH \
- *.H++ \
- *.CS \
- *.PHP \
- *.PHP3 \
- *.M \
- *.MM \
- *.PY \
- *.F90 \
- *.F \
- *.VHD \
- *.VHDL
-RECURSIVE = YES
-EXCLUDE =
-EXCLUDE_SYMLINKS = NO
-EXCLUDE_PATTERNS =
-EXCLUDE_SYMBOLS =
-EXAMPLE_PATH =
-EXAMPLE_PATTERNS = *
-EXAMPLE_RECURSIVE = NO
-IMAGE_PATH =
-INPUT_FILTER =
-FILTER_PATTERNS =
-FILTER_SOURCE_FILES = NO
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-SOURCE_BROWSER = NO
-INLINE_SOURCES = NO
-STRIP_CODE_COMMENTS = YES
-REFERENCED_BY_RELATION = NO
-REFERENCES_RELATION = NO
-REFERENCES_LINK_SOURCE = YES
-USE_HTAGS = NO
-VERBATIM_HEADERS = NO
-#---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-ALPHABETICAL_INDEX = YES
-COLS_IN_ALPHA_INDEX = 3
-IGNORE_PREFIX =
-#---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-GENERATE_HTML = YES
-HTML_OUTPUT = html
-HTML_FILE_EXTENSION = .html
-HTML_HEADER =
-HTML_FOOTER =
-HTML_STYLESHEET =
-HTML_ALIGN_MEMBERS = YES
-HTML_DYNAMIC_SECTIONS = NO
-GENERATE_DOCSET = NO
-DOCSET_FEEDNAME = "Doxygen generated docs"
-DOCSET_BUNDLE_ID = org.doxygen.Project
-GENERATE_HTMLHELP = NO
-CHM_FILE =
-HHC_LOCATION =
-GENERATE_CHI = NO
-CHM_INDEX_ENCODING =
-BINARY_TOC = NO
-TOC_EXPAND = NO
-GENERATE_QHP = NO
-QCH_FILE =
-QHP_NAMESPACE = org.doxygen.Project
-QHP_VIRTUAL_FOLDER = doc
-QHG_LOCATION =
-DISABLE_INDEX = NO
-ENUM_VALUES_PER_LINE = 4
-GENERATE_TREEVIEW = NONE
-TREEVIEW_WIDTH = 250
-FORMULA_FONTSIZE = 10
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-GENERATE_LATEX = NO
-LATEX_OUTPUT = latex
-LATEX_CMD_NAME = latex
-MAKEINDEX_CMD_NAME = makeindex
-COMPACT_LATEX = NO
-PAPER_TYPE = a4wide
-EXTRA_PACKAGES =
-LATEX_HEADER =
-PDF_HYPERLINKS = YES
-USE_PDFLATEX = YES
-LATEX_BATCHMODE = NO
-LATEX_HIDE_INDICES = NO
-#---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-GENERATE_RTF = NO
-RTF_OUTPUT = rtf
-COMPACT_RTF = NO
-RTF_HYPERLINKS = NO
-RTF_STYLESHEET_FILE =
-RTF_EXTENSIONS_FILE =
-#---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-GENERATE_MAN = NO
-MAN_OUTPUT = man
-MAN_EXTENSION = .3
-MAN_LINKS = NO
-#---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-GENERATE_XML = NO
-XML_OUTPUT = xml
-XML_SCHEMA =
-XML_DTD =
-XML_PROGRAMLISTING = YES
-#---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-GENERATE_AUTOGEN_DEF = NO
-#---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-GENERATE_PERLMOD = NO
-PERLMOD_LATEX = NO
-PERLMOD_PRETTY = YES
-PERLMOD_MAKEVAR_PREFIX =
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-ENABLE_PREPROCESSING = YES
-MACRO_EXPANSION = NO
-EXPAND_ONLY_PREDEF = NO
-SEARCH_INCLUDES = YES
-INCLUDE_PATH =
-INCLUDE_FILE_PATTERNS =
-PREDEFINED =
-EXPAND_AS_DEFINED =
-SKIP_FUNCTION_MACROS = YES
-#---------------------------------------------------------------------------
-# Configuration::additions related to external references
-#---------------------------------------------------------------------------
-TAGFILES = ../libgenrunner/libgenrunner.tag=../libgenrunner
-GENERATE_TAGFILE = generatorrunner.tag
-ALLEXTERNALS = NO
-EXTERNAL_GROUPS = YES
-PERL_PATH = /usr/bin/perl
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-CLASS_DIAGRAMS = YES
-MSCGEN_PATH =
-HIDE_UNDOC_RELATIONS = YES
-HAVE_DOT = YES
-DOT_FONTNAME = FreeSans
-DOT_FONTSIZE = 10
-DOT_FONTPATH =
-CLASS_GRAPH = YES
-COLLABORATION_GRAPH = YES
-GROUP_GRAPHS = NO
-UML_LOOK = NO
-TEMPLATE_RELATIONS = NO
-INCLUDE_GRAPH = NO
-INCLUDED_BY_GRAPH = NO
-CALL_GRAPH = NO
-CALLER_GRAPH = NO
-GRAPHICAL_HIERARCHY = YES
-DIRECTORY_GRAPH = NO
-DOT_IMAGE_FORMAT = png
-DOT_PATH =
-DOTFILE_DIRS =
-DOT_GRAPH_MAX_NODES = 50
-MAX_DOT_GRAPH_DEPTH = 1000
-DOT_TRANSPARENT = NO
-DOT_MULTI_TARGETS = NO
-GENERATE_LEGEND = YES
-DOT_CLEANUP = YES
-#---------------------------------------------------------------------------
-# Configuration::additions related to the search engine
-#---------------------------------------------------------------------------
-SEARCHENGINE = NO
diff --git a/sources/shiboken2/cmake_uninstall.cmake b/sources/shiboken2/cmake_uninstall.cmake
deleted file mode 100644
index df95fb9d8..000000000
--- a/sources/shiboken2/cmake_uninstall.cmake
+++ /dev/null
@@ -1,21 +0,0 @@
-IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
- MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"")
-ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
-
-FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
-STRING(REGEX REPLACE "\n" ";" files "${files}")
-FOREACH(file ${files})
- MESSAGE(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"")
- IF(EXISTS "$ENV{DESTDIR}${file}")
- EXEC_PROGRAM(
- "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
- OUTPUT_VARIABLE rm_out
- RETURN_VALUE rm_retval
- )
- IF(NOT "${rm_retval}" STREQUAL 0)
- MESSAGE(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"")
- ENDIF(NOT "${rm_retval}" STREQUAL 0)
- ELSE(EXISTS "$ENV{DESTDIR}${file}")
- MESSAGE(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.")
- ENDIF(EXISTS "$ENV{DESTDIR}${file}")
-ENDFOREACH(file)
diff --git a/sources/shiboken2/data/CMakeLists.txt b/sources/shiboken2/data/CMakeLists.txt
deleted file mode 100644
index e7ce95456..000000000
--- a/sources/shiboken2/data/CMakeLists.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-if (CMAKE_BUILD_TYPE STREQUAL "Debug")
- set(LIBRARY_OUTPUT_SUFFIX ${CMAKE_DEBUG_POSTFIX})
-else()
- set(LIBRARY_OUTPUT_SUFFIX ${CMAKE_RELEASE_POSTFIX})
-endif()
-
-add_custom_target(data)
-add_dependencies(data shiboken2)
-get_target_property(SHIBOKEN_GENERATOR shiboken2 OUTPUT_NAME)
-
-include(CMakePackageConfigHelpers)
-
-# Build-tree / super project package config file.
-set(SHIBOKEN_PYTHON_MODULE_DIR "${shiboken2_BINARY_DIR}/shibokenmodule")
-set(SHIBOKEN_SHARED_LIBRARY_DIR "${shiboken2_BINARY_DIR}/libshiboken")
-
-configure_package_config_file(
- "${CMAKE_CURRENT_SOURCE_DIR}/Shiboken2Config-spec.cmake.in"
- "${CMAKE_CURRENT_BINARY_DIR}/Shiboken2Config${PYTHON_CONFIG_SUFFIX}.cmake"
- INSTALL_DESTINATION "${CMAKE_CURRENT_BINARY_DIR}"
- PATH_VARS SHIBOKEN_PYTHON_MODULE_DIR SHIBOKEN_SHARED_LIBRARY_DIR
- INSTALL_PREFIX "${CMAKE_CURRENT_BINARY_DIR}"
-)
-
-# Install-tree / relocatable package config file.
-set(SHIBOKEN_PYTHON_MODULE_DIR "${PYTHON_SITE_PACKAGES}/shiboken2")
-if (WIN32)
- set(SHIBOKEN_SHARED_LIBRARY_DIR "${BIN_INSTALL_DIR}")
-else()
- set(SHIBOKEN_SHARED_LIBRARY_DIR "${LIB_INSTALL_DIR}")
-endif()
-
-configure_package_config_file(
- "${CMAKE_CURRENT_SOURCE_DIR}/Shiboken2Config-spec.cmake.in"
- "${CMAKE_CURRENT_BINARY_DIR}/install/Shiboken2Config${PYTHON_CONFIG_SUFFIX}.cmake"
- INSTALL_DESTINATION "${LIB_INSTALL_DIR}/cmake/Shiboken2-${shiboken2_VERSION}"
- PATH_VARS SHIBOKEN_PYTHON_MODULE_DIR SHIBOKEN_SHARED_LIBRARY_DIR
-)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/Shiboken2Config.cmake.in"
- "${CMAKE_CURRENT_BINARY_DIR}/Shiboken2Config.cmake" @ONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/Shiboken2ConfigVersion.cmake.in"
- "${CMAKE_CURRENT_BINARY_DIR}/Shiboken2ConfigVersion.cmake" @ONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/shiboken2.pc.in"
- "${CMAKE_CURRENT_BINARY_DIR}/shiboken2${shiboken2_SUFFIX}.pc" @ONLY)
-
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/Shiboken2Config.cmake"
- DESTINATION "${LIB_INSTALL_DIR}/cmake/Shiboken2-${shiboken2_VERSION}")
-
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/Shiboken2Config${PYTHON_CONFIG_SUFFIX}.cmake"
- DESTINATION "${LIB_INSTALL_DIR}/cmake/Shiboken2-${shiboken2_VERSION}")
-
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/Shiboken2ConfigVersion.cmake"
- DESTINATION "${LIB_INSTALL_DIR}/cmake/Shiboken2-${shiboken2_VERSION}")
-
-install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/shiboken_helpers.cmake"
- DESTINATION "${LIB_INSTALL_DIR}/cmake/Shiboken2-${shiboken2_VERSION}")
-
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/shiboken2${shiboken2_SUFFIX}.pc"
- DESTINATION "${LIB_INSTALL_DIR}/pkgconfig")
-
diff --git a/sources/shiboken2/data/GeneratorRunnerConfig.cmake.in b/sources/shiboken2/data/GeneratorRunnerConfig.cmake.in
deleted file mode 100644
index cf973e2a6..000000000
--- a/sources/shiboken2/data/GeneratorRunnerConfig.cmake.in
+++ /dev/null
@@ -1,17 +0,0 @@
-# GENERATORRUNNER_INCLUDE_DIR - Directories to include to use GENERATORRUNNER
-# GENERATORRUNNER_LIBRARIES - Files to link against to use GENERATORRUNNER
-# GENERATORRUNNER_PLUGIN_DIR - Where to find/put plugins for generator runner
-# GENERATORRUNNER_BINARY - Executable name
-
-SET(GENERATORRUNNER_INCLUDE_DIR "@CMAKE_INSTALL_PREFIX@/include/generatorrunner@generator_SUFFIX@")
-if(MSVC)
- SET(GENERATORRUNNER_LIBRARY "@LIB_INSTALL_DIR@/@CMAKE_SHARED_LIBRARY_PREFIX@genrunner@generator_SUFFIX@.lib")
-elseif(CYGWIN)
- SET(GENERATORRUNNER_LIBRARY "@LIB_INSTALL_DIR@/@CMAKE_IMPORT_LIBRARY_PREFIX@genrunner@generator_SUFFIX@@CMAKE_IMPORT_LIBRARY_SUFFIX@")
-elseif(WIN32)
- SET(GENERATORRUNNER_LIBRARY "@CMAKE_INSTALL_PREFIX@/bin/@CMAKE_SHARED_LIBRARY_PREFIX@genrunner@generator_SUFFIX@@CMAKE_SHARED_LIBRARY_SUFFIX@")
-else()
- SET(GENERATORRUNNER_LIBRARY "@LIB_INSTALL_DIR@/@CMAKE_SHARED_LIBRARY_PREFIX@genrunner@generator_SUFFIX@@CMAKE_SHARED_LIBRARY_SUFFIX@")
-endif()
-SET(GENERATORRUNNER_PLUGIN_DIR "@generator_plugin_DIR@")
-SET(GENERATORRUNNER_BINARY "@CMAKE_INSTALL_PREFIX@/bin/generatorrunner@generator_SUFFIX@")
diff --git a/sources/shiboken2/data/GeneratorRunnerConfigVersion.cmake.in b/sources/shiboken2/data/GeneratorRunnerConfigVersion.cmake.in
deleted file mode 100644
index 8eb5ba479..000000000
--- a/sources/shiboken2/data/GeneratorRunnerConfigVersion.cmake.in
+++ /dev/null
@@ -1,10 +0,0 @@
-set(PACKAGE_VERSION @generator_VERSION@)
-
-if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
- set(PACKAGE_VERSION_COMPATIBLE FALSE)
-else("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
- set(PACKAGE_VERSION_COMPATIBLE TRUE)
- if( "${PACKAGE_FIND_VERSION}" STREQUAL "${PACKAGE_VERSION}")
- set(PACKAGE_VERSION_EXACT TRUE)
- endif( "${PACKAGE_FIND_VERSION}" STREQUAL "${PACKAGE_VERSION}")
-endif("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
diff --git a/sources/shiboken2/data/Shiboken2Config-spec.cmake.in b/sources/shiboken2/data/Shiboken2Config-spec.cmake.in
deleted file mode 100644
index db8373806..000000000
--- a/sources/shiboken2/data/Shiboken2Config-spec.cmake.in
+++ /dev/null
@@ -1,41 +0,0 @@
-# SHIBOKEN_BUILD_TYPE - Tells if Shiboken was compiled in Release or Debug mode.
-# SHIBOKEN_PYTHON_INTERPRETER - Python interpreter (regular or debug) to be used with the bindings.
-
-@PACKAGE_INIT@
-
-# This is the version of Python against which Shiboken was built. Not necessarily the version
-# against which a downstream project is built (e.g. PySide2).
-set(SHIBOKEN_PYTHON_VERSION_MAJOR "@PYTHON_VERSION_MAJOR@")
-set(SHIBOKEN_PYTHON_VERSION_MINOR "@PYTHON_VERSION_MINOR@")
-set(SHIBOKEN_PYTHON_VERSION_PATCH "@PYTHON_VERSION_PATCH@")
-set(SHIBOKEN_PYTHON_LIMITED_API "@PYTHON_LIMITED_API@")
-
-# Import targets and call variable set up functions only when using an installed shiboken config
-# file (so not during a regular shiboken build, or during a super project build).
-if (NOT TARGET Shiboken2::shiboken2)
- include("${CMAKE_CURRENT_LIST_DIR}/Shiboken2Targets.cmake")
- include("${CMAKE_CURRENT_LIST_DIR}/shiboken_helpers.cmake")
-
- # Compute the python include and libraries path if needed (aka not part of super project build).
- shiboken_find_required_python(@PYTHON_VERSION_MAJOR@)
- shiboken_check_if_built_and_target_python_are_compatible()
- shiboken_check_if_limited_api()
- shiboken_compute_python_includes(IS_CALLED_FROM_EXPORT)
- shiboken_compute_python_libraries(IS_CALLED_FROM_EXPORT)
-endif()
-
-# Get the "python interpreter" dynamic global property as a variable instead. It brings it into
-# scope for super project builds.
-get_property(SHIBOKEN_PYTHON_INTERPRETER GLOBAL PROPERTY SHIBOKEN_PYTHON_INTERPRETER)
-
-# Set static variables.
-set(SHIBOKEN_PYTHON_EXTENSION_SUFFIX "@PYTHON_EXTENSION_SUFFIX@")
-set(SHIBOKEN_PYTHON_SHARED_LIBRARY_SUFFIX "@PYTHON_SHARED_LIBRARY_SUFFIX@")
-set(SHIBOKEN_PYTHON_CONFIG_SUFFIX "@PYTHON_CONFIG_SUFFIX@")
-set(SHIBOKEN_SO_VERSION "@shiboken2_library_so_version@")
-set(SHIBOKEN_BUILD_TYPE "@SHIBOKEN_BUILD_TYPE@")
-
-set_and_check(SHIBOKEN_PYTHON_MODULE_DIR "@PACKAGE_SHIBOKEN_PYTHON_MODULE_DIR@")
-set_and_check(SHIBOKEN_SHARED_LIBRARY_DIR "@PACKAGE_SHIBOKEN_SHARED_LIBRARY_DIR@")
-
-message(STATUS "libshiboken built for @SHIBOKEN_BUILD_TYPE@")
diff --git a/sources/shiboken2/data/Shiboken2Config.cmake.in b/sources/shiboken2/data/Shiboken2Config.cmake.in
deleted file mode 100644
index e13bd2a12..000000000
--- a/sources/shiboken2/data/Shiboken2Config.cmake.in
+++ /dev/null
@@ -1,5 +0,0 @@
-if (NOT PYTHON_CONFIG_SUFFIX)
- message(STATUS "Shiboken2Config: Using default python: @PYTHON_CONFIG_SUFFIX@")
- SET(PYTHON_CONFIG_SUFFIX @PYTHON_CONFIG_SUFFIX@)
-endif()
-include("${CMAKE_CURRENT_LIST_DIR}/Shiboken2Config${PYTHON_CONFIG_SUFFIX}.cmake")
diff --git a/sources/shiboken2/data/Shiboken2ConfigVersion.cmake.in b/sources/shiboken2/data/Shiboken2ConfigVersion.cmake.in
deleted file mode 100644
index 9460099b2..000000000
--- a/sources/shiboken2/data/Shiboken2ConfigVersion.cmake.in
+++ /dev/null
@@ -1,10 +0,0 @@
-set(PACKAGE_VERSION @shiboken2_VERSION@)
-
-if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
- set(PACKAGE_VERSION_COMPATIBLE FALSE)
-else("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
- set(PACKAGE_VERSION_COMPATIBLE TRUE)
- if( "${PACKAGE_FIND_VERSION}" STREQUAL "${PACKAGE_VERSION}")
- set(PACKAGE_VERSION_EXACT TRUE)
- endif( "${PACKAGE_FIND_VERSION}" STREQUAL "${PACKAGE_VERSION}")
-endif("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}" )
diff --git a/sources/shiboken2/data/docgenerator.1 b/sources/shiboken2/data/docgenerator.1
deleted file mode 120000
index c65282f98..000000000
--- a/sources/shiboken2/data/docgenerator.1
+++ /dev/null
@@ -1 +0,0 @@
-generatorrunner.1 \ No newline at end of file
diff --git a/sources/shiboken2/data/generatorrunner.1 b/sources/shiboken2/data/generatorrunner.1
deleted file mode 100644
index f5a61f139..000000000
--- a/sources/shiboken2/data/generatorrunner.1
+++ /dev/null
@@ -1,76 +0,0 @@
-.TH GENERATORRUNNER 1 "SEPTEMBER 2009" Linux "User Manuals"
-.SH NAME
-generatorrunner - plugin-based binding source code generator
-.SH SYNOPSIS
-.B generatorrunner \-\-generator-set=<plugin name> [options] header-file typesystem-file
-.SH DESCRIPTION
-.B generatorrunner
-is a utility that uses the information taken from APIExtractor
-related to the provided C++ headers and typesystem files and execute
-generators using this information. Generators are plugins and you need
-to specify one using the \-\-generator-set parameter. At the moment there
-are two generators available:
-
-.B qtdoc
-\- Generates Sphinx-based documentation for C++ libraries documented using
-.B qdoc
-documentation syntax, using the XML files created by the documentation tool
-.B (qdoc).
-Can be called supplying
-.B \-\-generator-set=qtdoc
-to
-.B generatorrunner
-or by calling the convenience executable
-.B docgenerator.
-
-Other plugins can be used with
-.B generatorrunner,
-provided that they follow the generator front-end specifications,
-and can be written to generate code or documentation for any target
-languague you desire. For more information about the generator front-end
-architecture and current limitations, refer to http://www.pyside.org/home-binding.
-
-.SH OPTIONS
-.SS "General options"
-.IP \-\-api-version=<version>
-Specify the supported api version used to generate the bindings.
-.IP \-\-debug-level=[sparse|medium|full]
-The amount of messages displayed.
-.IP \-\-documentation-only
-Only generates the documentation.
-.IP \-\-drop-type-entries="<TypeEntry0>[;TypeEntry1;...]"
-Semicolon separated list of type system entries (classes, namespaces, global functions and enums) to be dropped from generation.
-.IP \-\-help \fR,\fP \-h \fR,\fP -?
-Prints the usage message.
-.IP \-\-project-file=<file>
-Text file containing a description of the binding project. Replaces and overrides command line arguments.
-.IP \-\-include\-paths=\fI<path>[:path:..]\fR
-The directories where the generator will search for the
-headers. Works like gcc's \-I flag.
-.IP \-\-license\-file=\fI[licensefile]\fR
-Template for copyright headers of generated files.
-.IP \-\-no\-supress\-warnings
-Show all warnings.
-.IP \-\-output\-directory=\fI[dir]\fR
-The directory where the generated files will be written.
-.IP \-\-silent
-Avoid printing any messages.
-.IP \-\-typesytem\-paths=\fI<path>[:path:..]\fR
-The directories where the generator will search for the
-external typesystems referred by the main one.
-.IP \-\-version
-Displays the current version.
-Drops support for named args.
-.SS "Specific to qtdoc plugin"
-.IP \-\-documentation\-code\-snippets\-dir
-Directory used to search code snippets used by the documentation
-.IP \-\-documentation\-data\-dir
-Directory with XML files generated by documentation tool (qdoc or Doxygen)
-.IP \-\-documentation\-out\-dir
-The directory where the generated documentation files will be written
-.IP \-\-library\-source\-dir
-Directory where library source code is located
-
-.SH AUTHORS
-Lauro Moura <lauro.neto at openbossa dot org>, Bruno Araujo <bruno.araujo at openbossa dot org>, Hugo Lima <hugo.lima at openbossa dot org>
-
diff --git a/sources/shiboken2/data/generatorrunner.pc.in b/sources/shiboken2/data/generatorrunner.pc.in
deleted file mode 100644
index a566f4356..000000000
--- a/sources/shiboken2/data/generatorrunner.pc.in
+++ /dev/null
@@ -1,13 +0,0 @@
-prefix=@CMAKE_INSTALL_PREFIX@
-exec_prefix=@CMAKE_INSTALL_PREFIX@
-libdir=@LIB_INSTALL_DIR@
-includedir=@CMAKE_INSTALL_PREFIX@/include
-
-
-Name: generatorrunner@generator_SUFFIX@
-Description: Generator Runner loads and calls binding generator front-ends.
-Requires: apiextractor
-Version: @generatorrunner_VERSION@
-Libs: -L${libdir} -lgenrunner@generator_SUFFIX@
-Cflags: -I${includedir}@generator_SUFFIX@
-
diff --git a/sources/shiboken2/data/shiboken2.pc.in b/sources/shiboken2/data/shiboken2.pc.in
deleted file mode 100644
index 10db59e1e..000000000
--- a/sources/shiboken2/data/shiboken2.pc.in
+++ /dev/null
@@ -1,13 +0,0 @@
-prefix=@CMAKE_INSTALL_PREFIX@
-exec_prefix=@CMAKE_INSTALL_PREFIX@
-libdir=@LIB_INSTALL_DIR@
-includedir=@CMAKE_INSTALL_PREFIX@/include/shiboken2
-generator_location=@CMAKE_INSTALL_PREFIX@/bin/@SHIBOKEN_GENERATOR@
-python_interpreter=@PYTHON_EXECUTABLE@
-python_include_dir=@PYTHON_INCLUDE_DIRS@
-
-Name: shiboken2
-Description: Support library for Python bindings created with the Shiboken2 generator.
-Version: @shiboken2_VERSION@
-Libs: @SHIBOKEN_PYTHON_LIBRARIES@ -L${libdir} -lshiboken2@shiboken2_SUFFIX@@PYTHON_SHARED_LIBRARY_SUFFIX@@LIBRARY_OUTPUT_SUFFIX@
-Cflags: -I@PYTHON_INCLUDE_DIRS@ -I${includedir}/@shiboken2_SUFFIX@@SBK_PKG_CONFIG_PY_DEBUG_DEFINITION@
diff --git a/sources/shiboken2/data/shiboken_helpers.cmake b/sources/shiboken2/data/shiboken_helpers.cmake
deleted file mode 100644
index 6bd75d0ea..000000000
--- a/sources/shiboken2/data/shiboken_helpers.cmake
+++ /dev/null
@@ -1,476 +0,0 @@
-include(CMakeParseArguments)
-
-macro(set_python_shared_library_suffix)
- set(PYTHON_SHARED_LIBRARY_SUFFIX "${PYTHON_CONFIG_SUFFIX}")
-
- # Append a "v" to disambiguate the python version and the shiboken version in the
- # shared library file name.
- if (APPLE AND PYTHON_VERSION_MAJOR EQUAL 2)
- set(PYTHON_SHARED_LIBRARY_SUFFIX "${PYTHON_SHARED_LIBRARY_SUFFIX}v")
- endif()
-endmacro()
-
-macro(set_limited_api)
- if (WIN32 AND NOT EXISTS "${PYTHON_LIMITED_LIBRARIES}")
- message(FATAL_ERROR "The Limited API was enabled, but ${PYTHON_LIMITED_LIBRARIES} was not found!")
- endif()
- message(STATUS "******************************************************")
- message(STATUS "** Limited API enabled ${PYTHON_LIMITED_LIBRARIES}")
- message(STATUS "******************************************************")
-endmacro()
-
-macro(set_debug_build)
- set(SHIBOKEN_BUILD_TYPE "Debug")
-
- if(NOT PYTHON_DEBUG_LIBRARIES)
- message(WARNING "Python debug shared library not found; \
- assuming python was built with shared library support disabled.")
- endif()
-
- if(NOT PYTHON_WITH_DEBUG)
- message(WARNING "Compiling shiboken2 with debug enabled, \
- but the python executable was not compiled with debug support.")
- else()
- set(SBK_PKG_CONFIG_PY_DEBUG_DEFINITION " -DPy_DEBUG")
- endif()
-
- if (PYTHON_WITH_COUNT_ALLOCS)
- set(SBK_PKG_CONFIG_PY_DEBUG_DEFINITION "${SBK_PKG_CONFIG_PY_DEBUG_DEFINITION} -DCOUNT_ALLOCS")
- endif()
-endmacro()
-
-macro(setup_sanitize_address)
- # Currently this does not check that the clang / gcc version used supports Address sanitizer,
- # so once again, use at your own risk.
- add_compile_options("-fsanitize=address" "-g" "-fno-omit-frame-pointer")
- # We need to add the sanitize address option to all linked executables / shared libraries
- # so that proper sanitizer symbols are linked in.
- #
- # Note that when running tests, you may need to set an additional environment variable
- # in set_tests_properties for shiboken2 / pyside tests, or exported in your shell. Address
- # sanitizer will tell you what environment variable needs to be exported. For example:
- # export DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Toolchains/
- # ./XcodeDefault.xctoolchain/usr/lib/clang/8.1.0/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
- set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_STANDARD_LIBRARIES} -fsanitize=address")
-endmacro()
-
-macro(set_cmake_cxx_flags)
-if(MSVC)
- # Qt5: this flag has changed from /Zc:wchar_t- in Qt4.X
- set(CMAKE_CXX_FLAGS "/Zc:wchar_t /GR /EHsc /DWIN32 /D_WINDOWS /D_SCL_SECURE_NO_WARNINGS")
- #set(CMAKE_CXX_FLAGS "/Zc:wchar_t /GR /EHsc /DNOCOLOR /DWIN32 /D_WINDOWS /D_SCL_SECURE_NO_WARNINGS") # XXX
-else()
- if(CMAKE_HOST_UNIX AND NOT CYGWIN)
- add_definitions(-fPIC)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -fvisibility=hidden -Wno-strict-aliasing")
- endif()
- set(CMAKE_CXX_FLAGS_DEBUG "-g")
- option(ENABLE_GCC_OPTIMIZATION "Enable specific GCC flags to optimization library \
- size and performance. Only available on Release Mode" 0)
- if(ENABLE_GCC_OPTIMIZATION)
- set(CMAKE_CXX_FLAGS_RELEASE "-DNDEBUG -Os -Wl,-O1")
- if(NOT CMAKE_HOST_APPLE)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--hash-style=gnu")
- endif()
- endif()
- if(CMAKE_HOST_APPLE)
- # ALTERNATIVE_QT_INCLUDE_DIR is deprecated, because CMake takes care of finding the proper
- # include folders using the qmake found in the environment. Only use it for now in case
- # something goes wrong with the cmake process.
- if(ALTERNATIVE_QT_INCLUDE_DIR AND NOT QT_INCLUDE_DIR)
- set(QT_INCLUDE_DIR ${ALTERNATIVE_QT_INCLUDE_DIR})
- endif()
- endif()
-endif()
-
-endmacro()
-
-macro(set_python_site_packages)
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "if True:
- from distutils import sysconfig
- from os.path import sep
- print(sysconfig.get_python_lib(1, 0, prefix='${CMAKE_INSTALL_PREFIX}').replace(sep, '/'))
- "
- OUTPUT_VARIABLE PYTHON_SITE_PACKAGES
- OUTPUT_STRIP_TRAILING_WHITESPACE)
- if (NOT PYTHON_SITE_PACKAGES)
- message(FATAL_ERROR "Could not detect Python module installation directory.")
- elseif (APPLE)
- message(STATUS "!!! The generated bindings will be installed on ${PYTHON_SITE_PACKAGES}, \
- is it right!?")
- endif()
-endmacro()
-
-macro(set_python_config_suffix)
- if (PYTHON_VERSION_MAJOR EQUAL 2)
- set(PYTHON_CONFIG_SUFFIX "-python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}")
- if (PYTHON_EXTENSION_SUFFIX)
- set(PYTHON_CONFIG_SUFFIX "${PYTHON_CONFIG_SUFFIX}${PYTHON_EXTENSION_SUFFIX}")
- endif()
- elseif (PYTHON_VERSION_MAJOR EQUAL 3)
- if (PYTHON_LIMITED_API)
- if(WIN32)
- set(PYTHON_EXTENSION_SUFFIX "")
- else()
- set(PYTHON_EXTENSION_SUFFIX ".abi3")
- endif()
- set(PYTHON_CONFIG_SUFFIX ".abi3")
- else()
- set(PYTHON_CONFIG_SUFFIX "${PYTHON_EXTENSION_SUFFIX}")
- endif()
- endif()
-endmacro()
-
-macro(setup_clang)
- set(CLANG_DIR "")
- set(CLANG_DIR_SOURCE "")
-
- set(clang_not_found_message "Unable to detect CLANG location by checking LLVM_INSTALL_DIR, \
- CLANG_INSTALL_DIR or running llvm-config.")
-
- if (DEFINED ENV{LLVM_INSTALL_DIR})
- set(CLANG_DIR $ENV{LLVM_INSTALL_DIR})
- string(REPLACE "_ARCH_" "${PYTHON_ARCH}" CLANG_DIR "${CLANG_DIR}")
- set(CLANG_DIR_SOURCE "LLVM_INSTALL_DIR")
- elseif (DEFINED ENV{CLANG_INSTALL_DIR})
- set(CLANG_DIR $ENV{CLANG_INSTALL_DIR})
- string(REPLACE "_ARCH_" "${PYTHON_ARCH}" CLANG_DIR "${CLANG_DIR}")
- set(CLANG_DIR_SOURCE "CLANG_INSTALL_DIR")
- else ()
- if (NOT LLVM_CONFIG)
- get_llvm_config()
- endif()
- set(CLANG_DIR_SOURCE "${LLVM_CONFIG}")
- if ("${CLANG_DIR_SOURCE}" STREQUAL "")
- message(FATAL_ERROR "${clang_not_found_message}")
- endif()
-
- EXEC_PROGRAM("${LLVM_CONFIG}" ARGS "--prefix" OUTPUT_VARIABLE CLANG_DIR)
- if (NOT "${CLANG_DIR}" STREQUAL "")
- EXEC_PROGRAM("${LLVM_CONFIG}" ARGS "--version" OUTPUT_VARIABLE CLANG_VERSION)
- if (CLANG_VERSION VERSION_LESS 3.9)
- message(FATAL_ERROR "libclang version 3.9 or higher is required \
- (${LLVM_CONFIG} detected ${CLANG_VERSION} at ${CLANG_DIR}).")
- endif()
- endif()
- endif()
-
- if ("${CLANG_DIR}" STREQUAL "")
- message(FATAL_ERROR "${clang_not_found_message}")
- elseif (NOT IS_DIRECTORY ${CLANG_DIR})
- message(FATAL_ERROR "${CLANG_DIR} detected by ${CLANG_DIR_SOURCE} does not exist.")
- endif()
-
- # The non-development Debian / Ubuntu packages (e.g. libclang1-6.0) do not ship a
- # libclang.so symlink, but only libclang-6.0.so.1 and libclang.so.1 (adjusted for version number).
- # Thus searching for libclang would not succeed.
- # The "libclang.so" symlink is shipped as part of the development package (libclang-6.0-dev) which
- # we need anyway because of the headers. Thus we will search for libclang.so.1 also, and complain
- # about the headers not being found in a check further down. This is more friendly to the user,
- # so they don't scratch their head thinking that they have already installed the necessary package.
- set(CLANG_LIB_NAMES clang libclang.so libclang.so.1)
- if(MSVC)
- set(CLANG_LIB_NAMES libclang)
- endif()
-
- find_library(CLANG_LIBRARY NAMES ${CLANG_LIB_NAMES} HINTS ${CLANG_DIR}/lib)
- if (NOT EXISTS ${CLANG_LIBRARY})
- string(REPLACE ";" ", " CLANG_LIB_NAMES_STRING "${CLANG_LIB_NAMES}")
- message(FATAL_ERROR "Unable to find the Clang library in ${CLANG_DIR}.\
- Names tried: ${CLANG_LIB_NAMES_STRING}.")
- endif()
-
- message(STATUS "CLANG: ${CLANG_DIR}, ${CLANG_LIBRARY} detected by ${CLANG_DIR_SOURCE}")
-
- set(CLANG_EXTRA_INCLUDES ${CLANG_DIR}/include)
- set(CLANG_EXTRA_LIBRARIES ${CLANG_LIBRARY})
-
- # Check if one of the required clang headers is found. Error out early at CMake time instead of
- # compile time if not found.
- # It can happen that a user uses a distro-provided libclang.so, but no development header package
- # was installed (e.g. libclang-6.0-dev on Ubuntu).
- set(CMAKE_REQUIRED_INCLUDES ${CLANG_EXTRA_INCLUDES})
- set(CLANG_HEADER_FILE_TO_CHECK "clang-c/Index.h")
- check_include_file_cxx(${CLANG_HEADER_FILE_TO_CHECK} CLANG_INCLUDE_FOUND)
- unset(CMAKE_REQUIRED_INCLUDES)
- if (NOT CLANG_INCLUDE_FOUND)
- # Need to unset so that when installing the package, CMake doesn't complain that the header
- # still isn't found.
- unset(CLANG_INCLUDE_FOUND CACHE)
- message(FATAL_ERROR "Unable to find required Clang header file ${CLANG_HEADER_FILE_TO_CHECK} \
- in ${CLANG_DIR}/include. Perhaps you forgot to install the clang development header \
- package? (e.g. libclang-6.0-dev)")
- endif()
-endmacro()
-
-macro(set_quiet_build)
- # Don't display "up-to-date / install" messages when installing, to reduce visual clutter.
- set(CMAKE_INSTALL_MESSAGE NEVER)
- # Override message not to display info messages when doing a quiet build.
- function(message)
- list(GET ARGV 0 MessageType)
- if (MessageType STREQUAL FATAL_ERROR OR
- MessageType STREQUAL SEND_ERROR OR
- MessageType STREQUAL WARNING OR
- MessageType STREQUAL AUTHOR_WARNING)
- list(REMOVE_AT ARGV 0)
- _message(${MessageType} "${ARGV}")
- endif()
- endfunction()
-endmacro()
-
-macro(get_python_extension_suffix)
- # Result of importlib.machinery.EXTENSION_SUFFIXES depends on the platform,
- # but generally looks something like:
- # ['.cpython-38-x86_64-linux-gnu.so', '.abi3.so', '.so']
- # We pick the first most detailed one.
-
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "if True:
- import re
- try:
- from importlib import machinery
- first_suffix = machinery.EXTENSION_SUFFIXES[0]
- except (AttributeError, ImportError):
- import imp
- first_suffix = imp.get_suffixes()[0][0]
- res = re.search(r'^(.+)\\.', first_suffix)
- if res:
- first_suffix = res.group(1)
- else:
- first_suffix = ''
- print(first_suffix)
- "
- OUTPUT_VARIABLE PYTHON_EXTENSION_SUFFIX
- OUTPUT_STRIP_TRAILING_WHITESPACE)
- message("PYTHON_EXTENSION_SUFFIX: " ${PYTHON_EXTENSION_SUFFIX})
-endmacro()
-
-macro(get_llvm_config)
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "if True:
- import os
- import sys
- sys.path.append(os.path.realpath(os.path.join('${CMAKE_CURRENT_LIST_DIR}', '..', '..')))
- from build_scripts.utils import find_llvm_config
- llvmConfig = find_llvm_config()
- if llvmConfig:
- print(llvmConfig)
- "
- OUTPUT_VARIABLE LLVM_CONFIG
- OUTPUT_STRIP_TRAILING_WHITESPACE)
- message("LLVM_CONFIG: " ${LLVM_CONFIG})
-endmacro()
-
-macro(get_python_arch)
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "if True:
- import sys
- print('64' if sys.maxsize > 2**31-1 else '32')
- "
- OUTPUT_VARIABLE PYTHON_ARCH
- OUTPUT_STRIP_TRAILING_WHITESPACE)
- message("PYTHON_ARCH: " ${PYTHON_ARCH})
-endmacro()
-
-macro(shiboken_parse_all_arguments prefix type flags options multiopts)
- cmake_parse_arguments(${prefix} "${flags}" "${options}" "${multiopts}" ${ARGN})
- if(DEFINED ${prefix}_UNPARSED_ARGUMENTS)
- message(FATAL_ERROR "Unknown arguments were passed to ${type} (${${prefix}_UNPARSED_ARGUMENTS}).")
- endif()
-endmacro()
-
-macro(shiboken_check_if_limited_api)
- # On Windows, PYTHON_LIBRARIES can be a list. Example:
- # optimized;C:/Python36/libs/python36.lib;debug;C:/Python36/libs/python36_d.lib
- # On other platforms, this result is not used at all.
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "if True:
- import os
- for lib in '${PYTHON_LIBRARIES}'.split(';'):
- if '/' in lib and os.path.isfile(lib):
- prefix, py = lib.rsplit('/', 1)
- if py.startswith('python3'):
- print(prefix + '/python3.lib')
- break
- "
- OUTPUT_VARIABLE PYTHON_LIMITED_LIBRARIES
- OUTPUT_STRIP_TRAILING_WHITESPACE)
-
- if(FORCE_LIMITED_API STREQUAL "yes")
- if (${PYTHON_VERSION_MAJOR} EQUAL 3 AND ${PYTHON_VERSION_MINOR} GREATER 4)
- # GREATER_EQUAL is available only from cmake 3.7 on. We mean python 3.5 .
- set(PYTHON_LIMITED_API 1)
- endif()
- if(WIN32)
- if (${PYTHON_VERSION_MAJOR} EQUAL 3 AND ${PYTHON_VERSION_MINOR} GREATER 4)
- # PYSIDE-560: XXX maybe add an option to setup.py as override
- set(SHIBOKEN_PYTHON_LIBRARIES ${PYTHON_LIMITED_LIBRARIES})
- endif()
- endif()
- endif()
-endmacro()
-
-
-macro(shiboken_find_required_python)
- if(${ARGC} GREATER 0)
- find_package(PythonInterp ${ARGV0} REQUIRED)
- find_package(PythonLibs ${ARGV0} REQUIRED)
- else()
- # If no version is specified, just use any interpreter that can be found (from PATH).
- # This is useful for super-project builds, so that the default system interpeter
- # gets picked up (e.g. /usr/bin/python and not /usr/bin/python2.7).
- find_package(PythonInterp REQUIRED)
- find_package(PythonLibs REQUIRED)
- endif()
- shiboken_validate_python_version()
-
- set(SHIBOKEN_PYTHON_INTERPRETER "${PYTHON_EXECUTABLE}")
- set_property(GLOBAL PROPERTY SHIBOKEN_PYTHON_INTERPRETER "${PYTHON_EXECUTABLE}")
-endmacro()
-
-macro(shiboken_validate_python_version)
- if((PYTHON_VERSION_MAJOR EQUAL "2" AND PYTHON_VERSION_MINOR LESS "7") OR
- (PYTHON_VERSION_MAJOR EQUAL "3" AND PYTHON_VERSION_MINOR LESS "5"))
- message(FATAL_ERROR
- "Shiboken requires Python 2.7+ or Python 3.5+.")
- endif()
-endmacro()
-
-macro(shiboken_compute_python_includes)
- shiboken_parse_all_arguments(
- "SHIBOKEN_COMPUTE_INCLUDES" "shiboken_compute_python_includes"
- "IS_CALLED_FROM_EXPORT" "" "" ${ARGN})
-
-
- # If the installed shiboken config file is used,
- # append the found Python include dirs as an interface property on the libshiboken target.
- # This needs to be dynamic because the user of the library might have python installed
- # in a different path than when shiboken was originally built.
- # Otherwise if shiboken is currently being built itself (either as standalone, or super project
- # build) append the include dirs as PUBLIC.
- if (SHIBOKEN_COMPUTE_INCLUDES_IS_CALLED_FROM_EXPORT)
- #TODO target_include_directories works on imported targets only starting with v3.11.0.
- set_property(TARGET Shiboken2::libshiboken
- APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${PYTHON_INCLUDE_DIRS})
- else()
- target_include_directories(libshiboken
- PUBLIC $<BUILD_INTERFACE:${PYTHON_INCLUDE_DIRS}>)
- endif()
-
-
- set(SHIBOKEN_PYTHON_INCLUDE_DIRS "${PYTHON_INCLUDE_DIRS}")
- message(STATUS
- "SHIBOKEN_PYTHON_INCLUDE_DIRS computed to value: '${SHIBOKEN_PYTHON_INCLUDE_DIRS}'")
-endmacro()
-
-# Given a list of the following form:
-# optimized;C:/Python36/libs/python36.lib;debug;C:/Python36/libs/python36_d.lib
-# choose the correpsonding library to use, based on the current configuration type.
-function(shiboken_get_library_for_current_config library_list current_config out_var)
- list(FIND library_list "optimized" optimized_found)
- list(FIND library_list "general" general_found)
- list(FIND library_list "debug" debug_found)
-
- if (optimized_found OR general_found OR debug_found)
- # Iterate over library list to find the most appropriate library.
- foreach(token ${library_list})
- if(token STREQUAL "optimized" OR token STREQUAL "general")
- set(is_debug 0)
- set(token1 1)
- set(lib "")
- elseif(token STREQUAL "debug")
- set(is_debug 1)
- set(token1 1)
- set(lib "")
- elseif(EXISTS ${token})
- set(lib ${token})
- set(token2 1)
- else()
- set(token1 0)
- set(token2 0)
- set(lib "")
- endif()
-
- if(token1 AND token2)
- if((is_debug AND lib AND current_config STREQUAL "Debug")
- OR (NOT is_debug AND lib AND (NOT current_config STREQUAL "Debug")))
- set(${out_var} ${lib} PARENT_SCOPE)
- return()
- endif()
- endif()
- endforeach()
- else()
- # No configuration specific libraries found, just set the original value.
- set(${out_var} "${library_list}" PARENT_SCOPE)
- endif()
-
-endfunction()
-
-macro(shiboken_compute_python_libraries)
- shiboken_parse_all_arguments(
- "SHIBOKEN_COMPUTE_LIBS" "shiboken_compute_python_libraries"
- "IS_CALLED_FROM_EXPORT" "" "" ${ARGN})
-
- if (NOT SHIBOKEN_PYTHON_LIBRARIES)
- set(SHIBOKEN_PYTHON_LIBRARIES "")
- endif()
-
- if(CMAKE_BUILD_TYPE STREQUAL "Debug")
- if(WIN32 AND NOT SHIBOKEN_PYTHON_LIBRARIES)
- set(SHIBOKEN_PYTHON_LIBRARIES ${PYTHON_DEBUG_LIBRARIES})
- endif()
- endif()
-
- if(CMAKE_BUILD_TYPE STREQUAL "Release")
- if(WIN32 AND NOT SHIBOKEN_PYTHON_LIBRARIES)
- set(SHIBOKEN_PYTHON_LIBRARIES ${PYTHON_LIBRARIES})
- endif()
- endif()
-
- # If the resulting variable
- # contains a "debug;X;optimized;Y" list like described in shiboken_check_if_limited_api,
- # make sure to pick just one, so that the final generator expressions are valid.
- shiboken_get_library_for_current_config("${SHIBOKEN_PYTHON_LIBRARIES}" "${CMAKE_BUILD_TYPE}" "SHIBOKEN_PYTHON_LIBRARIES")
-
- if(APPLE)
- set(SHIBOKEN_PYTHON_LIBRARIES "-undefined dynamic_lookup")
- endif()
-
- # If the installed shiboken config file is used,
- # append the computed Python libraries as an interface property on the libshiboken target.
- # This needs to be dynamic because the user of the library might have python installed
- # in a different path than when shiboken was originally built.
- # Otherwise if shiboken is currently being built itself (either as standalone, or super project
- # build) append the libraries as PUBLIC.
- if (SHIBOKEN_COMPUTE_LIBS_IS_CALLED_FROM_EXPORT)
- #TODO target_link_libraries works on imported targets only starting with v3.11.0.
- set_property(TARGET Shiboken2::libshiboken
- APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${SHIBOKEN_PYTHON_LIBRARIES})
- else()
- target_link_libraries(libshiboken
- PUBLIC $<BUILD_INTERFACE:${SHIBOKEN_PYTHON_LIBRARIES}>)
- endif()
-
- message(STATUS "SHIBOKEN_PYTHON_LIBRARIES computed to value: '${SHIBOKEN_PYTHON_LIBRARIES}'")
-endmacro()
-
-function(shiboken_check_if_built_and_target_python_are_compatible)
- if(NOT SHIBOKEN_PYTHON_VERSION_MAJOR STREQUAL PYTHON_VERSION_MAJOR)
- message(FATAL_ERROR "The detected Python major version is not \
-compatible with the Python major version which was used when Shiboken was built.
-Built with: '${SHIBOKEN_PYTHON_VERSION_MAJOR}.${SHIBOKEN_PYTHON_VERSION_MINOR}' \
-Detected: '${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}'")
- else()
- if(NOT SHIBOKEN_PYTHON_LIMITED_API
- AND NOT SHIBOKEN_PYTHON_VERSION_MINOR STREQUAL PYTHON_VERSION_MINOR)
- message(FATAL_ERROR
- "The detected Python minor version is not compatible with the Python minor \
-version which was used when Shiboken was built. Consider building shiboken with \
-FORCE_LIMITED_API set to '1', so that only the Python major version matters.
-Built with: '${SHIBOKEN_PYTHON_VERSION_MAJOR}.${SHIBOKEN_PYTHON_VERSION_MINOR}' \
-Detected: '${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}'")
- endif()
- endif()
-endfunction()
diff --git a/sources/shiboken2/doc/CMakeLists.txt b/sources/shiboken2/doc/CMakeLists.txt
deleted file mode 100644
index 5903e9dfc..000000000
--- a/sources/shiboken2/doc/CMakeLists.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-find_program(SPHINX sphinx-build DOC "Path to sphinx-build binary.")
-
-if (SPHINX)
- message("-- sphinx-build - found")
- configure_file(conf.py.in conf.py @ONLY)
- add_custom_target(doc ${SPHINX} -b html -c . ${CMAKE_CURRENT_SOURCE_DIR} html )
-else()
- message("-- sphinx-build - not found! doc target disabled")
- if (WIN32)
- # if jom is used and we have no sphinx, then jom will crash.
- # so for windows, we always create a doc target (until jom gets fixed...)
- add_custom_target(doc echo.
- COMMAND echo +++ This is a fake build, to make 'jom' happy.
- COMMAND echo +++ The documentation was _not_ built!
- COMMAND echo.
- )
- endif()
-endif()
-
-if (NOT WIN32)
- file(GLOB manpages "${CMAKE_CURRENT_SOURCE_DIR}/*.1")
- install(FILES ${manpages} DESTINATION share/man/man1)
-endif()
diff --git a/sources/shiboken2/doc/README.md b/sources/shiboken2/doc/README.md
deleted file mode 100644
index 2575eafd2..000000000
--- a/sources/shiboken2/doc/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Shiboken Documentation
-
-The documentation was written and needs to be generated
-with [python-sphinx](http://www.sphinx-doc.org/en/master/)
-
-### Images
-
-The SVG diagrams use the Qt color scheme.
-The font also follows Qt styling, and it is called `Titillium`.
-It can be download from:
-* https://fonts.google.com/specimen/Titillium+Web
-* https://www.fontsquirrel.com/fonts/Titillium
diff --git a/sources/shiboken2/doc/_templates/index.html b/sources/shiboken2/doc/_templates/index.html
deleted file mode 100644
index 00ac64271..000000000
--- a/sources/shiboken2/doc/_templates/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-{% extends "layout.html" %}
-{% set title = 'Overview' %}
-{% block body %}
-<div class="section">
- <h1>{{ project }} {{ version }}</h1>
-
- <p>{{ project }} is a plugin (front-end) for Generator Runner. It generates bindings for C++ libraries using CPython source code.</p>
-
- <h2>Documentation</h2>
- <table class="contentstable" align="center" style="margin-left: 30px"><tr>
- <td width="50%">
- <p class="biglink"><a class="biglink" href="{{ pathto("contents") }}">Contents</a><br/>
- <span class="linkdescr">for a complete overview</span></p>
- <p class="biglink"><a class="biglink" href="{{ pathto("faq") }}">FAQ</a><br/>
- <span class="linkdescr">answers for frequent asked questions</span></p>
- <p class="biglink"><a class="biglink" href="{{ pathto("commandlineoptions") }}">Command line options</a><br/>
- <span class="linkdescr">explains the few flags used to change {{ project }} behaviour</span></p>
- <p class="biglink"><a class="biglink" href="{{ pathto("typesystemvariables") }}">Type System Variables</a><br/>
- <span class="linkdescr">describes the type system variables that could be used in user custom code</span></p>
- <p class="biglink"><a class="biglink" href="{{ pathto("typeconverters") }}">Type Converters</a><br/>
- <span class="linkdescr">describes how to define type converters</span></p>
- </td>
- <td width="50%">
- <p class="biglink"><a class="biglink" href="{{ pathto("codeinjectionsemantics") }}">Code Injection Semantics</a><br/>
- <span class="linkdescr">explains how custom code injection is interpreted by {{ project }}</span></p>
- <p class="biglink"><a class="biglink" href="{{ pathto("sequenceprotocol") }}">Sequence Protocol</a><br/>
- <span class="linkdescr">support for python sequence protocol</span></p>
- <p class="biglink"><a class="biglink" href="{{ pathto("ownership") }}">Object Ownership</a><br/>
- <span class="linkdescr">object ownership features</span></p>
- <p class="biglink"><a class="biglink" href="{{ pathto("wordsofadvice") }}">Words of Advice</a><br/>
- <span class="linkdescr">Advice for binding developers and users.</span></p>
- </td></tr>
- </table>
-</div>
-{% endblock %}
diff --git a/sources/shiboken2/doc/_templates/layout.html b/sources/shiboken2/doc/_templates/layout.html
deleted file mode 100644
index 2e2e9e892..000000000
--- a/sources/shiboken2/doc/_templates/layout.html
+++ /dev/null
@@ -1,29 +0,0 @@
-{% extends "!layout.html" %}
-
-# Invert sidebars
-{%- block sidebar1 %}{{ sidebar() }}{%- endblock %}
-{%- block sidebar2 %}{%- endblock %}
-
-{%- block header %}
-<div id="container">
-<div class="header">
- <div class="header_container">
- <div class="logo"><a href="http://www.pyside.org"><img alt="PySide" src="{{ pathto('_static/pysidelogo.png', 1) }}"/></a></div>
- {{ relbar() }}
- </div>
-</div>
-{%- endblock -%}
-
-{%- block footer %}
- <div class="footer">
- <a href="http://www.qt.io/"><img src="{{ pathto('_static/logo_qt.png', 1) }}" alt="Qt" border="0" /></a>
- <a href="http://www.python.org"><img src="{{ pathto('_static/logo_python.jpg', 1) }}" alt="Python" border="0" /></a>
- </div>
-</div>
-{%- endblock %}
-
-# No top relbar.
-{%- block relbar1 %}{%- endblock %}
-
-# No bottom relbar.
-{%- block relbar2 %}{%- endblock %}
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/searchbox.html b/sources/shiboken2/doc/_themes/pysidedocs/searchbox.html
deleted file mode 100644
index 55a972156..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/searchbox.html
+++ /dev/null
@@ -1,12 +0,0 @@
-{%- if pagename != "search" %}
-<div id="searchbox" style="display: none">
- <h3>{{ _('Quick search') }}</h3>
- <form class="search" action="{{ pathto('search') }}" method="get">
- <input type="text" name="q" id="q" size="18" />
- <input type="submit" value="{{ _('Go') }}" id="search_button" />
- <input type="hidden" name="check_keywords" value="yes" />
- <input type="hidden" name="area" value="default" />
- </form>
-</div>
-<script type="text/javascript">$('#searchbox').show(0);</script>
-{%- endif %}
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/static/bg_header.png b/sources/shiboken2/doc/_themes/pysidedocs/static/bg_header.png
deleted file mode 100644
index 843e7e2c5..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/static/bg_header.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/static/bg_topo.jpg b/sources/shiboken2/doc/_themes/pysidedocs/static/bg_topo.jpg
deleted file mode 100644
index 4229ae8db..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/static/bg_topo.jpg
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/static/fakebar.png b/sources/shiboken2/doc/_themes/pysidedocs/static/fakebar.png
deleted file mode 100644
index b45830e00..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/static/fakebar.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/static/logo_python.jpg b/sources/shiboken2/doc/_themes/pysidedocs/static/logo_python.jpg
deleted file mode 100644
index cd474efba..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/static/logo_python.jpg
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/static/logo_qt.png b/sources/shiboken2/doc/_themes/pysidedocs/static/logo_qt.png
deleted file mode 100644
index 39a4a26f3..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/static/logo_qt.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/static/pyside.css b/sources/shiboken2/doc/_themes/pysidedocs/static/pyside.css
deleted file mode 100644
index c6a0c56a1..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/static/pyside.css
+++ /dev/null
@@ -1,2071 +0,0 @@
-@import url('cookie-confirm.css') screen;
-
-/* -- admonitions -- */
-
-div.admonition {
- margin: 1.5em 0 1.5em;
- padding: 0;
-}
-
-div.admonition dt {
- font-weight: bold;
-}
-
-div.admonition dl {
- margin-bottom: 0;
-}
-
-p.admonition-title {
- margin: 0px 10px 5px 0px;
- font-weight: bold;
-}
-
-div.admonition code {
- font-family: inherit;
-}
-
-p.admonition-title + p {
- padding-left: 1em;
-}
-
-div.admonition a:after {
- content: ', ';
-}
-
-div.admonition a:last-child:after {
- content: '';
-}
-
-.body {
- width: 100%
-}
-.bodywrapper .admonition p.admonition-title {
- margin-bottom:5px
-}
-
-.bodywrapper .admonition p {
- margin:0
-}
-
-div.body p.centered {
- text-align: center;
- margin-top: 25px;
-}
-
-div.warning, div.seealso, div.note {
- padding: 6px 0px 6px 10px;
- border: none;
-}
-
-div.warning {
- background-color: #ffe4e4;
-}
-
-div.seealso {
- background-color: #fff2d6;
-}
-
-div.note {
- background-color: #f3f3f4;
-}
-
-table.docutils {
- margin-right: auto;
- margin-bottom: 10px;
- border: none;
- width: initial;
-}
-
-table.docutils.colwidths-given td {
- float: none;
-}
-
-table.docutils th,
-table.docutils td {
- padding-left:0;
- border: none;
-}
-
-table.docutils td ul {
- margin:0
-}
-
-table.docutils td ul > li {
- margin: 0 0 0.5em;
-}
-h2 em {
- float: right;
- font-size: 10px;
- position: relative;
- top: -20px;
-}
-
-.document {
- padding-bottom: 20px;
-}
-
-.documentwrapper {
- margin-left: 255px;
-}
-
-.body blockquote {
- border: none;
- padding-left: 0;
- margin-bottom: 1.5em;
-}
-
-.sphinxsidebar {
- float: left;
- width: 186px;
- padding: 25px;
- text-align: left;
- background-color: #fff;
-}
-
-.sphinxsidebar ul {
- padding: 0px;
- margin: 0px;
- list-style-position: inside;
-}
-
-.sphinxsidebar > ul {
- padding: 0px;
- margin: 0px;
-}
-
-.sphinxsidebar ul li li {
- margin-left: 10px;
- padding: 0px;
- font-size: 0.95em;
-}
-
-.sphinxsidebar ul a,
-.sphinxsidebar p.topless a {
- word-break: break-word;
-}
-
-.sphinxsidebar h3, .sphinxsidebar h3 a {
- color: #333;
-}
-
-.sphinxsidebar p.topless {
- margin: 1em 0 1em;
-}
-
-.pysidetoc ul {
- list-style: none;
- padding: 0px;
- margin: 0px;
-}
-
-.pysidetoc em {
- font-style: normal;
-}
-
-.pysidetoc strong {
- display: block;
- padding: 5px;
- margin: 0 10px 10px 0;
- border: none;
- background-color: #e2e2e2;
-}
-
-.section .docutils.container td {
- float:left;
-}
-
-.hide {
- display: none;
-}
-
-/* copy-notice */
-.document + p {
- margin-left: 255px;
- width: 70%;
- font-size: 0.75em;
- margin: 0 35px 15px 280px;
-}
-
-#searchbox {
- border-top: 1px solid #989898;
- padding-top: 10px;
- margin-left: -10px;
- margin-right: -10px;
- padding-left: 10px;
- padding-right: 10px;
-}
-
-#search_button {
- border: 1px solid #3A393A;
- background-color: #3A393A;
- color: white;
- cursor: pointer;
- -moz-border-radius: 5px;
- -webkit-border-radius: 5px;
- -khtml-border-radius: 5px;
-
-}
-
-form {
- margin: 0px;
- padding: 0px;
-}
-
-#searchbox h3 {
- padding: 10px 0 0 0;
- margin-bottom: 5px;
-}
-
-/* search field */
-form #q {
- width: 136px;
- /* height: 22px; */
- /* border: none; */
- margin: 0px;
- -moz-border-radius: 5px;
- -webkit-border-radius: 5px;
- -khtml-border-radius: 5px;
- margin-top: 2px;
- padding: 4px;
- line-height: 22px;
-}
-
-#search-results h2 {
- display: none;
-}
-
-#search-results h2 {
- display: none;
-}
-
-#search-results ul.search {
- margin: 0px;
- padding: 0px;
-}
-
-ul.search div.context {
- padding-left: 40px;
-}
-
-#installation td {
- text-align: center;
- font-weight: bold;
-}
-
-em {
- color: inherit;
- font-style:italic;
-}
-
-/******** REL bar *********/
-
-.related {
- display: inline;
-}
-
-.related h3 {
- display: none;
-}
-
-.align-center {
- text-align: center;
-}
-
-.contentstable {
- width: 100%;
-}
-
-.contentstable td {
- padding-left: 30px;
- vertical-align: top;
-}
-
-p.biglink a {
- font-size: 20px;
-}
-
-dt:target, .highlight {
- background-color: #fbe54e;
-}
-
-p.highlight-link {
- margin-top: 10px;
- font-size: 0.8em;
-}
-
-#synopsis table, table.field-list {
- margin: 1em 0 1em 0;
-}
-
-table.field-list tr {
- text-align: left;
-}
-
-tt.descname {
- font-size: 120%;
- font-weight: bold;
-}
-
-#functions ul, #virtual-functions ul, #slots ul, #signals ul, #static-functions ul {
- margin: 0;
- padding: 6px;
- border: 1px solid #ddd;
- border-radius: 0;
- background-color: #e2e2e2;
-}
-
-#functions p, #virtual-functions p, #slots p, #signals p, #static-functions p {
- margin: 0;
- padding: 0;
-}
-
-#functions li, #virtual-functions li, #slots li, #signals li, #static-functions li {
- list-style: none;
- margin: 5px;
- padding: 0;
- font-size: 90%;
-}
-
-#synopsis span.pre {
- color: #009491;
- font-weight: bolder;
-}
-
-#detailed-description .class dt,
-#detailed-description .method dt,
-#detailed-description .staticmethod dt,
-#detailed-description .attribute dt {
- margin: 0px;
- margin-bottom: 10px;
- padding: 10px;
- font-weight: bold;
- background-color: #e2e2e2;
- border: none;
- border-radius: 0;
-}
-
-#detailed-description dd > blockquote,
-#detailed-description dd > .field-list {
- font-family: 'Droid Sans Mono';
- font-size: small;
- border-left: 10px solid #e2e2e2;
- padding-left: 10px;
- margin-bottom: 1.5em;
-}
-
-#detailed-description dd > blockquote blockquote {
- border: none;
- padding: 0;
-}
-
-#detailed-description .class .field-odd,
-#detailed-description .method .field-odd,
-#detailed-description .staticmethod .field-odd,
-#detailed-description .attribute .field-odd {
- margin: 0;
- padding: 1px 0 0 0;
- background-color: #ffffff;
-
-}
-
-#detailed-description .class .field-even,
-#detailed-description .method .field-even,
-#detailed-description .staticmethod .field-even,
-#detailed-description .attribute .field-even {
- margin: 0;
- padding: 1px 0 0 0;
- background-color: #ffffff;
-}
-
-#detailed-description .class .field-odd li,
-#detailed-description .method .field-odd li,
-#detailed-description .staticmethod .field-odd li,
-#detailed-description .attribute .field-odd li {
- list-style: none;
- margin: 0;
- padding: 0;
-
-}
-
-#detailed-description .class .field-even li,
-#detailed-description .method .field-even li,
-#detailed-description .staticmethod .field-even li,
-#detailed-description .attribute .field-even li {
- list-style: none;
- margin: 0;
- padding: 0;
-}
-
-#detailed-description .class .field-odd p,
-#detailed-description .method .field-odd p,
-#detailed-description .staticmethod .field-odd p,
-#detailed-description .attribute .field-odd p{
- margin: 0;
- margin-left: 20px;
-
-}
-
-#detailed-description .class .field-even p,
-#detailed-description .method .field-even p,
-#detailed-description .staticmethod .field-even p,
-#detailed-description .attribute .field-even p{
- margin: 0;
- margin-left: 20px;
-}
-
-#detailed-description .class .field-odd p:last-child,
-#detailed-description .method .field-odd p:last-child,
-#detailed-description .staticmethod .field-odd p:last-child,
-#detailed-description .attribute .field-odd p:last-child {
- margin-bottom: 10px;
-
-}
-
-#detailed-description .class .field-even p:last-child,
-#detailed-description .method .field-even p:last-child,
-#detailed-description .staticmethod .field-even p:last-child,
-#detailed-description .attribute .field-even p:last-child{
- margin-bottom: 10px;
-}
-
-.document dl.attribute,
-.document dl.class,
-.document dl.method,
-.document dl.staticmethod {
- margin-top: 2em;
-}
-
-.document dl.attribute dd,
-.document dl.class dd,
-.document dl.method dd,
-.document dl.staticmethod dd {
- padding-left: 1em;
-}
-
-#detailed-description .attribute td:nth-child(1) {
- font-family: 'Droid Sans Mono';
-}
-
-/* Qt theme */
-#navbar {
- position:fixed;
- top:0;
- left:0;
- z-index:100;
- background:#fff;
- width:100%
-}
-#navbar .container, .fixed .container {
- max-width:1280px;
- margin:0 auto;
- padding:0 3.9%; /* 0? */
- position:relative;
- overflow:visible
-}
-#navbar .navbar-header {
- position:relative
-}
-#menuextras li a:hover span {
- color: #41cd52;
-}
-/* new header */
-#mm-wrap, #mm-wrap #mm-helper,
-#mm-wrap #mm-helper li.mm-item,
-#mm-wrap #mm-helper a.mm-link {
- -moz-transition: none;
- -o-transition: none;
- -webkit-transition: none;
- transition: none;
- -webkit-border-radius: 0 0 0 0;
- -moz-border-radius: 0 0 0 0;
- -ms-border-radius: 0 0 0 0;
- -o-border-radius: 0 0 0 0;
- border-radius: 0 0 0 0;
- -webkit-box-shadow: none;
- -moz-box-shadow: none;
- -ms-box-shadow: none;
- -o-box-shadow: none;
- box-shadow: none;
- background: none;
- border: 0;
- bottom: auto;
- box-sizing: border-box;
- clip: auto;
- color: #090e21;
- display: block;
- float: none;
- font-family: inherit;
- font-size: 14px;
- height: auto;
- left: auto;
- line-height: 1.7;
- list-style-type: none;
- margin: 0;
- min-height: 0;
- opacity: 1;
- outline: none;
- overflow: visible;
- padding: 0;
- position: relative;
- right: auto;
- text-align: left;
- text-decoration: none;
- text-transform: none;
- top: auto;
- vertical-align: baseline;
- visibility: inherit;
- width: auto;
-}
-#mm-wrap #mm-helper {
- visibility:visible;
- text-align:right;
- padding:0 0px 0 0px
-}
-#navbar #mm-wrap #mm-helper li.mm-item {
- border-right:solid #f3f3f4 1px;
- padding-right:30px;
- padding-left:30px
-}
-#navbar #mm-wrap #mm-helper li.mm-item > a:hover {
- opacity: .5
-}
-#mm-wrap #mm-helper > li.mm-item {
- margin:0 0 0 0;
- display:inline-block;
- height:auto;
- vertical-align:middle
-}
-#navbar #mm-wrap #mm-helper li.mm-item:nth-child(3) {
- border-right:0
-}
-#mm-wrap #mm-helper a.mm-link {
- cursor: pointer
-}
-@media (max-width: 1279px) {
- #navbar {
- padding:0;
- position:relative;
- }
- #navbar .container {
- max-width:100%
- }
- .container {
- padding:0 2%
- }
-}
-#navbar .navbar-oneQt {
- display:inline;
- float:left;
- width:31px;
- color:#41cd52
-}
-#navbar .navbar-oneQt:before {
- content:attr(data-icon);
- position:absolute;
- top:14px;
- left:0;
- color:#41cd52;
- font-family:'Qt Icons';
- line-height:1;
- font-size:40px;
- transition:all 0.3s ease-in-out;
-}
-#mm-wrap {
- clear:both;
- background:rgba(255, 255, 255, 0.1);
- -webkit-border-radius:0px 0px 0px 0px;
- -moz-border-radius:0px 0px 0px 0px;
- -ms-border-radius:0px 0px 0px 0px;
- -o-border-radius:0px 0px 0px 0px;
- border-radius:0px 0px 0px 0px
-}
-#mm-wrap #mm-helper li.mm-item:last-child a {
- background:transparent url("icon_avatar.png") 50% 50% no-repeat !important;
- background-size:24px !important;
- width:24px !important;
- height:24px !important;
-}
-#navbar #mm-wrap #mm-helper li.mm-item > a {
- opacity:1;
- -webkit-transition:all 0.3s ease-in-out;
- -moz-transition:all 0.3s ease-in-out;
- -ms-transition:all 0.3s ease-in-out;
- -o-transition:all 0.3s ease-in-out;
- transition:all 0.3s ease-in-out;
-}
-#mm-wrap #mm-helper > li.mm-item > a.mm-link {
- border-top:0px solid #fff;
- border-left:0px solid #fff;
- border-right:0px solid #fff;
- border-bottom:0px solid #fff;
- outline:none;
- text-decoration:none;
- padding:0 0 0 0;
- line-height:70px;
- font-weight:normal;
- height:70px;
- vertical-align:baseline;
- text-align:left;
- width:auto;
- display:block;
- color:#090e21;
- text-transform:none;
- text-decoration:none;
- background:rgba(0, 0, 0, 0);
- -webkit-border-radius:0px 0px 0px 0px;
- -moz-border-radius:0px 0px 0px 0px;
- -ms-border-radius:0px 0px 0px 0px;
- -o-border-radius:0px 0px 0px 0px;
- border-radius:0px 0px 0px 0px;
- font-family:inherit;
- font-size:14px;
-}
-/* end new header */
-@media (min-width: 1320px) {
- .body .flowListDiv dl.flowList {
- -webkit-column-count:3;
- -moz-column-count:3;
- column-count:3
- }
-}
-@media (min-width: 1120px) {
- #navbar.fixed {
- -moz-box-shadow:0px 0px 8px rgba(0,0,0,0.23);
- -webkit-box-shadow:0px 0px 8px rgba(0,0,0,0.23);
- box-shadow:0px 0px 8px rgba(0,0,0,0.23)
- }
- #navbar.fixed #mm-wrap #mm-helper > li.mm-item > a.mm-link {
- height:50px;
- line-height:50px
- }
- #navbar.fixed .navbar-oneQt:before {
- font-size:35px;
- top:7px
- }
-
- .flowListDiv dl.flowList {
- -webkit-column-count:2;
- -moz-column-count:2;
- column-count:2
- }
-}
-@media (max-width: 1120px) {
- #navbar {
- padding:0;
- position:relative
- }
- #navbar .navbar-oneQt:before {
- left:10px
- }
- #navbar .container {
- max-width:100%;
- padding:0
- }
- #footerbar .container {
- padding:0
- }
- body .main {
- margin-top:0px
- }
- #footerbar .footer-main .footer-nav {
- padding:3.9% 0 3.9% 3%;
- border-bottom:1px solid #413d3b;
- float:none;
- display:block;
- width:auto
- }
- #footerbar .footer-main .theqtcompany {
- clear:both;
- float:left;
- margin:30px 0 8px 3%
- }
- #footerbar .footer-main .footer-social {
- float:left;
- padding:50px 0px 0px 3%
- }
- #footerbar #menu-footer-submenu {
- clear:both;
- float:none;
- display:block;
- padding:0px 0px 3.9% 3%
- }
- ul#menu-footer-submenu {
- margin-left: 0
- }
-}
-.cookies_yum {
- background-color:#cecfd5;
- display:none;
- width:100%
-}
-.cookies_yum img {
- width:25px;
- top:6px;
- display:inline-block;
- position:absolute;
- left:13px
-}
-.cookies_yum div {
- margin:0 auto;
- max-width:1280px;
- min-height:30px;
- padding:6px 0px 6px 0px;
- position:relative
-}
-.cookies_yum p {
- color:#09102b;
- margin:0px;
- font-size:0.79em;
- display:inline-block;
- line-height:1.2;
- padding:0 30px 0 50px
-}
-.cookies_yum p a {
- white-space:nowrap
-}
-.cookies_yum a:hover {
- color:#46a2da
-}
-.cookies_yum .close {
- width:15px;
- height:15px;
- background-image:url("cookiebar-x.png");
- background-size:15px 30px;
- background-position:top left;
- cursor:pointer;
- top:13px;
- right:13px;
- position:absolute;
- transition:none
-}
-.cookies_yum .close:hover {
- background-position:bottom left
-}
-#sidebar-toggle,#toc-toggle {
- width:24px;
- height:14px;
- background-size:24px 28px;
- cursor:pointer;
- background-image:url("list_expand.png");
- float:right
-}
-#sidebar-toggle.collapsed,
-#toc-toggle.collapsed {
- background-position:bottom left
-}
-#sidebar-content > h2 {
- display:none
-}
-#footerbar {
- background:#222840;
- color:#fff;
- font-size: 0.9em;
-}
-#footerbar.fixed {
- bottom:0;
- left:0;
- width:100%
-}
-#footerbar .footer-nav {
- display:inline;
- float:left
-}
-#footerbar .footer-main .footer-nav li {
- float:left;
- margin-right:1em
-}
-#footerbar .footer-main .footer-nav li a {
- display:block;
- padding:30px 0 10px 0;
- line-height:20px;
- height:20px;
- color:#fff;
- font-weight: 600;
-}
-#footerbar .footer-main .footer-nav li a:hover,#footerbar .footer-main .footer-nav li.current-menu-item a {
- color:#eee
-}
-#footerbar .footer-main .footer-nav .sub-menu {
- margin-left:0;
- margin-bottom:0
-}
-#footerbar .footer-main .footer-nav .sub-menu li {
- float:none;
- width: 100%;
-}
-#footerbar .footer-main .footer-nav .sub-menu ul {
- padding:1px 1em;
- font-size:0.786em;
- line-height:8px;
- float:none;
- color:#5d5b59;
- margin-bottom:0
-}
-#footerbar .footer-main .footer-nav .sub-menu li a {
- padding:2px 0;
- font-size:1em;
- float:none;
- color:#cecfd5;
- font-weight: 400;
-}
-#footerbar .footer-main .footer-nav .sub-menu li a:hover,#footerbar .footer-main .footer-nav .sub-menu li.current-menu-item a {
- color:#eee
-}
-#footerbar .theqtcompany {
- background:url("theqtcompany.png") no-repeat;
- background-size:100%;
- width:215px;
- height:68px;
- display:inline;
- float:right;
- margin:29px 0 28px 30px
-}
-#footerbar .footer-social {
- display:inline;
- float:right;
- width:164px
-}
-#footerbar .footer-main .footer-social>div {
- margin-left:0.1em;
- margin-bottom:10px
-}
-#footerbar .disclaimer {
- font-size:0.786em;
- line-height:2.73;
- color:#868584;
- padding-top:20px;
- padding-bottom:0.5%
-}
-#footerbar .disclaimer a {
- color:#bdbebf
-}
-#footerbar .disclaimer a:hover {
- color:#d6d6d6
-}
-#footerbar .disclaimer ul li {
- float:left;
- vertical-align:middle;
- margin-left:1.18em
-}
-#footerbar .disclaimer ul li:first-child {
- margin-left:0
-}
-#footerbar .disclaimer ul.lang-selector a {
- color:#506a34;
- color:rgba(128,195,66,0.3)
-}
-#footerbar .disclaimer ul.lang-selector a:hover {
- color:#80c342;
- color:rgba(128,195,66,0.7)
-}
-#menu-footer-menu, #menu-footer-menu ul {
- margin-left:0;
- margin-bottom:0
-}
-@font-face {
- font-family: 'Titillium Web';
- font-style: normal;
- font-weight: 400;
- src: url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-regular.eot");
- /* IE9 Compat Modes */
- src: local("Titillium Web"), local("TitilliumWeb-Regular"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-regular.eot?#iefix") format("embedded-opentype"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-regular.woff2") format("woff2"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-regular.woff") format("woff"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-regular.ttf") format("truetype"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-regular.svg#TitilliumWeb") format("svg");
- /* Legacy iOS */
-}
-/* titillium-web-italic - latin_latin-ext */
-@font-face {
- font-family: 'Titillium Web';
- font-style: italic;
- font-weight: 400;
- src: url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-italic.eot");
- /* IE9 Compat Modes */
- src: local("Titillium WebItalic"), local("TitilliumWeb-Italic"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-italic.eot?#iefix") format("embedded-opentype"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-italic.woff2") format("woff2"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-italic.woff") format("woff"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-italic.ttf") format("truetype"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-italic.svg#TitilliumWeb") format("svg");
- /* Legacy iOS */
-}
-/* titillium-web-600 - latin_latin-ext */
-@font-face {
- font-family: 'Titillium Web';
- font-style: normal;
- font-weight: 600;
- src: url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-600.eot");
- /* IE9 Compat Modes */
- src: local("Titillium WebSemiBold"), local("TitilliumWeb-SemiBold"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-600.eot?#iefix") format("embedded-opentype"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-600.woff2") format("woff2"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-600.woff") format("woff"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-600.ttf") format("truetype"), url("//d33sqmjvzgs8hq.cloudfront.net/wp-content/themes/oneqt/assets/fonts/titillium-web-v4-latin_latin-ext-600.svg#TitilliumWeb") format("svg");
- /* Legacy iOS */
-}
-@font-face {
- font-family:'Droid Sans Mono';
- font-style:normal;
- font-weight:400;
- src:local("Droid Sans Mono"),local("DroidSansMono"),url(//fonts.gstatic.com/s/droidsansmono/v7/ns-m2xQYezAtqh7ai59hJUYuTAAIFFn5GTWtryCmBQ4.woff) format("woff")
-}
-@font-face {
- font-family:'Qt Icons';
- src:url("../style/icomoon.eot?-tgjuoj");
- src:url("../style/icomoon.eot?#iefix-tgjuoj") format("embedded-opentype"),url("../style/icomoon.woff?-tgjuoj") format("woff"),url("../style/icomoon.ttf?-tgjuoj") format("truetype"),url("../style/icomoon.svg?-tgjuoj#icomoon") format("svg");
- font-weight:normal;
- font-style:normal
-}
-@font-face {
- font-family:'social-icons';
- src:url("../style/social-icons.eot?54625607");
- src:url("../style/social-icons.eot?54625607#iefix") format("embedded-opentype"),
- url("../style/social-icons.woff?54625607") format("woff");
- font-weight:normal;
- font-style:normal
-}
-.clearfix:before,.clearfix:after {
- content:" ";
- display:table
-}
-.clearfix:after {
- clear:both
-}
-.clearfix {
- *zoom:1
-}
-.clearfix .right {
- float:right
-}
-html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {
- margin:0;
- padding:0;
- border:0;
- font-size:100%
- line-height: 1.4;
-}
-html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,caption,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {
- vertical-align:baseline
-}
-h1,h2,h3,h4,h5,h6 {
- font-weight:300
-}
-.body h2,.body h3,.body h4,.body h5,.body h6 {
- margin:1.5em 0 0.75em
-}
-.body h1 {
- margin-bottom:0.75em;
- font-size:2.25em;
-}
-.body h3.fn,.body h3.flags {
- color:#26282a;
- font-size:1.46em;
- padding:15px 0 15px 0;
- border-bottom:2px #eee solid;
- word-wrap:break-word
-}
-.body .fngroup {
- border-bottom:2px #eee solid;
- padding-bottom:15px;
- margin-bottom:1.5em
-}
-.body .fngroup h3.fngroupitem {
- margin:0;
- padding-bottom:0;
- border:none
-}
-.body h3.fn .name,
-.body h3 span.type,
-.qmlname span.name {
- font-weight: 400
-}
-.qmlname {
- font-size:1.46em
-}
-.qmlproto table {
- border:none;
- border-bottom:2px #eee solid
-}
-.qmlproto table p {
- max-width:100%
-}
-.qmlproto table tr {
- background-color:#fff
-}
-.qmlname td, .qmlname th {
- border:none;
- text-align:left;
- padding:5px 0 0 0
-}
-.qmlreadonly,.qmldefault {
- padding:0 5px 0 5px;
- font-size:0.75em;
- background-color:#eee;
- float:right
-}
-.qmlreadonly {
- color:#414141
-}
-.qmldefault {
- color:#D14141
-}
-.rightAlign {
- padding:3px 5px 3px 10px;
- text-align:right
-}
-.centerAlign.functionIndex {
- text-align:center;
- font-size:150%;
- margin-bottom: 1em
-}
-article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section {
- display:block
-}
-body {
- line-height:1;
- font-family:'Titillium Web', Arial, Helvetica, sans-serif;
- font-weight:400;
- transition-duration:1s;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- font-size: 16px;
- background-color:#f3f3f4;
- color:#404244;
-}
-ol,ul {
- list-style-type: square;
- color: #17a81a;
-}
-.body ol,.body ul {
- margin-top:0.75em;
- margin-left:20px
-}
-.bodywrapper ol>li {
- list-style-type:decimal;
- margin-left:15px
-}
-.bodywrapper ol.a >li {
- list-style-type:lower-alpha;
-}
-.bodywrapper ol.A >li {
- list-style-type:upper-alpha;
-}
-.bodywrapper ol.i >li {
- list-style-type:lower-roman;
-}
-.bodywrapper ol.I >li {
- list-style-type:upper-roman;
-}
-.body li p {
- margin-top:1em
-}
-blockquote,q {
- quotes:none;
- border-left:10px solid #ddd;
- padding-left:10px
-}
-blockquote:before,blockquote:after,q:before,q:after {
- content:'';
- content:none;
- width:100%
-}
-table {
- border-collapse:collapse;
- border-spacing:0;
- margin-bottom:5px;
- width:100%
-}
-a {
- color:#17a81a;
- text-decoration:none;
- transition-duration:0.3s
-}
-a:hover {
- color:#17a81a
-}
-.main,#footerbar>div {
- max-width:1280px;
- width:95%;
- margin:0 auto
-}
-.main {
- margin-top:80px
-}
-@media (max-width: 1120px) {
- .main,.navbar-header,#footerbar>div {
- width: 100%;
- margin: 0;
- }
- .main .main-rounded {
- padding: 0 15px;
- }
-}
-.main_index {
- background-color:#fff
-}
-.sectionlist {
- margin-bottom:2em
-}
-[class*="col-"] {
- letter-spacing:normal
-}
-.landing,.main_index .row {
- letter-spacing:-0.31em
-}
-.main_index .row>div {
- letter-spacing:normal
-}
-.col-1,.body {
- display:inline-block;
- background-color:#fff;
- padding: 25px 35px 20px 30px;
- -webkit-box-sizing:border-box;
- -moz-box-sizing:border-box;
- -ms-box-sizing:border-box;
- box-sizing:border-box;
-}
-.col-1 h2 {
- font-size:1.8em;
- font-weight:300;
- line-height:1.1;
- margin-bottom:0.83em;
- margin-top:1em
-}
-.icons1of3 img {
- display:inline-block;
- float:left;
- margin-right:0.75em;
- margin-top:-5px;
- width:2.75em
-}
-div.multi-column {
- position:relative
-}
-div.multi-column div {
- display:-moz-inline-box;
- display:inline-block;
- vertical-align:top;
- margin-top:1em;
- margin-right:2em;
- width:16em
-}
-.sidebar {
- display:block;
- position:relative;
- position:sticky;
- float:left;
- -webkit-box-sizing:border-box;
- -moz-box-sizing:border-box;
- -ms-box-sizing:border-box;
- box-sizing:border-box;
- width:20%;
- padding-right:20px
-}
-.sidebar li {
- text-overflow:ellipsis;
- overflow:hidden
-}
-.toc,.sectionlist {
- padding:25px;
- background-color:#fff;
- margin-bottom:1.25em
-}
-.sidebar .sectionlist p {
- margin-bottom:0
-}
-.sectionlist.promo {
- padding:0;
- background-color:#f3f3f4
-}
-.sidebar-content:empty {
- display:none;
- visibility:hidden
-}
-.col-2 h2,.toc h3,.sidebar-content h2,
-.sidebar-content h3,.sectionlist h2,
-.sphinxsidebar {
- position: fixed;
- overflow: scroll;
- overflow-x: hidden;
- overflow-y: hidden;
-}
-.sphinxsidebar h3 {
- font-weight: bold;
- margin-bottom:1em;
-}
-.toc h3 a {
- color:#404244
-}
-.title {
- font-size:2.25em;
- font-weight:300;
- letter-spacing:-1px;
- line-height:1.15em;
- margin-bottom:0.5em;
- word-wrap:break-word
-}
-.navigationbar,col-1 h2 {
- font-size:0.85em
-}
-.navigationbar h1 {
- font-size:2.5em;
- margin-bottom:0.85em;
- margin-top:0.85em
-}
-.navigationbar li {
- display:inline-block;
- margin-right:5px;
- position:relative;
- padding-right:10px;
- color:#585a5c
-}
-.navigationbar ul:last-of-type li a {
- color:#404244
-}
-.sectionlist li, .sphinxsidebar li {
- padding-bottom: 10px;
- line-height: 1.75em;
-}
-.col-1 ul {
- margin-bottom:1.56em
-}
-.bodywrapper li {
- margin-top:0.5em;
- line-height:1.25em
-}
-.bodywrapper li.level2 {
- margin-left:10px;
- margin-top:0.4em;
- font-size:0.9375em;
-}
-.bodywrapper p,
-.bodywrapper dd {
- line-height:1.25em;
- margin:1em 0 1em;
- color:#404244
-}
-.bodywrapper b {
- font-weight:600
-}
-.body ul,.body ol {
- /* margin-bottom:1.5em */
-}
-.bodywrapper ul ul {
- margin-top:0.5em
-}
-.bodywrapper .naviNextPrevious {
- margin-top:25px;
- max-width:100%
-}
-.naviNextPrevious.headerNavi,
-p.naviNextPrevious + p {
- display:none
-}
-.nextPage {
- float:right
-}
-.prevPage:before {
- content:"< "
-}
-.nextPage:after {
- content:" >"
-}
-.navigationbar li a {
- color:#404244
-}
-.navigationbar li:after {
- color:#404244;
- content:"›";
- display:inline-block;
- font-size:1.5em;
- line-height:1;
- position:absolute;
- right:-2px;
- top:-4px
-}
-.sub-navigation {
- margin-top:10px
-}
-.navigationbar li:last-child:after,.sub-navigation li:after {
- content:none
-}
-.navigationbar {
- margin-bottom:10px;
- line-height:1em
-}
-#buildversion {
- margin-bottom:10px;
- font-style:italic;
- font-size:small;
- float:right
-}
-.copy-notice {
- width:75%;
- font-size:0.75em;
- margin:20px 35px 0 10px;
- line-height:1.75em;
- float:right;
- color:#585a5c
-}
-.copy-notice.index {
- margin-top:10px;
- float:none
-}
-li a.active {
- color:#585a5c
-}
-.flowList {
- padding:25px
-}
-.flowListDiv dl {
- -webkit-column-count:1;
- -moz-column-count:1;
- column-count:1
-}
-.flowList dd {
- display:inline-block;
- margin-left:10px;
- width:90%;
- line-height:1.15em;
- overflow-x:hidden;
- text-overflow:ellipsis
-}
-.alphaChar {
- font-size:2em;
- position:absolute
-}
-.flowList.odd {
- background-color:#f9f9f9
-}
-.body ul>li,.doc-column ul>li {
- list-style-image:url("list_arrow.png");
- margin-left:15px;
- color:#404244;
- margin-top:0.65em;
- line-height:1em
-}
-.bodywrapper table p {
- margin:0px;
- padding:0px
-}
-.bodywrapper table p {
- margin:0px;
- padding:0px;
- min-height:1.25em
-}
-.bodywrapper .qmldoc {
- margin-top:0.75em
-}
-.body h2 {
- margin-top: 1.5em;
- font-size:1.75em
-}
-.body h3 {
- font-size:1.35em
-}
-.body h4 {
- font-size:1.15em
-}
-.body p img {
- margin-top:0.75em;
- max-width:100%
-}
-.body .border img {
- box-shadow:3px 3px 8px 3px rgba(200,200,200,0.5)
-}
-.body .border .player {
- box-shadow:3px 3px 8px 3px rgba(200,200,200,0.5)
-}
-.body p.figCaption {
- transform:translateY(-30px);
- color:#606366;
- font-size:95%;
- margin-left:3px;
- font-style:italic
-}
-.body table {
- width:initial;
- vertical-align:initial
-}
-table .odd {
- background-color:#f9f9f9
-}
-table thead {
- text-align:left;
- padding-left:20px
-}
-table,table td,table th {
- border:1px solid #eee
-}
-table td,table th {
- padding:5px 20px;
- line-height:1.3
-}
-.body .fixed table td {
- min-width:50%;
- width:50%
-}
-table.alignedsummary,table.propsummary {
- width:initial
-}
-table.valuelist td.tblval {
- font-size:0.75em
-}
-div.main_index .row {
- border-bottom:10px solid #f3f3f4
-}
-div.main_index .row {
- position:relative
-}
-div.main_index .row>div {
- display:inline-block;
- width:50%;
- vertical-align:top;
- padding:2em 3em;
- -webkit-box-sizing:border-box;
- -moz-box-sizing:border-box;
- -ms-box-sizing:border-box;
- box-sizing:border-box
-}
-div.main_index h2 {
- font-size:2.1875em;
- margin-bottom:1em
-}
-#search_bar {
- width:40%;
- float:right
-}
-div.main_index .row:after {
- content:"";
- position:absolute;
- top:0;
- right:50%;
- height:100%;
- width:10px;
- background-color:#f3f3f4
-}
-div.table {
- overflow-x:auto
-}
-.body tr > td > pre {
- font-size:0.75em
-}
-p.qt_commercial {
- border:3px solid #5caa15;
- margin:0 auto;
- padding:15px;
- width:28%;
- text-align:center;
- clear:both
-}
-h1.qt_commercial {
- padding:20px;
- background-color:#5caa15;
- display:inline;
- float:right;
- font-size:1.25em;
- line-height:1.25em;
- height:1.25em;
- color:#fff
-}
-div.qt_commercial {
- border-top:5px solid #5caa15;
- margin-bottom:50px
-}
-div.pre {
- position:relative;
- height:auto
-}
-pre, .LegaleseLeft {
- background-color:#222840;
- color:#fff;
- display:block;
- font-family:"Droid Sans Mono";
- line-height:1.5;
- overflow-x:auto;
- margin-bottom:25px;
- padding:25px;
- margin-top:0.75em;
- font-size: .8em;
-}
-.bodywrapper .LegaleseLeft p {
- color:#fff;
- white-space: pre-wrap
-}
-pre .str,code .str {
- color:#aaaaaa
-}
-pre .kwd,code .kwd {
- color:#ffff55
-}
-pre .com,code .com {
- color:#55ffff
-}
-pre .typ,code .typ {
- color:#4f9d08
-}
-pre a .typ,code a .typ {
- color:#21be2b
-}
-pre .lit,code .lit {
- color:#ff55ff
-}
-pre .pun,code .pun {
- color:#fff
-}
-pre .pln,code .pln {
- color:#fff
-}
-@media print {
- pre {
- background-color:#eee !important
- }
- pre .str,code .str {
- color:#060
- }
- pre .kwd,code .kwd{
- color:#006;
- font-weight:bold
- }
- pre .com,code .com {
- color:#600
- }
- pre .typ,code .typ {
- color:#404;
- font-weight:bold
- }
- pre .lit,code .lit {
- color:#044
- }
- pre .pun,code .pun {
- color:#440
- }
- pre .pln,code .pln {
- color:#000
- }
-}
-pre.wrap {
- white-space:pre-wrap
-}
-pre span.wrap {
- display:none;
- background:url("wrap.png") no-repeat;
- right:0;
- top:2px;
- position:absolute;
- width:20px;
- height:14px;
- margin:4px;
- opacity:0.65
-}
-
-span.pre {
- color: #09102d;
-}
-
-span.wrap:hover {
- opacity:1
-}
-span.wrap:active {
- opacity:0.75
-}
-.copy_text {
- background-color:#46a2da;
- color:#fff;
- border:2px solid #46a2da;
- padding:10px 16px;
- margin-left:-10px;
- margin-top:-50px;
- position:absolute;
- opacity:0;
- cursor:pointer;
- float:right
-}
-.copy_text:hover {
- background-color:#fff;
- color:#46a2da
-}
-code,.codelike {
- font-family:"Droid Sans Mono"
-}
-#detailed-description .function dt > code,
-#detailed-description .function dt > em {
- font-weight:bold
-}
-h3.fn code {
- font-size:0.75em;
- float:right;
- background-color:#eee;
- padding:3px;
- margin: 3px 0 0 20px
-}
-pre:hover>.copy_text {
- display:inline-block;
- opacity:1;
- transition:0.5s ease
-}
-#main_title_bar {
- background:url("pyside-logo.png") no-repeat;
- background-size:100%;
- width:366px;
- height:86px;
- margin:15px 0 15px 0
-}
-#main_title_bar h1 {
- visibility:hidden
-}
-#main_title_bar .search_bar {
- letter-spacing:normal;
- width:50%;
- display:inline-block;
- -webkit-box-sizing:border-box;
- -moz-box-sizing:border-box;
- -ms-box-sizing:border-box;
- box-sizing:border-box;
- vertical-align:middle
-}
-#main_title_bar h1 {
- letter-spacing:normal;
- display:inline-block;
- -webkit-box-sizing:border-box;
- -moz-box-sizing:border-box;
- -ms-box-sizing:border-box;
- box-sizing:border-box;
- vertical-align:middle
-}
-#main_title_bar .search_bar * {
- letter-spacing:normal;
- padding:0;
- margin:0;
- border:none
-}
-#sidebar-toggle,#toc-toggle {
- display:none
-}
-@media (max-width: 980px) {
- body {
- font-size:calc-em(14px)
- }
- #main_title_bar>h1,#main_title_bar .search_bar {
- width:100%
- }
- #main_title_bar .search_bar {
- margin-bottom:15px
- }
- .main {
- margin-top:0px
- }
- .main_index .row {
- border:none !important
- }
- .title {
- font-size:1.5em;
- font-weight:400;
- word-wrap:break-word
- }
- .col-1,.body,.naviNextPrevious,.sidebar {
- padding:10px
- }
- .sidebar {
- position:relative;
- padding-top:0
- }
- .search .sidebar {
- display:none;
- visibility:hidden
- }
- .col-2 h2,.toc h3,.sidebar-content h2,.sidebar-content h3,.sectionlist h2 {
- text-align:center;
- margin-bottom:5px
- }
- div.main_index .row:after {
- content:none
- }
- div.main_index .row>div {
- display:block !important;
- width:100%;
- padding:15px;
- margin:0
- }
- .body,.sidebar,.col-1 {
- width:100%
- }
- .sidebar-content,.col-2,.toc {
- background-color:#fff;
- margin-bottom:1em;
- padding:20px
- }
- #sidebar-toggle,#toc-toggle {
- display:block
- }
- #sidebar-toggle.collapsed + h2 {
- display:block
- }
- .bodywrapper p {
- margin-bottom:1em;
- max-width:100%
- }
- table td,table th {
- padding:5px 5px
- }
- .sectionlist {
- padding:0
- }
- .sidebar > .sectionlist {
- padding:20px
- }
- .sectionlist.promo {
- max-width:46%;
- margin:0 auto 1em auto;
- float:left;
- padding:0 2%
- }
- .sidebar .sidebar-content {
- clear:both
- }
- .copy-notice {
- float:none;
- width:initial
- }
-}
-[id]:target > *:first-child,
-dt[id]:target {
- -webkit-animation:highlighter 3s;
- animation:highlighter 3s
-}
-@-webkit-keyframes highlighter {
- 25% {
- background-color:#d1e8f6;
- color:#444
- }
- 75% {
- background-color:#d1e8f6;
- color:#444
- }
-}
-@keyframes highlighter {
- 25% {
- background-color:#d1e8f6;
- color:#444
- }
- 75% {
- background-color:#d1e8f6;
- color:#444
- }
-}
-@-webkit-keyframes copypaste {
- 25% {
- opacity:1
- }
- 100% {
- border-radius:10px;
- margin-top:-50px;
- opacity:1
- }
-}
-@keyframes copypaste {
- 25% {
- opacity:1
- }
- 100% {
- border-radius:10px;
- margin-top:-50px;
- opacity:1
- }
-}
-#footer {
- clear:both
-}
-.footer-social i {
- font-family: "social-icons";
- font-style: normal;
- font-size:150%;
- margin: .55em;
- color: #cecfd5
-}
-.footer-social i:hover {
- color: #eee
-}
-.footer-social .icon-twitter:before {
- content: '\f099'
-}
-.footer-social .icon-facebook:before {
- content: '\f09a'
-}
-.footer-social .icon-youtube:before {
- content: '\f16a'
-}
-.menuextraslanguages {
- display:none;
- visibility:hidden
-}
-form.gsc-search-box {
- font-size: 25px !important;
- margin-top: 0 !important;
- margin-right: 0 !important;
- margin-bottom: 4px !important;
- margin-left: 0 !important;
- width: 102.5% !important;
-}
-table.gsc-search-box {
- border-style: none !important;
- border-width: 0 !important;
- border-spacing: 0 0 !important;
- width: 100% !important;
- margin-bottom: 2px !important;
-}
-
-table.gsc-search-box td {
- vertical-align: middle !important;
-}
-
-table.gsc-search-box td.gsc-input {
- padding-right: 0px !important;
-}
-table.gsc-search-box td.gsc-input input {
- background-position: 10px center !important;
-}
-
-td.gsc-search-button {
- width: 1% !important;
-}
-
-td.gsc-clear-button {
- width: 14px !important;
- visibility:hidden !important;
- display:none !important;
-}
-table.gsc-branding td,
-table.gsc-branding {
- margin: 0 0 0 0 !important;
- padding: 0 0 0 0 !important;
- border: none !important;
-}
-
-table.gsc-branding {
- border-style: none !important;
- border-width: 0 !important;
- border-spacing: 0 0 !important;
- width: 100% !important;
-}
-
-.gsc-branding-text {
- color: #676767 !important;
-}
-
-td.gsc-branding-text {
- vertical-align: top !important;
-}
-td.gsc-branding-text div.gsc-branding-text {
- padding-bottom: 2px !important;
- text-align: right !important;
- font-size: 11px !important;
- margin-right: 2px !important;
-}
-
-td.gsc-branding-img {
- width: 65px !important;
- vertical-align: bottom !important;
-}
-
-img.gsc-branding-img {
- padding-top: 1px !important;
- margin: 0 0 0 0 !important;
- padding-right: 0 !important;
- padding-left: 0 !important;
- padding-bottom: 0 !important;
- border: none !important;
- display: inline !important;
-}
-
-input.gsc-search-button {
- background-color: white !important;
- height: 35px !important;
- width: 25px !important;
- color: transparent !important;
- background-image: url("doc_search.png") !important;
- background-size: 25px auto;
- background-position: 0px 5px;
- background-repeat: no-repeat;
- margin-left: -43px !important;
- overflow: hidden;
- min-width: 20px !important;
-}
-
-input.gsc-search-button:hover {
- cursor: pointer;
-}
-
-input.gsc-search-button:focus {
- outline: none;
- box-shadow: none;
-}
-
-.gsc-search-box-tools .gsc-clear-button {
- display: none !important;
- visibility: none !important;
-}
-
-.gsc-overflow-hidden {
- overflow: hidden !important;
-}
-
-input.gsc-input {
- background-color: #fff !important;
- border: 1px solid #d6d6d6 !important;
- box-sizing: border-box !important;
- -moz-box-sizing: border-box !important;
- color: #868482 !important;
- outline: 0 none !important;
- padding: 9px 10px 10px !important;
- transition: color 0.5s ease 0s, box-shadow 0.5s ease 0s, background-color 0.5s ease 0s !important;
-}
-
-input {
- font-family: 'Titillium Web', Arial, Helvetica, sans-serif !important;
- line-height: 1.5 !important;
- font-weight: 300 !important;
- vertical-align:middle
-}
-
-input:focus {
- border-color: #46a2da;
- box-shadow: 0 0 5px #46a2da;
- color: #000;
-}
-
-.animation {
- width: 100%;
- border-style: none;
- border-width: 0
-}
-
-.player {
- width: auto;
- position: relative;
- display: table;
- margin-bottom:1.5em;
-}
-
-.playcontrol {
- display: none;
- background: url("play_icon.svg") no-repeat center,
- linear-gradient(
- rgba(0,0,0,0.15), rgba(0,0,0,0.15)
- );
- background-size: 25%;
- width: 100%;
- height: 100%;
- position: absolute;
- left: 0%;
- right: 0%;
- top: 0%;
- bottom: 0%;
- margin: auto
-}
-
-/* expand/collapse code sections */
-pre input {
- display:none;
- visibility:hidden
-}
-pre label {
- display:block;
- margin:-3px 3px 0 -16px;
- text-align:center;
- color:#21be2b;
- float:left;
-}
-pre label:hover {
- color:#fff
-}
-pre label::before {
- font-weight:600;
- font-size:16px;
- content:"+";
- display:inline-block;
- width:16px;
- height:16px
-}
-#ec_expand {
- height:16px;
- overflow:hidden;
- transition:height 0.35s;
-}
-#ec_expand::before {
- content:"...*/";
- color:#aaa;
- background-color:#3a4055;
- z-index:99 !important;
- right:25px;
- position:absolute
-}
-#ec_toggle:checked ~ #ec_expand {
- height:initial
-}
-#ec_toggle:checked ~ #ec_expand::before {
- content:""
-}
-#ec_toggle:checked ~ label::before {
- content:"-"
-}
-
-/* permalinks */
-h1:hover > .headerlink,
-h2:hover > .plink,
-h2:hover > .headerlink,
-h3:hover > .plink,
-h3:hover > .headerlink,
-h4:hover > .plink,
-h4:hover > .headerlink,
-h5:hover > .plink,
-h5:hover > .headerlink {
- opacity:1
-}
-a.plink, a.headerlink {
- opacity: 0;
- padding-left: 8px;
- font-size: 0.8em;
- font-weight: 600;
- transition: opacity 180ms ease-in-out
-}
-a.plink::before {
- content:'\00B6'
-}
-
-table.special {
- border: 3px;
- padding: 0px;
- border-collapse: separate;
- border-spacing: 20px;
- line-height: 1.5em;
-}
-
-.special p {
- text-align: center;
- color: #3a4055;
-}
-
-.special a {
- display: block;
- border-bottom: 0;
- text-decoration: none;
-}
-
-.special a:hover {
- border-bottom: 0;
- text-decoration: none;
-}
-
-.special strong {
- color: #17a81a;
- font-size: 110%;
- font-weight: normal;
-}
-
-table.special th,
-table.special td {
- border: 1px solid #888;
- padding-top: 14px;
- padding-bottom: 14px;
- padding-left: 6px;
- padding-right: 5px;
- border-radius: 5px;
- -moz-border-radius: 5px;
- -webkit-border-radius: 5px;
- -khtml-border-radius: 5px;
-}
-
-.special td:hover {
- padding-top: 2px;
- padding-bottom: 2px;
- border-bottom: 4px solid #41cd52;
-}
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/static/pysidelogo.png b/sources/shiboken2/doc/_themes/pysidedocs/static/pysidelogo.png
deleted file mode 100644
index 3a2f2bd17..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/static/pysidelogo.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/static/relbar_bg.png b/sources/shiboken2/doc/_themes/pysidedocs/static/relbar_bg.png
deleted file mode 100644
index 4036733a7..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/static/relbar_bg.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/_themes/pysidedocs/theme.conf b/sources/shiboken2/doc/_themes/pysidedocs/theme.conf
deleted file mode 100644
index 01a4dd4a1..000000000
--- a/sources/shiboken2/doc/_themes/pysidedocs/theme.conf
+++ /dev/null
@@ -1,7 +0,0 @@
-[theme]
-inherit = default
-stylesheet = pyside.css
-pygments_style = none
-
-[options]
-nosidebar = false
diff --git a/sources/shiboken2/doc/conf.py.in b/sources/shiboken2/doc/conf.py.in
deleted file mode 100644
index e158abbbe..000000000
--- a/sources/shiboken2/doc/conf.py.in
+++ /dev/null
@@ -1,160 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# PyQtB documentation build configuration file, created by
-# sphinx-quickstart on Wed Apr 22 15:04:20 2009.
-#
-# This file is execfile()d with the current directory set to its containing dir.
-#
-# Note that not all possible configuration values are present in this
-# autogenerated file.
-#
-# All configuration values have a default; values that are commented out
-# serve to show the default.
-
-import sys, os
-
-# If extensions (or modules to document with autodoc) are in another directory,
-# add these directories to sys.path here. If the directory is relative to the
-# documentation root, use os.path.abspath to make it absolute, like shown here.
-#sys.path.append(os.path.abspath('.'))
-
-# -- General configuration -----------------------------------------------------
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.ifconfig',
-'sphinx.ext.coverage']
-
-rst_epilog = """
-.. |project| replace:: Shiboken
-"""
-
-# Add any paths that contain templates here, relative to this directory.
-templates_path = ['@CMAKE_CURRENT_SOURCE_DIR@/_templates']
-
-# The suffix of source filenames.
-source_suffix = '.rst'
-
-# The encoding of source files.
-source_encoding = 'utf-8'
-
-# The master toctree document.
-master_doc = 'index'
-
-# General information about the project.
-project = u'Shiboken'
-copyright = u'© 2018 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/license/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.'
-
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
-version = '@shiboken_VERSION@'
-# The full version, including alpha/beta/rc tags.
-release = '@shiboken_VERSION@'
-
-# The language for content autogenerated by Sphinx. Refer to documentation
-# for a list of supported languages.
-#language = None
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
-
-# List of documents that shouldn't be included in the build.
-#unused_docs = []
-
-# List of directories, relative to source directory, that shouldn't be searched
-# for source files.
-exclude_trees = ['_build']
-
-# The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
-
-# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
-
-
-# -- Options for HTML output ---------------------------------------------------
-
-# The theme to use for HTML and HTML Help pages. Major themes that come with
-# Sphinx are currently 'default' and 'sphinxdoc'.
-html_theme = 'pysidedocs'
-
-# Theme options are theme-specific and customize the look and feel of a theme
-# further. For a list of options available for each theme, see the
-# documentation.
-#html_theme_options = {
-#}
-
-# Add any paths that contain custom themes here, relative to this directory.
-html_theme_path = ['@CMAKE_CURRENT_SOURCE_DIR@/_themes']
-
-# The name for this set of Sphinx documents. If None, it defaults to
-# "<project> v<release> documentation".
-#html_title = None
-
-# A shorter title for the navigation bar. Default is the same as html_title.
-#html_short_title = None
-
-# The name of an image file (relative to this directory) to place at the top
-# of the sidebar.
-#html_logo = None
-
-# The name of an image file (within the static path) to use as favicon of the
-# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
-# pixels large.
-#html_favicon = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
-#html_static_path = ['@CMAKE_CURRENT_SOURCE_DIR@/_static']
-
-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
-# using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
-
-# Custom sidebar templates, maps document names to template names.
-#html_sidebars = { '' : ''}
-
-# Additional templates that should be rendered to pages, maps page names to
-# template names.
-#html_additional_pages = { 'index' : 'index.html'}
-
-# If false, no module index is generated.
-html_use_modindex = False
-
-# If false, no index is generated.
-html_use_index = False
-
-# If true, the index is split into individual pages for each letter.
-html_split_index = False
-
-# If true, links to the reST sources are added to the pages.
-html_show_sourcelink = False
-
-# If true, an OpenSearch description file will be output, and all pages will
-# contain a <link> tag referring to it. The value of this option must be the
-# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
-
-# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = ''
diff --git a/sources/shiboken2/doc/considerations.rst b/sources/shiboken2/doc/considerations.rst
deleted file mode 100644
index 3488c3407..000000000
--- a/sources/shiboken2/doc/considerations.rst
+++ /dev/null
@@ -1,183 +0,0 @@
-.. _words-of-advice:
-
-***************
-Words of Advice
-***************
-
-When writing or using Python bindings there is some things you must keep in mind.
-
-
-.. _duck-punching-and-virtual-methods:
-
-Duck punching and virtual methods
-=================================
-
-The combination of duck punching, the practice of altering class characteristics
-of already instantiated objects, and virtual methods of wrapped C++ classes, can
-be tricky. That was an optimistic statement.
-
-Let's see duck punching in action for educational purposes.
-
- .. code-block:: python
-
- import types
- import Binding
-
- obj = Binding.CppClass()
-
- # CppClass has a virtual method called 'virtualMethod',
- # but we don't like it anymore.
- def myVirtualMethod(self_obj, arg):
- pass
-
- obj.virtualMethod = types.MethodType(myVirtualMethod, obj, Binding.CppClass)
-
-
-If some C++ code happens to call `CppClass::virtualMethod(...)` on the C++ object
-held by "obj" Python object, the new duck punched "virtualMethod" method will be
-properly called. That happens because the underlying C++ object is in fact an instance
-of a generated C++ class that inherits from `CppClass`, let's call it `CppClassWrapper`,
-responsible for receiving the C++ virtual method calls and finding out the proper Python
-override to which handle such a call.
-
-Now that you know this, consider the case when C++ has a factory method that gives you
-new C++ objects originated somewhere in C++-land, in opposition to the ones generated in
-Python-land by the usage of class constructors, like in the example above.
-
-Brief interruption to show what I was saying:
-
- .. code-block:: python
-
- import types
- import Binding
-
- obj = Binding.createCppClass()
- def myVirtualMethod(self_obj, arg):
- pass
-
- # Punching a dead duck...
- obj.virtualMethod = types.MethodType(myVirtualMethod, obj, Binding.CppClass)
-
-
-The `Binding.createCppClass()` factory method is just an example, C++ created objects
-can pop out for a number of other reasons. Objects created this way have a Python wrapper
-holding them as usual, but the object held is not a `CppClassWrapper`, but a regular
-`CppClass`. All virtual method calls originated in C++ will stay in C++ and never reach
-a Python virtual method overridden via duck punching.
-
-Although duck punching is an interesting Python feature, it don't mix well with wrapped
-C++ virtual methods, specially when you can't tell the origin of every single wrapped
-C++ object. In summary: don't do it!
-
-
-.. _pyside-old-style-class:
-
-Python old style classes and PySide
-===================================
-
-Because of some architectural decisions and deprecated Python types.
-Since PySide 1.1 old style classes are not supported with multiple inheritance.
-
-Below you can check the examples:
-
-Example with old style class:
-
- .. code-block:: python
-
- from PySide2 import QtCore
-
- class MyOldStyleObject:
- pass
-
- class MyObject(QtCore, MyOldStyleObject):
- pass
-
-
-this example will raise a 'TypeError' due to the limitation on PySide, to fix
-this you will need use the new style class:
-
-
- .. code-block:: python
-
- from PySide2 import QtCore
-
- class MyOldStyleObject(object):
- pass
-
- class MyObject(QtCore, MyOldStyleObject):
- pass
-
-
-All classes used for multiple inheritance with other PySide types need to have
-'object' as base class.
-**************************
-Frequently Asked Questions
-**************************
-
-This is a list of Frequently Asked Questions about |project|.
-Feel free to suggest new entries using our `Mailing list`_ or our IRC channel!
-
-General
-=======
-
-What is Shiboken?
------------------
-
-Shiboken is a Generator Runner plugin that outputs C++ code for CPython
-extensions.
-The first version of PySide had source code based on Boost templates.
-It was easier to produce code but a paradigm change was needed, as the next
-question explains.
-
-
-Why did you switch from Boost.Python to Shiboken?
--------------------------------------------------
-
-The main reason was the size reduction. Boost.Python makes excessive use of
-templates resulting in a significant increase of the binaries size.
-On the other hand, as Shiboken generates CPython code, the resulting binaries
-are smaller.
-
-Creating bindings
-=================
-
-Can I wrap non-Qt libraries?
-----------------------------
-
-Yes. Check Shiboken source code for an example (libsample).
-
-
-Is there any runtime dependency on the generated binding?
----------------------------------------------------------
-
-Yes. Only libshiboken, and the obvious Python interpreter
-and the C++ library that is being wrapped.
-
-What do I have to do to create my bindings?
--------------------------------------------
-
-Most of the work is already done by the API Extractor.
-The developer creates a :std:doc:`typesystem <typesystem>`
-file with any customization wanted in
-the generated code, like removing classes or changing method signatures.
-The generator will output the *.h* and *.cpp* files with the CPython code that
-will wrap the target library for python.
-
-
-Is there any recommended build system?
---------------------------------------
-
-Both API Extractor and generator uses and recommends the CMake build system.
-
-Can I write closed-source bindings with the generator?
-------------------------------------------------------
-
-Yes, as long as you use a LGPL version of Qt, due to runtime requirements.
-
-What is 'inject code'?
-----------------------
-
-That's how we call customized code that will be *injected* into the
-generated at specific locations. They are specified inside the typesystem.
-
-.. _`Mailing list`: http://lists.qt-project.org/mailman/listinfo/pyside
diff --git a/sources/shiboken2/doc/dependency-pyside.svg b/sources/shiboken2/doc/dependency-pyside.svg
deleted file mode 100644
index 786bdb8a6..000000000
--- a/sources/shiboken2/doc/dependency-pyside.svg
+++ /dev/null
@@ -1,527 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-<svg
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="900"
- height="560"
- id="svg2"
- sodipodi:version="0.32"
- inkscape:version="0.46"
- version="1.0"
- sodipodi:docname="dependency-pyside.svg"
- inkscape:output_extension="org.inkscape.output.svg.inkscape"
- inkscape:export-filename="/tmp/dependency-pyside.png"
- inkscape:export-xdpi="90"
- inkscape:export-ydpi="90">
- <defs
- id="defs4">
- <marker
- inkscape:stockid="Arrow1Lstart"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow1Lstart"
- style="overflow:visible">
- <path
- id="path3270"
- d="M 0,0 L 5,-5 L -12.5,0 L 5,5 L 0,0 z"
- style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(0.8,0,0,0.8,10,0)" />
- </marker>
- <marker
- inkscape:stockid="Arrow1Lend"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow1Lend"
- style="overflow:visible">
- <path
- id="path3679"
- d="M 0,0 L 5,-5 L -12.5,0 L 5,5 L 0,0 z"
- style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(-0.8,0,0,-0.8,-10,0)" />
- </marker>
- <inkscape:perspective
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective10" />
- </defs>
- <sodipodi:namedview
- id="base"
- pagecolor="#ffffff"
- bordercolor="#666666"
- borderopacity="1.0"
- gridtolerance="10000"
- guidetolerance="10"
- objecttolerance="10"
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:zoom="0.79440331"
- inkscape:cx="-36.66006"
- inkscape:cy="372.04724"
- inkscape:document-units="px"
- inkscape:current-layer="svg2"
- showgrid="false"
- showguides="true"
- inkscape:guide-bbox="true"
- inkscape:window-width="1278"
- inkscape:window-height="949"
- inkscape:window-x="0"
- inkscape:window-y="0">
- <sodipodi:guide
- orientation="1,0"
- position="384.28571,590"
- id="guide2601" />
- <sodipodi:guide
- orientation="1,0"
- position="678.57143,491.42857"
- id="guide2603" />
- <sodipodi:guide
- orientation="1,0"
- position="78.571429,257.14286"
- id="guide2605" />
- <sodipodi:guide
- orientation="1,0"
- position="93.571429,280.71429"
- id="guide7565" />
- <sodipodi:guide
- orientation="1,0"
- position="148.57143,216.42857"
- id="guide7567" />
- </sodipodi:namedview>
- <metadata
- id="metadata7">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <g
- inkscape:label="Layer 1"
- inkscape:groupmode="layer"
- id="layer1"
- transform="translate(-78.088635,-190.95252)" />
- <g
- id="g5394"
- transform="translate(6.1314759,14.304617)">
- <g
- transform="translate(-65.84289,-190.95252)"
- id="g5205">
- <g
- id="g5171">
- <rect
- rx="9.3643799"
- y="338.7739"
- x="678.57141"
- height="73.281754"
- width="274.54263"
- id="rect2393"
- style="fill:#aaeeff;fill-rule:evenodd;stroke:#006078;stroke-width:0.96620417px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- ry="13.104657" />
- <text
- id="text2395"
- y="355.93701"
- x="683.46539"
- style="font-size:16.27989578px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="355.93701"
- x="683.46539"
- id="tspan2397"
- sodipodi:role="line">boost::python</tspan></text>
- <text
- id="text2399"
- y="371.60172"
- x="683.46539"
- style="font-size:8.40044498px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="371.60172"
- x="683.46539"
- id="tspan2401"
- sodipodi:role="line">1.38.0</tspan></text>
- <text
- id="text2403"
- y="387.14166"
- x="683.46539"
- style="font-size:9.33067703px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- id="tspan2435"
- y="387.14166"
- x="683.46539"
- sodipodi:role="line">headers and libraries - compile-time and run-time</tspan></text>
- <text
- id="text2413"
- y="402.4646"
- x="683.46539"
- style="font-size:8.26250458px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="402.4646"
- x="683.46539"
- id="tspan2415"
- sodipodi:role="line">Boost Software License 1.0</tspan></text>
- </g>
- <g
- id="g5193">
- <rect
- rx="8.3239012"
- y="342.86383"
- x="78.571426"
- height="73.282379"
- width="274.18781"
- id="rect2417"
- style="fill:#b3ff80;fill-rule:evenodd;stroke:#2a7800;stroke-width:0.96558368px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- ry="9.2689295" />
- <text
- id="text2419"
- y="359.67014"
- x="88.822823"
- style="font-size:16.27989578px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="359.67014"
- x="88.822823"
- id="tspan2421"
- sodipodi:role="line">Qt 4.5</tspan></text>
- <text
- id="text2423"
- y="375.33484"
- x="88.822823"
- style="font-size:8.40044498px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="375.33484"
- x="88.822823"
- id="tspan2425"
- sodipodi:role="line">4.5</tspan></text>
- <text
- id="text2427"
- y="390.87479"
- x="88.822823"
- style="font-size:9.33067703px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="390.87479"
- x="88.822823"
- id="tspan2429"
- sodipodi:role="line">headers and libraries - compile-time and run-time</tspan></text>
- <text
- id="text2431"
- y="400.84058"
- x="88.822823"
- style="font-size:8.26250458px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="400.84058"
- x="88.822823"
- id="tspan2433"
- sodipodi:role="line">GNU General Public License v3 /</tspan><tspan
- y="411.1687"
- x="88.822823"
- sodipodi:role="line"
- id="tspan2472">GNU Lesser General Public Licence v2.1</tspan></text>
- </g>
- <g
- id="g5120">
- <rect
- y="496.43558"
- x="384.28571"
- height="73.281754"
- width="274.54263"
- id="rect2441"
- style="fill:#e9ddaf;fill-rule:evenodd;stroke:#5f5019;stroke-width:0.96620417px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- ry="13.104635"
- rx="10.404889" />
- <text
- id="text2443"
- y="513.59869"
- x="389.17969"
- style="font-size:16.27989578px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="513.59869"
- x="389.17969"
- id="tspan2445"
- sodipodi:role="line">libapiextractor</tspan></text>
- <text
- id="text2447"
- y="529.26337"
- x="389.17969"
- style="font-size:8.40044498px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="529.26337"
- x="389.17969"
- id="tspan2449"
- sodipodi:role="line">0.1</tspan></text>
- <text
- id="text2451"
- y="544.80334"
- x="389.17969"
- style="font-size:9.33067703px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- id="tspan2453"
- y="544.80334"
- x="389.17969"
- sodipodi:role="line">headers and libraries - compile-time and run-time</tspan></text>
- <text
- id="text2455"
- y="560.12628"
- x="389.17969"
- style="font-size:8.26250458px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="560.12628"
- x="389.17969"
- id="tspan2457"
- sodipodi:role="line">LGPL version 2.1</tspan></text>
- </g>
- <g
- id="g5131">
- <rect
- y="340.72134"
- x="384.28571"
- height="73.281754"
- width="274.54263"
- id="rect2459"
- style="fill:#e9ddaf;fill-rule:evenodd;stroke:#5f5019;stroke-width:0.96620417px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- ry="10.309408"
- rx="9.3644047" />
- <text
- id="text2461"
- y="357.88449"
- x="389.17969"
- style="font-size:16.27989578px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="357.88449"
- x="389.17969"
- id="tspan2463"
- sodipodi:role="line">BoostPythonGenerator</tspan></text>
- <text
- id="text2465"
- y="373.54916"
- x="389.17969"
- style="font-size:8.40044498px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="373.54916"
- x="389.17969"
- id="tspan2467"
- sodipodi:role="line">0.1</tspan></text>
- <text
- id="text2469"
- y="389.08914"
- x="389.17969"
- style="font-size:9.33067703px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- id="tspan2471"
- y="389.08914"
- x="389.17969"
- sodipodi:role="line">Binary executable - compile-time</tspan></text>
- <text
- id="text2473"
- y="404.41208"
- x="389.17969"
- style="font-size:8.26250458px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="404.41208"
- x="389.17969"
- id="tspan2475"
- sodipodi:role="line">LGPL version 2.1</tspan></text>
- </g>
- <g
- id="g5142">
- <rect
- y="191.43562"
- x="384.28571"
- height="73.281754"
- width="274.54263"
- id="rect2523"
- style="fill:#e9ddaf;fill-opacity:1;fill-rule:evenodd;stroke:#5f5019;stroke-width:0.96620417px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- ry="14.285714" />
- <text
- id="text2525"
- y="208.59874"
- x="389.17966"
- style="font-size:16.27989578px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="208.59874"
- x="389.17966"
- id="tspan2527"
- sodipodi:role="line">Qt Python bindings</tspan></text>
- <text
- id="text2529"
- y="224.26344"
- x="389.17966"
- style="font-size:8.40044498px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="224.26344"
- x="389.17966"
- id="tspan2531"
- sodipodi:role="line">0.1</tspan></text>
- <text
- id="text2533"
- y="239.80339"
- x="389.17966"
- style="font-size:9.33067703px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- id="tspan2535"
- y="239.80339"
- x="389.17966"
- sodipodi:role="line">Target</tspan></text>
- <text
- id="text2537"
- y="255.12633"
- x="389.17966"
- style="font-size:8.26250458px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="255.12633"
- x="389.17966"
- id="tspan2539"
- sodipodi:role="line">LGPL version 2.1</tspan></text>
- </g>
- <g
- id="g5182">
- <rect
- rx="10.404877"
- y="648.57843"
- x="384.28571"
- height="73.281754"
- width="274.54263"
- id="rect2563"
- style="fill:#aaeeff;fill-rule:evenodd;stroke:#006078;stroke-width:0.96620417px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- ry="11.287985" />
- <text
- id="text2565"
- y="665.74158"
- x="389.17969"
- style="font-size:16.27989578px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="665.74158"
- x="389.17969"
- id="tspan2567"
- sodipodi:role="line">boost::graph</tspan></text>
- <text
- id="text2569"
- y="681.40625"
- x="389.17969"
- style="font-size:8.40044498px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="681.40625"
- x="389.17969"
- id="tspan2571"
- sodipodi:role="line">1.38.0</tspan></text>
- <text
- id="text2573"
- y="696.94623"
- x="389.17969"
- style="font-size:9.33067703px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- id="tspan2575"
- y="696.94623"
- x="389.17969"
- sodipodi:role="line">headers and libraries - compile-time and run-time</tspan></text>
- <text
- id="text2577"
- y="712.26917"
- x="389.17969"
- style="font-size:8.26250458px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="712.26917"
- x="389.17969"
- id="tspan2579"
- sodipodi:role="line">Boost Software License 1.0</tspan></text>
- </g>
- </g>
- <path
- inkscape:connector-type="polyline"
- id="path2869"
- d="M 212.85114,151.42852 L 368.56822,74.247959"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;marker-start:url(#Arrow1Lstart);marker-end:none;stroke-opacity:1" />
- <path
- inkscape:connector-type="polyline"
- id="path2871"
- d="M 663.60462,147.33826 L 517.61788,74.247959"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;marker-start:url(#Arrow1Lstart);marker-end:none;stroke-opacity:1" />
- <path
- inkscape:connector-type="polyline"
- id="path2877"
- d="M 443.4684,149.28571 L 443.46839,74.247959"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;marker-start:url(#Arrow1Lstart);marker-end:none;stroke-opacity:1" />
- <path
- inkscape:connector-type="polyline"
- id="path2879"
- d="M 443.4684,304.99994 L 443.4684,223.53367"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;marker-start:url(#Arrow1Lstart);marker-end:none;stroke-opacity:1" />
- <path
- inkscape:connector-type="polyline"
- id="path2881"
- d="M 443.4684,457.14279 L 443.4684,379.2479"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;marker-start:url(#Arrow1Lstart);marker-mid:none;marker-end:none;stroke-opacity:1" />
- <rect
- ry="17.142857"
- y="293.85626"
- x="0.48279184"
- height="124.28571"
- width="211.42857"
- id="rect7541"
- style="fill:#e3e2db;stroke:#000000;stroke-opacity:1" />
- <text
- id="text7543"
- y="325.44049"
- x="70.482788"
- style="font-size:20.61732101px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="325.44049"
- x="70.482788"
- id="tspan7545"
- sodipodi:role="line">Boost</tspan></text>
- <text
- id="text7547"
- y="358.37042"
- x="70.482788"
- style="font-size:20.61732101px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="358.37042"
- x="70.482788"
- id="tspan7549"
- sodipodi:role="line">Qt Software</tspan></text>
- <text
- id="text7551"
- y="394.07593"
- x="70.482788"
- style="font-size:20.61732101px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- y="394.07593"
- x="70.482788"
- id="tspan7553"
- sodipodi:role="line">INdT/Nokia</tspan></text>
- <rect
- ry="6.4285707"
- y="307.24911"
- x="15.482792"
- height="22.5"
- width="43.163269"
- id="rect7555"
- style="fill:#aaeeff;fill-opacity:1;stroke:#000000;stroke-width:0.64285713;stroke-opacity:1" />
- <rect
- ry="6.4285707"
- y="341.17767"
- x="15.482792"
- height="22.5"
- width="43.163269"
- id="rect7561"
- style="fill:#b3ff80;fill-opacity:1;stroke:#000000;stroke-width:0.64285713;stroke-opacity:1" />
- <rect
- ry="6.4285707"
- y="376.17767"
- x="15.482792"
- height="22.5"
- width="43.163269"
- id="rect7563"
- style="fill:#e9ddaf;fill-opacity:1;stroke:#000000;stroke-width:0.64285713;stroke-opacity:1" />
- </g>
-</svg>
diff --git a/sources/shiboken2/doc/examples/index.rst b/sources/shiboken2/doc/examples/index.rst
deleted file mode 100644
index 92a64195e..000000000
--- a/sources/shiboken2/doc/examples/index.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-Examples
-========
-
-C++ examples
-------------
-
-.. toctree::
-
- samplebinding.rst
diff --git a/sources/shiboken2/doc/examples/samplebinding.rst b/sources/shiboken2/doc/examples/samplebinding.rst
deleted file mode 100644
index a53b32bac..000000000
--- a/sources/shiboken2/doc/examples/samplebinding.rst
+++ /dev/null
@@ -1,246 +0,0 @@
-SampleBinding Example
-***********************
-
-This example showcases how you can use Shiboken to generate CPython-based
-binding code for a C++ library. The C++ library is called :code:`Universe`,
-with two classes: :code:`Icecream` and :code:`Truck`. Ice-creams are
-characterized by their flavor, and :code:`Truck` serves as a vehicle of
-:code:`Icecream` distribution for kids in a neighborhood.
-
-First, let's look at the definition of the two classes:
-
-.. code-block:: cpp
- :caption: icecream.h
-
- class Icecream
- {
- public:
- Icecream(const std::string &flavor);
- virtual Icecream *clone();
- virtual ~Icecream();
- virtual const std::string getFlavor();
-
- private:
- std::string m_flavor;
- };
-
-.. code-block:: cpp
- :caption: truck.h
-
- class Truck {
- public:
- Truck(bool leaveOnDestruction = false);
- Truck(const Truck &other);
- Truck& operator=(const Truck &other);
- ~Truck();
-
- void addIcecreamFlavor(Icecream *icecream);
- void printAvailableFlavors() const;
-
- bool deliver() const;
- void arrive() const;
- void leave() const;
-
- void setLeaveOnDestruction(bool value);
- void setArrivalMessage(const std::string &message);
-
- private:
- void clearFlavors();
-
- bool m_leaveOnDestruction = false;
- std::string m_arrivalMessage = "A new icecream truck has arrived!\n";
- std::vector m_flavors;
- };
-
-Here's a summary of what's included in the :code:`Universe` library:
-
-* The :code:`Icecream` polymorphic type, which is intended to be overridden.
-* The :code:`Icecream::getFlavor()` method returns the flavor depending on the
- actual derived type.
-* The :code:`Truck` value type that contains pointers, hence the copy
- constructor.
-* :code:`Truck` stores the :code:`Icecream` objects in a vector, which can be
- modified via :code:`Truck::addIcecreamFlavor()`.
-* The :code:`Truck’s` arrival message can be customized using its
- :code:`setArrivalMessage()` method.
-* The :code:`Truck::deliver()` method tells us if the ice-cream delivery was
- successful.
-
-Shiboken typesystem
-====================
-
-Now that the library definitions are in place, the Shiboken generator needs a
-header file that includes the types we are interested in:
-
-.. code-block:: cpp
- :caption: bindings.h
-
- #ifndef BINDINGS_H
- #define BINDINGS_H
- #include "icecream.h"
- #include "truck.h"
- #endif // BINDINGS_H
-
-In addition, Shiboken also requires an XML-based typesystem file that defines the
-relationship between C++ and Python types:
-
-.. code-block:: xml
- :caption: bindings.xml
-
- <?xml version="1.0"?>
- <typesystem package="Universe">
- <primitive-type name="bool"/>
- <primitive-type name="std::string"/>
- <object-type name="Icecream">
- <modify-function signature="clone()">
- <modify-argument index="0">
- <define-ownership owner="c++"/>
- </modify-argument>
- </modify-function>
- </object-type>
- <value-type name="Truck">
- <modify-function signature="addIcecreamFlavor(Icecream*)">
- <modify-argument index="1">
- <define-ownership owner="c++"/>
- </modify-argument>
- </modify-function>
- </value-type>
- </typesystem>
-
-One important thing to notice here is that we declare :code:`"bool"` and
-:code:`"std::string"` as primitive types. These types are used by some of the
-C++ methods as parameters or return types, so Shiboken must know about them.
-Then, Shiboken can generate relevant conversion code between C++ and Python, although
-most C++ primitive types are handled by Shiboken without additional code.
-
-Next, we declare the two aforementioned classes. One of them as an
-“object-type” and the other as a “value-type”. The main difference is that
-object-types are passed around in generated code as pointers, whereas
-value-types are copied (value semantics).
-
-By specifying the names of these classes in the typesystem file, Shiboken
-automatically tries to generate bindings for all methods of those
-classes. You need not mention all the methods manually in the XML file, unless
-you want to modify them.
-
-Object ownership rules
-=======================
-
-Shiboken doesn't know if Python or C++ are responsible for freeing the C++ objects that were
-allocated in the Python code, and assuming this might lead to errors.
-There can be cases where Python should release the C++ memory when the reference count of the
-Python object becomes zero, but it should never delete the underlying C++ object just from
-assuming that it will not be deleted by underlying C++ library, or if it's maybe parented to
-another object (like QWidgets).
-
-In our case, the :code:`clone()` method is only called inside the C++ library,
-and we assume that the C++ code takes care of releasing the cloned object.
-
-As for :code:`addIcecreamFlavor()`, we know that a :code:`Truck` owns the
-:code:`Icecream` object, and will remove it once the :code:`Truck` is
-destroyed. That's why the ownership is set to “c++” in the typesystem file,
-so that the C++ objects are not deleted when the corresponding Python names
-go out of scope.
-
-Build
-=====
-
-To build the :code:`Universe` custom library and then generate bindings for it,
-use the :file:`CMakeLists.txt` file provided with the example. Later, you can reuse
-the file for your own libraries with minor changes.
-
-Now, run the :command:`"cmake ."` command from the prompt to configure the
-project and build with the toolchain of your choice; we recommend the
-‘(N)Makefiles’ generator.
-
-As a result, you end up with two shared libraries:
-:file:`libuniverse.(so/dylib/dll)` and :file:`Universe.(so/pyd)`. The former is
-the custom C++ library, and the latter is the Python module to import in your
-Python script.
-
-For more details about these platforms, see the :file:`README.md` file.
-
-Use the Python module
-=====================
-
-The following script uses the :code:`Universe` module, derives a few types from
-:code:`Icecream`, implements virtual methods, instantiates objects, and much more:
-
-.. code-block:: python
- :caption: main.py
-
- from Universe import Icecream, Truck
-
- class VanillaChocolateIcecream(Icecream):
- def __init__(self, flavor=""):
- super(VanillaChocolateIcecream, self).__init__(flavor)
-
- def clone(self):
- return VanillaChocolateIcecream(self.getFlavor())
-
- def getFlavor(self):
- return "vanilla sprinked with chocolate"
-
- class VanillaChocolateCherryIcecream(VanillaChocolateIcecream):
- def __init__(self, flavor=""):
- super(VanillaChocolateIcecream, self).__init__(flavor)
-
- def clone(self):
- return VanillaChocolateCherryIcecream(self.getFlavor())
-
- def getFlavor(self):
- base_flavor = super(VanillaChocolateCherryIcecream, self).getFlavor()
- return base_flavor + " and a cherry"
-
- if __name__ == '__main__':
- leave_on_destruction = True
- truck = Truck(leave_on_destruction)
-
- flavors = ["vanilla", "chocolate", "strawberry"]
- for f in flavors:
- icecream = Icecream(f)
- truck.addIcecreamFlavor(icecream)
-
- truck.addIcecreamFlavor(VanillaChocolateIcecream())
- truck.addIcecreamFlavor(VanillaChocolateCherryIcecream())
-
- truck.arrive()
- truck.printAvailableFlavors()
- result = truck.deliver()
-
- if result:
- print("All the kids got some icecream!")
- else:
- print("Aww, someone didn't get the flavor they wanted...")
-
- if not result:
- special_truck = Truck(truck)
- del truck
-
- print("")
- special_truck.setArrivalMessage("A new SPECIAL icecream truck has arrived!\n")
- special_truck.arrive()
- special_truck.addIcecreamFlavor(Icecream("SPECIAL *magical* icecream"))
- special_truck.printAvailableFlavors()
- special_truck.deliver()
- print("Now everyone got the flavor they wanted!")
- special_truck.leave()
-
-After importing the classes from the :code:`Universe` module, it derives two
-types from :code:`Icecream` for different “flavors”. It then creates a
-:code:`truck` to deliver some regular flavored Icecreams and two special ones.
-
-If the delivery fails, a new :code:`truck` is created with the old flavors
-copied over, and a new *magical* flavor that will surely satisfy all customers.
-
-Try running it to see if the ice creams are delivered.
-
-.. note::
- You can find the sources for this example under
- :file:`<PYTHON_ENV_ROOT>/site-packages/lib/PySide2/examples/samplebinding`.
-
-Refer to the following topics for detailed information about using Shiboken:
- * :doc:`Type System Variables <../typesystem_variables>`
- * :doc:`User Defined Type Conversion <../typesystem_converters>`
- * :doc:`Object ownership <../typesystem_ownership>`
- * :doc:`Considerations and Frequently Asked Questions <../considerations>`
diff --git a/sources/shiboken2/doc/gettingstarted.rst b/sources/shiboken2/doc/gettingstarted.rst
deleted file mode 100644
index caeb5a909..000000000
--- a/sources/shiboken2/doc/gettingstarted.rst
+++ /dev/null
@@ -1,61 +0,0 @@
-Getting started
-===============
-
-Building from source
---------------------
-
-This step is focused on building Shiboken from source, both the Generator and Python module.
-Please notice that these are built when you are building PySide from source too, so there is no
-need to continue if you already have a built PySide.
-
-General Requirements
-^^^^^^^^^^^^^^^^^^^^
-
- * **Python**: 3.5+ and 2.7
- * **Qt:** 5.12+ is recommended
- * **libclang:** The libclang library, recommended: version 6 for Shiboken2 5.12.
- Prebuilt versions of it can be `downloaded here`_.
- * **CMake:** 3.1+ is needed.
-
-.. _downloaded here: http://download.qt.io/development_releases/prebuilt/libclang/
-
-Simple build
-^^^^^^^^^^^^
-
-If you need only Shiboken Generator, a simple build run would look like this::
-
- python setup.py install --qmake=/path/to/qmake \
- --build-tests \
- --parallel=8 \
- --verbose-build \
- --internal-build-type=shiboken2-generator
-
-The same can be used for the module, changing the value of ``internal-build-type`` to
-``shiboken2-module``.
-
-Using the wheels
-----------------
-
-Installing ``pyside2`` or ``shiboken2`` from pip **does not** install ``shiboken2_generator``,
-because the wheels are not on PyPi.
-
-You can get the ``shiboken2_generator`` wheels from Qt servers, and you can still install it
-via ``pip``::
-
- pip install \
- --index-url=http://download.qt.io/official_releases/QtForPython/ \
- --trusted-host download.qt.io \
- shiboken2 pyside2 shiboken2_generator
-
-
-The ``whl`` package cannot automatically discover in your system the location for:
-
-* Clang installation,
-* ``qmake`` location with the same version as the one described in the wheel,
-* Qt libraries with the same package version.
-
-So using this process requires you to manually modify the variables:
-
-* ``CLANG_INSTALL_DIR`` must be set to where the libraries are,
-* ``PATH`` must include the location for a ``qmake`` with the same Qt version as the package,
-* ``LD_LIBRARY_PATH`` including the Qt libraries and Clang libraries paths.
diff --git a/sources/shiboken2/doc/images/.directory b/sources/shiboken2/doc/images/.directory
deleted file mode 100644
index e65475f65..000000000
--- a/sources/shiboken2/doc/images/.directory
+++ /dev/null
@@ -1,3 +0,0 @@
-[Dolphin]
-ShowPreview=true
-Timestamp=2009,5,5,17,43,26
diff --git a/sources/shiboken2/doc/images/bindinggen-development.png b/sources/shiboken2/doc/images/bindinggen-development.png
deleted file mode 100644
index 5931b126a..000000000
--- a/sources/shiboken2/doc/images/bindinggen-development.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/images/bindinggen-development.svg b/sources/shiboken2/doc/images/bindinggen-development.svg
deleted file mode 100644
index 591e1f2d1..000000000
--- a/sources/shiboken2/doc/images/bindinggen-development.svg
+++ /dev/null
@@ -1,542 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="640"
- height="200"
- id="svg2"
- sodipodi:version="0.32"
- inkscape:version="0.92.2 2405546, 2018-03-11"
- version="1.0"
- sodipodi:docname="bindinggen-development.svg"
- inkscape:output_extension="org.inkscape.output.svg.inkscape"
- inkscape:export-filename="bindinggen-development.png"
- inkscape:export-xdpi="90"
- inkscape:export-ydpi="90">
- <defs
- id="defs4">
- <marker
- inkscape:stockid="EmptyDiamondL"
- orient="auto"
- refY="0"
- refX="0"
- id="EmptyDiamondL"
- style="overflow:visible">
- <path
- id="path3930"
- d="M 0,-7.0710768 L -7.0710894,0 L 0,7.0710589 L 7.0710462,0 L 0,-7.0710768 z"
- style="fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="scale(0.8,0.8)" />
- </marker>
- <marker
- inkscape:stockid="EmptyTriangleInL"
- orient="auto"
- refY="0"
- refX="0"
- id="EmptyTriangleInL"
- style="overflow:visible">
- <path
- id="path3975"
- d="M 5.77,0 L -2.88,5 L -2.88,-5 L 5.77,0 z"
- style="fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(-0.8,0,0,-0.8,4.8,0)" />
- </marker>
- <marker
- inkscape:stockid="Arrow1Sstart"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow1Sstart"
- style="overflow:visible">
- <path
- id="path3835"
- d="M 0,0 L 5,-5 L -12.5,0 L 5,5 L 0,0 z"
- style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(0.2,0,0,0.2,1.2,0)" />
- </marker>
- <marker
- inkscape:stockid="Arrow1Mend"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow1Mend"
- style="overflow:visible">
- <path
- id="path3832"
- d="M 0,0 L 5,-5 L -12.5,0 L 5,5 L 0,0 z"
- style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(-0.4,0,0,-0.4,-4,0)" />
- </marker>
- <marker
- inkscape:stockid="Tail"
- orient="auto"
- refY="0"
- refX="0"
- id="Tail"
- style="overflow:visible">
- <g
- id="g3859"
- transform="scale(-1.2,-1.2)">
- <path
- id="path3861"
- d="M -3.8048674,-3.9585227 L 0.54352094,0"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3863"
- d="M -1.2866832,-3.9585227 L 3.0617053,0"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3865"
- d="M 1.3053582,-3.9585227 L 5.6537466,0"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3867"
- d="M -3.8048674,4.1775838 L 0.54352094,0.21974226"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3869"
- d="M -1.2866832,4.1775838 L 3.0617053,0.21974226"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3871"
- d="M 1.3053582,4.1775838 L 5.6537466,0.21974226"
- style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- </g>
- </marker>
- <marker
- inkscape:stockid="Arrow2Lend"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow2Lend"
- style="overflow:visible">
- <path
- id="path3636"
- style="font-size:12px;fill-rule:evenodd;stroke-width:0.625;stroke-linejoin:round"
- d="M 8.7185878,4.0337352 L -2.2072895,0.016013256 L 8.7185884,-4.0017078 C 6.97309,-1.6296469 6.9831476,1.6157441 8.7185878,4.0337352 z"
- transform="matrix(-1.1,0,0,-1.1,-1.1,0)" />
- </marker>
- <inkscape:perspective
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective10" />
- </defs>
- <sodipodi:namedview
- id="base"
- pagecolor="#ffffff"
- bordercolor="#666666"
- borderopacity="1.0"
- gridtolerance="10000"
- guidetolerance="10"
- objecttolerance="10"
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:zoom="0.76787377"
- inkscape:cx="286.61779"
- inkscape:cy="101.18182"
- inkscape:document-units="px"
- inkscape:current-layer="g5440"
- showgrid="false"
- inkscape:window-width="1116"
- inkscape:window-height="1042"
- inkscape:window-x="10"
- inkscape:window-y="28"
- showguides="true"
- inkscape:guide-bbox="true"
- inkscape:window-maximized="0">
- <sodipodi:guide
- orientation="1,0"
- position="-557.55608,678.10875"
- id="guide7299"
- inkscape:locked="false" />
- </sodipodi:namedview>
- <metadata
- id="metadata7">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <g
- inkscape:label="Layer 1"
- inkscape:groupmode="layer"
- id="layer1"
- transform="translate(-1758.7331,-2056.8567)">
- <flowRoot
- xml:space="preserve"
- id="flowRoot3229"
- style="font-style:normal;font-weight:normal;line-height:0.01%;font-family:'Bitstream Vera Sans';fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- transform="translate(4.1137413,-2.3429609)"><flowRegion
- id="flowRegion3231"><rect
- id="rect3233"
- width="125.74072"
- height="40.5849"
- x="388.45547"
- y="279.5423" /></flowRegion><flowPara
- id="flowPara3235"
- style="font-size:40px;line-height:1.25"> </flowPara></flowRoot> <g
- id="g5658"
- transform="translate(6.5767925,7.0112479)">
- <g
- transform="matrix(0,-1,1,0,697.50638,3244.256)"
- id="g5624"
- style="">
- <g
- id="g5626"
- transform="matrix(0,-1,1,0,-294.81158,2953.0504)"
- style="">
- <path
- sodipodi:nodetypes="cc"
- inkscape:connector-type="polyline"
- id="path5628"
- d="m 1586.5317,1348.2858 0.091,41.5266"
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- inkscape:connector-curvature="0" />
- <path
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- d="m 1586.7489,1389.4756 7.9979,-9.1068"
- id="path5630"
- inkscape:connector-type="polyline"
- sodipodi:nodetypes="cc"
- inkscape:connector-curvature="0" />
- <path
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- d="m 1586.6031,1389.5063 -7.9979,-9.1069"
- id="path5632"
- inkscape:connector-type="polyline"
- sodipodi:nodetypes="cc"
- inkscape:connector-curvature="0" />
- </g>
- </g>
- <g
- transform="matrix(0,-1,1,0,908.50929,3242.9612)"
- id="g5648"
- style="">
- <g
- id="g5650"
- transform="matrix(0,-1,1,0,-294.81158,2953.0504)"
- style="">
- <path
- sodipodi:nodetypes="cc"
- inkscape:connector-type="polyline"
- id="path5652"
- d="m 1586.5317,1348.2858 0.091,41.5266"
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- inkscape:connector-curvature="0" />
- <path
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- d="m 1586.7489,1389.4756 7.9979,-9.1068"
- id="path5654"
- inkscape:connector-type="polyline"
- sodipodi:nodetypes="cc"
- inkscape:connector-curvature="0" />
- <path
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- d="m 1586.6031,1389.5063 -7.9979,-9.1069"
- id="path5656"
- inkscape:connector-type="polyline"
- sodipodi:nodetypes="cc"
- inkscape:connector-curvature="0" />
- </g>
- </g>
- <g
- id="g5634"
- style="">
- <g
- id="g6271"
- transform="translate(1086.3689,746.93837)"
- style="">
- <g
- transform="matrix(0,-1,1,0,-294.81158,2953.0504)"
- id="g6252"
- style="">
- <path
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- d="m 1586.5317,1300.2858 0.091,89.5266"
- id="path11089"
- inkscape:connector-type="polyline"
- sodipodi:nodetypes="cc"
- inkscape:connector-curvature="0" />
- <path
- sodipodi:nodetypes="cc"
- inkscape:connector-type="polyline"
- id="path2758"
- d="m 1586.7489,1389.4756 7.9979,-9.1068"
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- inkscape:connector-curvature="0" />
- <path
- sodipodi:nodetypes="cc"
- inkscape:connector-type="polyline"
- id="path2760"
- d="m 1586.6031,1389.5063 -7.9979,-9.1069"
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- inkscape:connector-curvature="0" />
- </g>
- </g>
- </g>
- <g
- id="g5641"
- style="">
- <g
- id="g5465"
- transform="translate(874.42628,746.93837)"
- style="">
- <g
- transform="matrix(0,-1,1,0,-294.81158,2953.0504)"
- id="g5467"
- style="">
- <path
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- d="m 1586.5317,1300.2858 0.091,89.5266"
- id="path5469"
- inkscape:connector-type="polyline"
- sodipodi:nodetypes="cc"
- inkscape:connector-curvature="0" />
- <path
- sodipodi:nodetypes="cc"
- inkscape:connector-type="polyline"
- id="path5471"
- d="m 1586.7489,1389.4756 7.9979,-9.1068"
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- inkscape:connector-curvature="0" />
- <path
- sodipodi:nodetypes="cc"
- inkscape:connector-type="polyline"
- id="path5473"
- d="m 1586.6031,1389.5063 -7.9979,-9.1069"
- style="display:inline;fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;marker-start:none"
- inkscape:connector-curvature="0" />
- </g>
- </g>
- </g>
- <g
- transform="translate(-194.79968,-212.08495)"
- id="g5440">
- <path
- style="fill:#41cd52;fill-opacity:1;stroke:none;stroke-width:2.18747473;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 2378.6251,2292.247 v 66.9548 h 171.1068 l 14.8788,-14.8788 v -66.9549 h -171.1068 z"
- id="path3715-5-6-7-9-8-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:0%;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.29069424px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;"
- x="2471.614"
- y="2309.093"
- id="text5174"><tspan
- sodipodi:role="line"
- x="2471.614"
- y="2309.093"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.29069424px;"
- id="tspan953">Qt for Python</tspan><tspan
- id="tspan6109"
- sodipodi:role="line"
- x="2471.614"
- y="2339.093"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.29069424px;">(generated code)</tspan></text>
- <path
- style="fill:#6b7080;fill-opacity:1;stroke:none;stroke-width:2.18747473;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 2166.5963,2292.247 v 66.9548 h 171.1068 l 14.8788,-14.8788 v -66.9549 h -171.1068 z"
- id="path3715-5-6-7-9-8-7-9-94"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:0%;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.50930572px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;"
- x="2259.1294"
- y="2311.0505"
- id="text3627"
- transform="scale(1.0000266,0.9999734)"><tspan
- id="tspan3697"
- sodipodi:role="line"
- x="2259.1294"
- y="2311.0505"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.50930572px;">generator</tspan><tspan
- sodipodi:role="line"
- x="2259.1294"
- y="2341.0505"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.50930572px;"
- id="tspan2464">front-end</tspan></text>
- <path
- style="fill:#6b7080;fill-opacity:1;stroke:none;stroke-width:2.18747473;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 1959.8625,2292.2469 v 66.9548 h 171.1068 l 14.8788,-14.8788 v -66.9549 h -171.1068 z"
- id="path3715-5-6-7-9-8-7-9-1"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- id="text3168"
- y="2326.4568"
- x="2052.7678"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:0%;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.65129721px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;"
- xml:space="preserve"><tspan
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.65129721px;"
- y="2326.4568"
- x="2052.7678"
- sodipodi:role="line"
- id="tspan5424">API Extractor</tspan></text>
- <path
- style="fill:#9d9faa;fill-opacity:1;stroke:none;stroke-width:2.18747473;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 2378.6251,2393.0867 v 66.9548 h 171.1068 l 14.8788,-14.8788 v -66.9549 h -171.1068 z"
- id="path3715-5-6-7-9-8-7-9-9"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- id="text3487"
- y="2410.3647"
- x="2471.614"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:0%;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.44197154px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;"
- xml:space="preserve"><tspan
- id="tspan2509"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.44197154px;"
- y="2410.3647"
- x="2471.614"
- sodipodi:role="line">typesystem</tspan><tspan
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.44197154px;"
- y="2440.3647"
- x="2471.614"
- sodipodi:role="line"
- id="tspan5432">(handwritten)</tspan></text>
- <path
- style="fill:#9d9faa;fill-opacity:1;stroke:none;stroke-width:2.18747473;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 2166.5963,2394.0075 v 66.9548 h 171.1068 l 14.8788,-14.8788 v -66.9549 h -171.1068 z"
- id="path3715-5-6-7-9-8-7-9"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:0%;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.58586931px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;"
- x="2259.5852"
- y="2412.0415"
- id="text2735"><tspan
- sodipodi:role="line"
- x="2259.5852"
- y="2412.0415"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.58586931px;"
- id="tspan2737">injected code</tspan><tspan
- id="tspan2743"
- sodipodi:role="line"
- x="2259.5852"
- y="2442.0415"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:24px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:1.58586931px;">(handwritten)</tspan></text>
- </g>
- <g
- transform="translate(-102.30216,-279.71223)"
- id="g5541"
- style="stroke:none">
- <path
- sodipodi:type="arc"
- style="fill:#f28888;fill-opacity:1;stroke:none;stroke-width:1;stroke-miterlimit:4;stroke-dasharray:3, 3;stroke-dashoffset:0;stroke-opacity:1"
- id="path5535"
- sodipodi:cx="255.10791"
- sodipodi:cy="326.69064"
- sodipodi:rx="38.848923"
- sodipodi:ry="38.848923"
- d="m 293.95683,326.69064 a 38.848923,38.848923 0 0 1 -38.84892,38.84893 38.848923,38.848923 0 0 1 -38.84892,-38.84893 38.848923,38.848923 0 0 1 38.84892,-38.84892 38.848923,38.848923 0 0 1 38.84892,38.84892 z"
- transform="matrix(0.4405339,0,0,0.4405339,1842.2283,2282.9708)" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-weight:normal;line-height:0%;font-family:Titillium;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;-inkscape-font-specification:'Titillium, Normal';font-stretch:normal;font-variant:normal;font-size:26.66666667px;text-anchor:start;text-align:start;writing-mode:lr;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal"
- x="1946.3259"
- y="2435.7"
- id="text5537"><tspan
- sodipodi:role="line"
- id="tspan5539"
- x="1946.3259"
- y="2435.7"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:26.66666667px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';text-anchor:start;text-align:start;writing-mode:lr;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;stroke:none">1</tspan></text>
- </g>
- <g
- transform="translate(52.589867,-352.69787)"
- id="g5546"
- style="stroke:none">
- <path
- sodipodi:type="arc"
- style="fill:#f28888;fill-opacity:1;stroke:none;stroke-width:1;stroke-miterlimit:4;stroke-dasharray:3, 3;stroke-dashoffset:0;stroke-opacity:1"
- id="path5548"
- sodipodi:cx="255.10791"
- sodipodi:cy="326.69064"
- sodipodi:rx="38.848923"
- sodipodi:ry="38.848923"
- d="m 293.95683,326.69064 a 38.848923,38.848923 0 0 1 -38.84892,38.84893 38.848923,38.848923 0 0 1 -38.84892,-38.84893 38.848923,38.848923 0 0 1 38.84892,-38.84892 38.848923,38.848923 0 0 1 38.84892,38.84892 z"
- transform="matrix(0.4405339,0,0,0.4405339,1842.2283,2282.9708)" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-weight:normal;line-height:0%;font-family:Titillium;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;-inkscape-font-specification:'Titillium, Normal';font-stretch:normal;font-variant:normal;font-size:26.66666667px;text-anchor:start;text-align:start;writing-mode:lr;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal"
- x="1946.3259"
- y="2435.7"
- id="text5550"><tspan
- sodipodi:role="line"
- id="tspan5552"
- x="1946.3259"
- y="2435.7"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:26.66666667px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';text-anchor:start;text-align:start;writing-mode:lr;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;stroke:none">2</tspan></text>
- </g>
- <g
- transform="translate(200.4676,-222.96766)"
- id="g5554"
- style="stroke:none">
- <path
- sodipodi:type="arc"
- style="fill:#f28888;fill-opacity:1;stroke:none;stroke-width:1;stroke-miterlimit:4;stroke-dasharray:3, 3;stroke-dashoffset:0;stroke-opacity:1"
- id="path5556"
- sodipodi:cx="255.10791"
- sodipodi:cy="326.69064"
- sodipodi:rx="38.848923"
- sodipodi:ry="38.848923"
- d="m 293.95683,326.69064 a 38.848923,38.848923 0 0 1 -38.84892,38.84893 38.848923,38.848923 0 0 1 -38.84892,-38.84893 38.848923,38.848923 0 0 1 38.84892,-38.84892 38.848923,38.848923 0 0 1 38.84892,38.84892 z"
- transform="matrix(0.4405339,0,0,0.4405339,1842.2283,2282.9708)" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-weight:normal;line-height:0%;font-family:Titillium;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;-inkscape-font-specification:'Titillium, Normal';font-stretch:normal;font-variant:normal;font-size:26.66666667px;text-anchor:start;text-align:start;writing-mode:lr;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal"
- x="1946.3259"
- y="2435.7"
- id="text5558"><tspan
- sodipodi:role="line"
- id="tspan5560"
- x="1946.3259"
- y="2435.7"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:26.66666667px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';text-anchor:start;text-align:start;writing-mode:lr;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;stroke:none">3</tspan></text>
- </g>
- <g
- transform="translate(413.633,-206.84535)"
- id="g5562"
- style="stroke:none">
- <path
- sodipodi:type="arc"
- style="fill:#f28888;fill-opacity:1;stroke:none;stroke-width:1;stroke-miterlimit:4;stroke-dasharray:3, 3;stroke-dashoffset:0;stroke-opacity:1"
- id="path5564"
- sodipodi:cx="255.10791"
- sodipodi:cy="326.69064"
- sodipodi:rx="38.848923"
- sodipodi:ry="38.848923"
- d="m 293.95683,326.69064 a 38.848923,38.848923 0 0 1 -38.84892,38.84893 38.848923,38.848923 0 0 1 -38.84892,-38.84893 38.848923,38.848923 0 0 1 38.84892,-38.84892 38.848923,38.848923 0 0 1 38.84892,38.84892 z"
- transform="matrix(0.4405339,0,0,0.4405339,1842.2283,2282.9708)" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-weight:normal;line-height:0%;font-family:Titillium;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;-inkscape-font-specification:'Titillium, Normal';font-stretch:normal;font-variant:normal;font-size:26.66666667px;text-anchor:start;text-align:start;writing-mode:lr;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal"
- x="1946.3259"
- y="2435.7"
- id="text5566"><tspan
- sodipodi:role="line"
- id="tspan5568"
- x="1946.3259"
- y="2435.7"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:26.66666667px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';text-anchor:start;text-align:start;writing-mode:lr;font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;stroke:none">4</tspan></text>
- </g>
- </g>
- </g>
-</svg>
diff --git a/sources/shiboken2/doc/images/boostgen.png b/sources/shiboken2/doc/images/boostgen.png
deleted file mode 100644
index ae9d9fc3d..000000000
--- a/sources/shiboken2/doc/images/boostgen.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/images/converter.png b/sources/shiboken2/doc/images/converter.png
deleted file mode 100644
index cd52e2769..000000000
--- a/sources/shiboken2/doc/images/converter.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/images/converter.svg b/sources/shiboken2/doc/images/converter.svg
deleted file mode 100644
index 4305eb720..000000000
--- a/sources/shiboken2/doc/images/converter.svg
+++ /dev/null
@@ -1,349 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="206.375mm"
- height="100.54167mm"
- viewBox="0 0 206.375 100.54167"
- version="1.1"
- id="svg8"
- inkscape:version="0.92.2 2405546, 2018-03-11"
- sodipodi:docname="converter.svg">
- <defs
- id="defs2">
- <marker
- inkscape:isstock="true"
- style="overflow:visible"
- id="marker1623"
- refX="0"
- refY="0"
- orient="auto"
- inkscape:stockid="Arrow1Lend">
- <path
- transform="matrix(-0.8,0,0,-0.8,-10,0)"
- style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1"
- d="M 0,0 5,-5 -12.5,0 5,5 Z"
- id="path1621"
- inkscape:connector-curvature="0" />
- </marker>
- <marker
- inkscape:stockid="Arrow1Lend"
- orient="auto"
- refY="0"
- refX="0"
- id="marker1569"
- style="overflow:visible"
- inkscape:isstock="true"
- inkscape:collect="always">
- <path
- id="path1567"
- d="M 0,0 5,-5 -12.5,0 5,5 Z"
- style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1"
- transform="matrix(-0.8,0,0,-0.8,-10,0)"
- inkscape:connector-curvature="0" />
- </marker>
- <marker
- inkscape:isstock="true"
- style="overflow:visible"
- id="marker1521"
- refX="0"
- refY="0"
- orient="auto"
- inkscape:stockid="Arrow1Lend"
- inkscape:collect="always">
- <path
- transform="matrix(-0.8,0,0,-0.8,-10,0)"
- style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1"
- d="M 0,0 5,-5 -12.5,0 5,5 Z"
- id="path1519"
- inkscape:connector-curvature="0" />
- </marker>
- <marker
- inkscape:stockid="Arrow1Lend"
- orient="auto"
- refY="0"
- refX="0"
- id="marker1479"
- style="overflow:visible"
- inkscape:isstock="true"
- inkscape:collect="always">
- <path
- id="path1477"
- d="M 0,0 5,-5 -12.5,0 5,5 Z"
- style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1"
- transform="matrix(-0.8,0,0,-0.8,-10,0)"
- inkscape:connector-curvature="0" />
- </marker>
- <marker
- inkscape:isstock="true"
- style="overflow:visible"
- id="marker1443"
- refX="0"
- refY="0"
- orient="auto"
- inkscape:stockid="Arrow1Lend"
- inkscape:collect="always">
- <path
- transform="matrix(-0.8,0,0,-0.8,-10,0)"
- style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1"
- d="M 0,0 5,-5 -12.5,0 5,5 Z"
- id="path1441"
- inkscape:connector-curvature="0" />
- </marker>
- <marker
- inkscape:stockid="Arrow1Lend"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow1Lend"
- style="overflow:visible"
- inkscape:isstock="true"
- inkscape:collect="always">
- <path
- id="path1154"
- d="M 0,0 5,-5 -12.5,0 5,5 Z"
- style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.00000003pt;stroke-opacity:1"
- transform="matrix(-0.8,0,0,-0.8,-10,0)"
- inkscape:connector-curvature="0" />
- </marker>
- </defs>
- <sodipodi:namedview
- id="base"
- pagecolor="#ffffff"
- bordercolor="#666666"
- borderopacity="1.0"
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:zoom="0.35"
- inkscape:cx="382.16184"
- inkscape:cy="-28.417621"
- inkscape:document-units="mm"
- inkscape:current-layer="layer1"
- showgrid="true"
- fit-margin-top="0"
- fit-margin-left="0"
- fit-margin-right="0"
- fit-margin-bottom="0"
- inkscape:window-width="1002"
- inkscape:window-height="1042"
- inkscape:window-x="10"
- inkscape:window-y="28"
- inkscape:window-maximized="0">
- <inkscape:grid
- type="xygrid"
- id="grid971"
- originx="-58.208333"
- originy="-68.791657" />
- </sodipodi:namedview>
- <metadata
- id="metadata5">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- <dc:title></dc:title>
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <g
- inkscape:label="Layer 1"
- inkscape:groupmode="layer"
- id="layer1"
- transform="translate(-58.208333,-127.66667)">
- <path
- style="fill:#17a81a;fill-opacity:1;stroke:none;stroke-width:0.82824755;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 127,132.95834 0.0687,26.45833 h 63.43127 l 5.29167,-5.29167 v -26.45833 h -63.5 z"
- id="path3715-5-6-7-9-8-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#3a4055;fill-opacity:1;stroke:none;stroke-width:0.67261654;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 68.791667,132.95834 v 26.45833 H 105.83333 L 111.125,154.125 V 127.66667 H 74.083333 Z"
- id="path3715-5-6-7-9-8-7-6-3"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#848895;fill-opacity:1;stroke:none;stroke-width:0.52087492;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="M 58.208333,173.96875 V 185.875 h 48.947917 l 3.96875,-3.96875 V 170 H 62.177083 Z"
- id="path3715-5-6-7-9-8-7-6-56"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#17a81a;fill-opacity:1;stroke:none;stroke-width:0.82824755;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 127.00003,175.29167 0.0687,26.45833 H 190.5 l 5.29167,-5.29167 V 170 h -63.5 z"
- id="path3715-5-6-7-9-8-7-2"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#848895;fill-opacity:1;stroke:none;stroke-width:0.52087492;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 58.208333,195.13542 v 11.90625 h 48.947917 l 3.96875,-3.96875 V 191.16667 H 62.177083 Z"
- id="path3715-5-6-7-9-8-7-6-56-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#848895;fill-opacity:1;stroke:none;stroke-width:0.52087492;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 58.208343,216.30209 v 11.90625 h 48.947907 l 3.96875,-3.96875 V 212.33334 H 62.177093 Z"
- id="path3715-5-6-7-9-8-7-6-56-0"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:7.05555534px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.26458332"
- x="65.68634"
- y="179.68727"
- id="text1032"><tspan
- sodipodi:role="line"
- id="tspan1030"
- x="65.68634"
- y="179.68727"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:7.05555534px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332">PythonType1</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:7.05555534px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.26458332"
- x="65.326508"
- y="200.85394"
- id="text1032-1"><tspan
- sodipodi:role="line"
- id="tspan1030-1"
- x="65.326508"
- y="200.85394"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:7.05555534px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332">PythonType2</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:7.05555534px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.26458332"
- x="65.319458"
- y="222.02061"
- id="text1032-4"><tspan
- sodipodi:role="line"
- id="tspan1030-6"
- x="65.319458"
- y="222.02061"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:7.05555534px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332">PythonType3</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.58333302px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:Titillium;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.26458332"
- x="90.120621"
- y="139.29776"
- id="text1062"><tspan
- sodipodi:role="line"
- id="tspan1060"
- x="90.120621"
- y="139.29776"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:9.87777805px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332">C++</tspan><tspan
- sodipodi:role="line"
- x="90.120621"
- y="152.52693"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:9.87777805px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332"
- id="tspan1064">Type</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.58333302px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:Titillium;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.26458332"
- x="135.41069"
- y="138.95909"
- id="text1068"><tspan
- sodipodi:role="line"
- id="tspan1066"
- x="135.41069"
- y="138.95909"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:8.46666622px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332">Converter</tspan><tspan
- sodipodi:role="line"
- x="135.41069"
- y="152.18826"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:8.46666622px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332"
- id="tspan1070">C++ -&gt; Python</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.58333302px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:Titillium;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.26458332"
- x="135.41072"
- y="181.29242"
- id="text1068-9"><tspan
- sodipodi:role="line"
- id="tspan1066-7"
- x="135.41072"
- y="181.29242"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:8.46666622px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332">Converter</tspan><tspan
- sodipodi:role="line"
- x="135.41072"
- y="194.52159"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:8.46666622px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332"
- id="tspan1070-5">Python -&gt; C++</tspan></text>
- <path
- style="fill:#3a4055;fill-opacity:1;stroke:none;stroke-width:0.67261654;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="M 211.66667,175.29167 V 201.75 h 37.04166 L 254,196.45833 V 170 h -37.04167 z"
- id="path3715-5-6-7-9-8-7-6-3-9"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:10.58333302px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:Titillium;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.26458332"
- x="232.99562"
- y="181.63109"
- id="text1062-7"><tspan
- sodipodi:role="line"
- id="tspan1060-4"
- x="232.99562"
- y="181.63109"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:9.87777805px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332">C++</tspan><tspan
- sodipodi:role="line"
- x="232.99562"
- y="194.86026"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:9.87777805px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:center;writing-mode:lr-tb;text-anchor:middle;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332"
- id="tspan1064-9">Type</tspan></text>
- <path
- style="fill:#848895;fill-opacity:1;stroke:none;stroke-width:0.52087492;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 211.66667,131.63542 v 11.90625 h 48.94791 l 3.96875,-3.96875 v -11.90625 h -48.94791 z"
- id="path3715-5-6-7-9-8-7-6-56-0-1"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:7.05555534px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.26458332"
- x="220.67876"
- y="137.35394"
- id="text1032-4-7"><tspan
- sodipodi:role="line"
- id="tspan1030-6-0"
- x="220.67876"
- y="137.35394"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:7.05555534px;font-family:Titillium;-inkscape-font-specification:'Titillium, Normal';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.26458332">PythonType</tspan></text>
- <path
- style="fill:none;stroke:#000000;stroke-width:0.26499999;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#Arrow1Lend)"
- d="M 111.125,143.54167 H 127"
- id="path1149"
- inkscape:connector-curvature="0" />
- <path
- style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#marker1443)"
- d="M 111.125,175.29167 H 127"
- id="path1433"
- inkscape:connector-curvature="0" />
- <path
- style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#marker1479)"
- d="M 111.125,196.45834 127,185.875"
- id="path1469"
- inkscape:connector-curvature="0" />
- <path
- style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#marker1521)"
- d="M 111.125,217.625 127,201.75"
- id="path1511"
- inkscape:connector-curvature="0" />
- <path
- style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#marker1569)"
- d="m 195.79166,185.875 h 15.875"
- id="path1559"
- inkscape:connector-curvature="0" />
- <path
- style="fill:none;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;marker-end:url(#marker1623)"
- d="m 195.79166,138.25001 h 15.875"
- id="path1613"
- inkscape:connector-curvature="0" />
- </g>
-</svg>
diff --git a/sources/shiboken2/doc/images/genrunnerarch.png b/sources/shiboken2/doc/images/genrunnerarch.png
deleted file mode 100644
index db1077cd0..000000000
--- a/sources/shiboken2/doc/images/genrunnerarch.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/images/genrunnerarch.svg b/sources/shiboken2/doc/images/genrunnerarch.svg
deleted file mode 100644
index ea7eb73e7..000000000
--- a/sources/shiboken2/doc/images/genrunnerarch.svg
+++ /dev/null
@@ -1,654 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="980"
- height="380"
- id="svg2"
- sodipodi:version="0.32"
- inkscape:version="0.47pre4 r22446"
- version="1.0"
- sodipodi:docname="genrunnerarch.svg"
- inkscape:output_extension="org.inkscape.output.svg.inkscape"
- inkscape:export-filename="genrunnerarch.png"
- inkscape:export-xdpi="56.549999"
- inkscape:export-ydpi="56.549999">
- <defs
- id="defs4">
- <marker
- inkscape:stockid="EmptyDiamondL"
- orient="auto"
- refY="0"
- refX="0"
- id="EmptyDiamondL"
- style="overflow:visible">
- <path
- id="path3930"
- d="M 0,-7.0710768 -7.0710894,0 0,7.0710589 7.0710462,0 0,-7.0710768 z"
- style="fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="scale(0.8,0.8)" />
- </marker>
- <marker
- inkscape:stockid="EmptyTriangleInL"
- orient="auto"
- refY="0"
- refX="0"
- id="EmptyTriangleInL"
- style="overflow:visible">
- <path
- id="path3975"
- d="m 5.77,0 -8.65,5 0,-10 8.65,5 z"
- style="fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(-0.8,0,0,-0.8,4.8,0)" />
- </marker>
- <marker
- inkscape:stockid="Arrow1Sstart"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow1Sstart"
- style="overflow:visible">
- <path
- id="path3835"
- d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
- style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(0.2,0,0,0.2,1.2,0)" />
- </marker>
- <marker
- inkscape:stockid="Arrow1Mend"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow1Mend"
- style="overflow:visible">
- <path
- id="path3832"
- d="M 0,0 5,-5 -12.5,0 5,5 0,0 z"
- style="fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(-0.4,0,0,-0.4,-4,0)" />
- </marker>
- <marker
- inkscape:stockid="Tail"
- orient="auto"
- refY="0"
- refX="0"
- id="Tail"
- style="overflow:visible">
- <g
- id="g3859"
- transform="scale(-1.2,-1.2)">
- <path
- id="path3861"
- d="M -3.8048674,-3.9585227 0.54352094,0"
- style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3863"
- d="M -1.2866832,-3.9585227 3.0617053,0"
- style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3865"
- d="M 1.3053582,-3.9585227 5.6537466,0"
- style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3867"
- d="M -3.8048674,4.1775838 0.54352094,0.21974226"
- style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3869"
- d="M -1.2866832,4.1775838 3.0617053,0.21974226"
- style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- <path
- id="path3871"
- d="M 1.3053582,4.1775838 5.6537466,0.21974226"
- style="fill:none;stroke:#000000;stroke-width:0.80000001;stroke-linecap:round;marker-start:none;marker-end:none" />
- </g>
- </marker>
- <marker
- inkscape:stockid="Arrow2Lend"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow2Lend"
- style="overflow:visible">
- <path
- id="path3636"
- style="font-size:12px;fill-rule:evenodd;stroke-width:0.625;stroke-linejoin:round"
- d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
- transform="matrix(-1.1,0,0,-1.1,-1.1,0)" />
- </marker>
- <inkscape:perspective
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective10" />
- <inkscape:perspective
- id="perspective3033"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <inkscape:perspective
- id="perspective3881"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <inkscape:perspective
- id="perspective3915"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <inkscape:perspective
- id="perspective3956"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <inkscape:perspective
- id="perspective5100"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <inkscape:perspective
- id="perspective5322"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <inkscape:perspective
- id="perspective5365"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <inkscape:perspective
- id="perspective5391"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <marker
- inkscape:stockid="EmptyTriangleInL"
- orient="auto"
- refY="0"
- refX="0"
- id="EmptyTriangleInL-4"
- style="overflow:visible">
- <path
- id="path3975-9"
- d="m 5.77,0 -8.65,5 0,-10 8.65,5 z"
- style="fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="matrix(-0.8,0,0,-0.8,4.8,0)" />
- </marker>
- <inkscape:perspective
- id="perspective5621"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <inkscape:perspective
- id="perspective5643"
- inkscape:persp3d-origin="0.5 : 0.33333333 : 1"
- inkscape:vp_z="1 : 0.5 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_x="0 : 0.5 : 1"
- sodipodi:type="inkscape:persp3d" />
- <marker
- inkscape:stockid="EmptyDiamondL"
- orient="auto"
- refY="0"
- refX="0"
- id="EmptyDiamondL-7"
- style="overflow:visible">
- <path
- id="path3930-7"
- d="M 0,-7.0710768 -7.0710894,0 0,7.0710589 7.0710462,0 0,-7.0710768 z"
- style="fill:#ffffff;fill-rule:evenodd;stroke:#000000;stroke-width:1pt;marker-start:none"
- transform="scale(0.8,0.8)" />
- </marker>
- </defs>
- <sodipodi:namedview
- id="base"
- pagecolor="#ffffff"
- bordercolor="#666666"
- borderopacity="1.0"
- gridtolerance="10000"
- guidetolerance="10"
- objecttolerance="10"
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:zoom="1.0716799"
- inkscape:cx="460.27913"
- inkscape:cy="148.01364"
- inkscape:document-units="px"
- inkscape:current-layer="layer1"
- showgrid="false"
- inkscape:window-width="1862"
- inkscape:window-height="1019"
- inkscape:window-x="20"
- inkscape:window-y="89"
- showguides="true"
- inkscape:guide-bbox="true"
- inkscape:window-maximized="0" />
- <metadata
- id="metadata7">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- <dc:title></dc:title>
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <g
- inkscape:label="Layer 1"
- inkscape:groupmode="layer"
- id="layer1"
- transform="translate(472.44407,-697.53823)">
- <flowRoot
- xml:space="preserve"
- id="flowRoot3229"
- style="font-size:40px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- transform="translate(2.0918751e-6,-6.0000008)"><flowRegion
- id="flowRegion3231"><rect
- id="rect3233"
- width="125.74072"
- height="40.5849"
- x="388.45547"
- y="279.5423" /></flowRegion><flowPara
- id="flowPara3235" /></flowRoot> <g
- id="g5867"
- transform="translate(6.7062969,-7.6922472)">
- <rect
- rx="3.4968286"
- ry="5.2462597"
- y="713.31403"
- x="-472.05276"
- height="363.61459"
- width="393.78473"
- id="rect3609"
- style="fill:#e4fae3;fill-opacity:0.65882353;stroke:#8eff89;stroke-width:0.78260708;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
- <text
- transform="scale(1.0000266,0.9999734)"
- id="text3601"
- y="742.43872"
- x="-275.16165"
- style="font-size:38.71272278px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- id="tspan3605"
- style="font-size:27.09890556px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans"
- y="742.43872"
- x="-275.16165"
- sodipodi:role="line"><tspan
- id="tspan2508"
- style="font-weight:bold">API Extractor</tspan></tspan></text>
- <g
- transform="matrix(0.9678438,0,0,0.9677923,-587.62742,-106.48682)"
- id="g3763">
- <rect
- style="fill:#bff3bc;fill-opacity:1;stroke:#0af400;stroke-width:0.79775763;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect3737"
- width="244.82956"
- height="101.59812"
- x="267.06232"
- y="905.13727"
- ry="3.1522403"
- rx="2.4096873" />
- <text
- xml:space="preserve"
- style="font-size:40px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- x="389.39117"
- y="931.86993"
- id="text3739"><tspan
- sodipodi:role="line"
- x="389.39117"
- y="931.86993"
- style="font-size:22px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans Bold"
- id="tspan3741">ApiExtractor</tspan><tspan
- id="tspan2523"
- sodipodi:role="line"
- x="389.39117"
- y="953.38947"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">commands the parsing and</tspan><tspan
- id="tspan2517"
- sodipodi:role="line"
- x="389.39117"
- y="973.38947"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">building of the data model</tspan><tspan
- id="tspan2519"
- sodipodi:role="line"
- x="389.39117"
- y="993.38947"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">and calls the user generators</tspan></text>
- </g>
- <rect
- rx="2.1814992"
- ry="5.2485871"
- y="713.45312"
- x="219.72128"
- height="363.77597"
- width="274.11292"
- id="rect9190"
- style="fill:#b8d1f1;fill-opacity:0.51184836;stroke:#0045a4;stroke-width:0.6182732;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
- <text
- transform="scale(1.0000266,0.9999734)"
- id="text9192"
- y="742.66901"
- x="357.65579"
- style="font-size:38.71272278px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#002e7a;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- id="tspan9194"
- style="font-size:27.09890556px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#002e7a;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans"
- y="742.66901"
- x="357.65579"
- sodipodi:role="line"><tspan
- id="tspan2512"
- style="font-weight:bold;fill:#002e7a;fill-opacity:1">front-end</tspan><tspan
- id="tspan2514"
- style="font-size:22px;fill:#002e7a;fill-opacity:1" /></tspan></text>
- <rect
- rx="2.2192271"
- ry="5.2485123"
- y="713.23639"
- x="-68.659073"
- height="363.77075"
- width="278.85358"
- id="rect9190-9"
- style="fill:#cbe990;fill-opacity:0.51184836;stroke:#6ca400;stroke-width:0.62359226;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
- <text
- transform="scale(1.0000266,0.9999734)"
- id="text9192-3"
- y="741.71094"
- x="70.291061"
- style="font-size:38.71272278px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#050800;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- xml:space="preserve"><tspan
- id="tspan9194-7"
- style="font-size:26px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:center;text-anchor:middle;fill:#050800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans"
- y="741.71094"
- x="70.291061"
- sodipodi:role="line">Generator Runner</tspan></text>
- <g
- transform="matrix(0.9678438,0,0,0.9677923,-687.04869,-241.74888)"
- id="g9234-4">
- <rect
- style="fill:#addc52;fill-opacity:1;stroke:#6ca400;stroke-width:0.73640609;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect9206-4"
- width="218.17299"
- height="83.517967"
- x="694.6994"
- y="1044.8701"
- ry="2.5912752"
- rx="2.4978092" />
- <text
- xml:space="preserve"
- style="font-size:40px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- x="803.78589"
- y="1072.3693"
- id="text9208-3"><tspan
- sodipodi:role="line"
- x="803.78589"
- y="1072.3693"
- style="font-size:22px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:center;text-anchor:middle;fill:#050800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans Bold"
- id="tspan9210-0">Generator</tspan><tspan
- id="tspan9222-8"
- sodipodi:role="line"
- x="803.78589"
- y="1093.8888"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#050800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">base class for front-end</tspan><tspan
- id="tspan3946"
- sodipodi:role="line"
- x="803.78589"
- y="1113.8888"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#050800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">output classes</tspan></text>
- </g>
- <g
- transform="matrix(0.9678438,0,0,0.9677923,-726.09128,-46.791689)"
- id="g10497-6">
- <rect
- style="fill:#89b3e7;fill-opacity:1;stroke:#0049a4;stroke-width:1.04736876;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect10444-8"
- width="256.05252"
- height="143.95157"
- x="990.81482"
- y="843.58032"
- ry="4.4663219"
- rx="2.9314826" />
- <text
- xml:space="preserve"
- style="font-size:40px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#002758;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- x="1118.0945"
- y="873.04047"
- id="text10446-8"><tspan
- sodipodi:role="line"
- x="1118.0945"
- y="873.04047"
- style="font-size:22px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:center;text-anchor:middle;fill:#002758;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans Bold"
- id="tspan10448-4">SpecificGenerator</tspan><tspan
- id="tspan4063"
- sodipodi:role="line"
- x="1118.0945"
- y="894.56"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#002758;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">generators written for any</tspan><tspan
- id="tspan5381"
- sodipodi:role="line"
- x="1118.0945"
- y="914.56"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#002758;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">desired output,</tspan><tspan
- id="tspan4065"
- sodipodi:role="line"
- x="1118.0945"
- y="934.56"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#002758;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans"> e.g.: HppGenerator,</tspan><tspan
- id="tspan4071"
- sodipodi:role="line"
- x="1118.0945"
- y="954.56"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#002758;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">CppGenerator,</tspan><tspan
- id="tspan4073"
- sodipodi:role="line"
- x="1118.0945"
- y="974.56"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#002758;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">ConverterGenerator</tspan></text>
- </g>
- <path
- sodipodi:nodetypes="cc"
- transform="translate(109.91989,748.26874)"
- id="path4056"
- d="m -201.98482,41.728896 76.97065,5e-6"
- style="fill:none;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:6, 1;stroke-dashoffset:0" />
- <path
- sodipodi:nodetypes="cc"
- id="path4056-2"
- d="m 197.04022,787.89746 35.38656,0"
- style="fill:none;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker-start:url(#EmptyTriangleInL)" />
- <g
- transform="matrix(0.9678438,0,0,0.9677923,-1010.4541,91.401187)"
- id="g10497">
- <rect
- style="fill:#addc52;fill-opacity:1;stroke:#6ca400;stroke-width:0.88060772;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect10444"
- width="256.21927"
- height="101.69494"
- x="990.73145"
- y="843.49695"
- ry="3.1552441"
- rx="2.9333918" />
- <text
- xml:space="preserve"
- style="font-size:40px;font-style:normal;font-weight:normal;text-align:start;text-anchor:start;fill:#035800;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- x="1012.22"
- y="870.08466"
- id="text10446"><tspan
- sodipodi:role="line"
- x="1012.22"
- y="870.08466"
- style="font-size:22px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:start;text-anchor:start;fill:#050800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans Bold"
- id="tspan10448">Generator App</tspan><tspan
- id="tspan10456"
- sodipodi:role="line"
- x="1012.22"
- y="891.60419"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;text-anchor:start;fill:#050800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">* loads generators</tspan><tspan
- id="tspan5353"
- sodipodi:role="line"
- x="1012.22"
- y="911.60419"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;text-anchor:start;fill:#050800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">* setup API Extractor</tspan><tspan
- id="tspan5355"
- sodipodi:role="line"
- x="1012.22"
- y="931.60419"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;text-anchor:start;fill:#050800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">* executes each generator</tspan></text>
- </g>
- <path
- sodipodi:nodetypes="cc"
- id="path4056-9"
- d="m 72.409302,850.57374 0,56.99122"
- style="fill:none;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:6, 1;stroke-dashoffset:0" />
- <path
- sodipodi:nodetypes="ccc"
- id="path4056-2-0"
- d="m -86.437722,825.54499 52.188784,0 0.06367,81.67009"
- style="fill:none;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0;marker-start:url(#EmptyDiamondL)" />
- <path
- sodipodi:nodetypes="cc"
- id="path4056-91"
- d="m -394.83596,853.70064 0,121.42437"
- style="fill:none;stroke:#000000;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:6, 1;stroke-dashoffset:0" />
- <g
- transform="matrix(0.9678438,0,0,0.9677923,-707.18032,-153.53291)"
- id="g3809">
- <rect
- style="fill:#bff3bc;fill-opacity:1;stroke:#0af400;stroke-width:1.00168562;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect3785"
- width="332.48172"
- height="82.830231"
- x="302.83319"
- y="1068.9153"
- ry="3.1461167"
- rx="3.8065021" />
- <text
- xml:space="preserve"
- style="font-size:40px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- x="469.03497"
- y="1095.5493"
- id="text3787"><tspan
- id="tspan3791"
- sodipodi:role="line"
- x="469.03497"
- y="1095.5493"
- style="font-size:22px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans Bold">AbstractMetaBuilder</tspan><tspan
- sodipodi:role="line"
- x="469.03497"
- y="1117.0688"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans"
- id="tspan3807">builds the data model with information</tspan><tspan
- id="tspan2545"
- sodipodi:role="line"
- x="469.03497"
- y="1137.0688"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">from headers and binding directives</tspan><tspan
- id="tspan3795"
- sodipodi:role="line"
- x="469.03497"
- y="1157.0688"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans" /></text>
- </g>
- <g
- transform="matrix(0.9678438,0,0,0.9677923,-755.89347,194.37862)"
- id="g3709">
- <rect
- style="fill:#bff3bc;fill-opacity:1;stroke:#0af400;stroke-width:0.69825613;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect2821"
- width="198.90968"
- height="93.892342"
- x="305.2475"
- y="807.38849"
- ry="2.6812849"
- rx="2.1703238" />
- <text
- xml:space="preserve"
- style="font-size:40px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- x="405.17499"
- y="831.81903"
- id="text3611"><tspan
- id="tspan3687"
- sodipodi:role="line"
- x="405.17499"
- y="831.81903"
- style="font-size:22px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans Bold">TypeDatabase</tspan><tspan
- id="tspan5641"
- sodipodi:role="line"
- x="405.17499"
- y="853.33856"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">parses typesystem</tspan><tspan
- id="tspan3689"
- sodipodi:role="line"
- x="405.17499"
- y="873.33856"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">and stores information</tspan></text>
- </g>
- <g
- transform="matrix(0.9678438,0,0,0.9677923,-589.50555,-13.923919)"
- id="g3728">
- <rect
- style="fill:#bff3bc;fill-opacity:1;stroke:#0af400;stroke-width:0.54871088;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
- id="rect3625"
- width="117.15066"
- height="86.355225"
- x="133.25664"
- y="809.36938"
- ry="2.6793056"
- rx="1.3412292" />
- <text
- xml:space="preserve"
- style="font-size:40px;font-style:normal;font-weight:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
- x="191.58197"
- y="838.75159"
- id="text3627"><tspan
- sodipodi:role="line"
- x="191.58197"
- y="838.75159"
- style="font-size:22px;font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans Bold"
- id="tspan3631">Parser</tspan><tspan
- id="tspan3695"
- sodipodi:role="line"
- x="191.58197"
- y="860.27112"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">parses the</tspan><tspan
- id="tspan3697"
- sodipodi:role="line"
- x="191.58197"
- y="880.27112"
- style="font-size:16px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:center;text-anchor:middle;fill:#035800;fill-opacity:1;font-family:Bitstream Vera Sans;-inkscape-font-specification:Bitstream Vera Sans">lib headers</tspan></text>
- </g>
- <path
- sodipodi:nodetypes="ccc"
- id="path4056-2-0-1"
- d="m 197.39006,961.71122 158.27877,0 0.19429,-51.88885"
- style="fill:none;stroke:#000000;stroke-width:1.38812411;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:8.32874408, 1.38812401;stroke-dashoffset:0;marker-start:none" />
- </g>
- </g>
-</svg>
diff --git a/sources/shiboken2/doc/images/icecream.png b/sources/shiboken2/doc/images/icecream.png
deleted file mode 100644
index 41d1a25fa..000000000
--- a/sources/shiboken2/doc/images/icecream.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/images/qtforpython-underthehood.png b/sources/shiboken2/doc/images/qtforpython-underthehood.png
deleted file mode 100644
index 64e30b1c5..000000000
--- a/sources/shiboken2/doc/images/qtforpython-underthehood.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/images/shibokenqtarch.png b/sources/shiboken2/doc/images/shibokenqtarch.png
deleted file mode 100644
index 359413373..000000000
--- a/sources/shiboken2/doc/images/shibokenqtarch.png
+++ /dev/null
Binary files differ
diff --git a/sources/shiboken2/doc/images/shibokenqtarch.svg b/sources/shiboken2/doc/images/shibokenqtarch.svg
deleted file mode 100644
index d9212f18c..000000000
--- a/sources/shiboken2/doc/images/shibokenqtarch.svg
+++ /dev/null
@@ -1,188 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-
-<svg
- xmlns:dc="http://purl.org/dc/elements/1.1/"
- xmlns:cc="http://creativecommons.org/ns#"
- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
- xmlns:svg="http://www.w3.org/2000/svg"
- xmlns="http://www.w3.org/2000/svg"
- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="275"
- height="197.55103"
- id="svg2"
- sodipodi:version="0.32"
- inkscape:version="0.92.2 2405546, 2018-03-11"
- version="1.0"
- sodipodi:docname="shibokenqtarch.svg"
- inkscape:output_extension="org.inkscape.output.svg.inkscape"
- inkscape:export-filename="shibokenqtarch.png"
- inkscape:export-xdpi="90"
- inkscape:export-ydpi="90">
- <defs
- id="defs4">
- <marker
- inkscape:stockid="Arrow2Lend"
- orient="auto"
- refY="0"
- refX="0"
- id="Arrow2Lend"
- style="overflow:visible">
- <path
- id="path3636"
- style="font-size:12px;fill-rule:evenodd;stroke-width:0.625;stroke-linejoin:round"
- d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
- transform="matrix(-1.1,0,0,-1.1,-1.1,0)"
- inkscape:connector-curvature="0" />
- </marker>
- <inkscape:perspective
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective10" />
- </defs>
- <sodipodi:namedview
- id="base"
- pagecolor="#ffffff"
- bordercolor="#666666"
- borderopacity="1.0"
- gridtolerance="10000"
- guidetolerance="10"
- objecttolerance="10"
- inkscape:pageopacity="0.0"
- inkscape:pageshadow="2"
- inkscape:zoom="1.0474359"
- inkscape:cx="110.19617"
- inkscape:cy="69.09871"
- inkscape:document-units="px"
- inkscape:current-layer="layer1"
- showgrid="true"
- inkscape:window-width="1002"
- inkscape:window-height="1042"
- inkscape:window-x="10"
- inkscape:window-y="28"
- showguides="true"
- inkscape:guide-bbox="true"
- fit-margin-top="0"
- fit-margin-left="0"
- fit-margin-right="0"
- fit-margin-bottom="0"
- inkscape:window-maximized="0">
- <inkscape:grid
- type="xygrid"
- id="grid44"
- originx="-44.999996"
- originy="-12.44898" />
- </sodipodi:namedview>
- <metadata
- id="metadata7">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- <dc:title></dc:title>
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <g
- inkscape:label="Layer 1"
- inkscape:groupmode="layer"
- id="layer1"
- transform="translate(-106.0768,-311.50489)">
- <path
- style="fill:#21be2b;fill-opacity:1;stroke:none;stroke-width:2.20567369;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 106.0768,322.72938 v 44.89796 h 262.2093 l 12.7907,-11.22449 V 311.50489 H 117.53514 Z"
- id="path3715-5-6-7-9-8-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#17a81a;fill-opacity:1;stroke:none;stroke-width:1.57079244;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 251.99517,457.61034 v 51.44557 H 369.85231 L 381.0768,498.76679 V 447.32122 H 263.21966 Z"
- id="path3715-5-6-7-9-6-7"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <path
- style="fill:#53586b;fill-opacity:1;stroke:none;stroke-width:1.57079256;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 106.0768,457.61034 v 51.44557 h 117.85714 l 11.22449,-10.28912 V 447.32122 H 117.30129 Z"
- id="path3715-5-6-7-9-6-7-5"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:16.68707466px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.12244904;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- x="120.87232"
- y="334.88406"
- id="text153"><tspan
- sodipodi:role="line"
- id="tspan151"
- x="120.87232"
- y="334.88406"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:16.68707466px;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.12244904;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1">Qt for Python</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:12.74510956px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:Titillium;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.31862774"
- x="121.09701"
- y="354.01886"
- id="text157"><tspan
- sodipodi:role="line"
- x="121.09701"
- y="354.01886"
- id="tspan159"
- style="fill:#ffffff;fill-opacity:1;stroke-width:0.31862774">Qt classes and functions exported to Python</tspan></text>
- <path
- style="fill:#53586b;fill-opacity:1;stroke:none;stroke-width:2.20567369;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- d="m 106.0768,391.19877 v 44.89796 h 262.2093 l 12.7907,-11.22449 V 379.97428 H 117.53514 Z"
- id="path3715-5-6-7-9-8-7-6"
- inkscape:connector-curvature="0"
- sodipodi:nodetypes="ccccccc" />
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:16.68707466px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.41717955"
- x="121.0225"
- y="403.38095"
- id="text153-2"><tspan
- sodipodi:role="line"
- id="tspan151-9"
- x="121.0225"
- y="403.38095"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:16.68707466px;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.41717955">Shiboken</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:12.74510956px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:Titillium;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.31862774"
- x="121.09701"
- y="421.95245"
- id="text157-1"><tspan
- sodipodi:role="line"
- x="121.09701"
- y="421.95245"
- id="tspan159-2"
- style="fill:#ffffff;fill-opacity:1;stroke-width:0.31862774">Generator that exposes C++ classes to Python</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:17.95918465px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.31862774"
- x="123.35368"
- y="482.61551"
- id="text157-1-7"><tspan
- sodipodi:role="line"
- x="123.35368"
- y="482.61551"
- id="tspan159-2-0"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:17.95918465px;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.31862774">CPython API</tspan></text>
- <text
- xml:space="preserve"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:17.95918465px;line-height:1.25;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.4132798"
- x="265.1445"
- y="483.19019"
- id="text157-1-9"><tspan
- sodipodi:role="line"
- x="265.1445"
- y="483.19019"
- id="tspan159-2-3"
- style="font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;font-size:17.95918465px;font-family:Titillium;-inkscape-font-specification:'Titillium, Semi-Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-feature-settings:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke-width:0.4132798">Qt 5 Libraries</tspan></text>
- </g>
-</svg>
diff --git a/sources/shiboken2/doc/index.rst b/sources/shiboken2/doc/index.rst
deleted file mode 100644
index ca452b9ca..000000000
--- a/sources/shiboken2/doc/index.rst
+++ /dev/null
@@ -1,52 +0,0 @@
-Shiboken
-********
-
-Shiboken is a fundamental piece on the `Qt for Python`_ project that serves two purposes:
-
-* Generator_: Extract information from C or C++ headers and generate CPython_ code that allow
- to bring C or C++ projects to Python. This process uses a library called ApiExtractor_ which
- internally uses Clang_.
-* Module_: An utility Python module that exposed new Python types, functions to handle pointers,
- among other things, that is written in CPython_ and can use independently of the generator.
-
-.. _`Qt for Python`: ../index.html
-.. _Generator: shibokengenerator.html
-.. _Module: shibokenmodule.html
-.. _CPython: https://github.com/python/cpython
-.. _Clang: https://clang.llvm.org/
-.. _ApiExtractor: typesystem.html
-
-Documentation
-=============
-
-.. raw:: html
-
- <table class="special">
- <colgroup>
- <col style="width: 33%" />
- <col style="width: 33%" />
- <col style="width: 33%" />
- </colgroup>
- <tr>
- <td><a href="gettingstarted.html"><p><strong>Getting Started</strong><br/>Install and build from source.</p></a></td>
- <td><a href="shibokengenerator.html"><p><strong>Shiboken Generator</strong><br/>Binding generator executable.</p></a></td>
- <td><a href="shibokenmodule.html"><p><strong>Shiboken Module</strong><br/>Python utility module.</p></a></td>
- </tr>
- <tr>
- <td><a href="typesystem.html"><p><strong>Type System</strong><br/>Reference and functionallities.</p></a></td>
- <td><a href="examples/index.html"><p><strong>Examples</strong><br/>Using Shiboken.</p></a></td>
- <td><a href="considerations.html"><p><strong>Considerations</strong><br/>Known issues and FAQ.</p></a></td>
- </tr>
-
- </table>
-
-.. toctree::
- :hidden:
- :glob:
-
- gettingstarted.rst
- shibokengenerator.rst
- shibokenmodule.rst
- typesystem.rst
- examples/index.rst
- considerations.rst
diff --git a/sources/shiboken2/doc/shibokengenerator.rst b/sources/shiboken2/doc/shibokengenerator.rst
deleted file mode 100644
index 1a7152fbb..000000000
--- a/sources/shiboken2/doc/shibokengenerator.rst
+++ /dev/null
@@ -1,315 +0,0 @@
-.. _gen-overview:
-
-******************
-Generator Overview
-******************
-
-The following diagram summarizes Shiboken's role in the Qt for Python
-project.
-
-.. image:: images/qtforpython-underthehood.png
-
-An XML typesystem file is used to specify the types to be exposed to Python
-and to apply modifications to properly represent and manipulate the types in
-the Python World. For example, you can remove and add methods to certain types,
-and also modify the arguments of each method. These actions are inevitable to
-properly handle the data structures or types.
-
-The final outcome of this process is a set of wrappers written in CPython,
-which can be used as a module in your Python code.
-
-In a few words, the Generator is a utility that parses a collection of header and
-typesystem files, generating other files (code, documentation, etc.) as result.
-
-Creating new bindings
-=====================
-
-.. figure:: images/bindinggen-development.png
- :scale: 80
- :align: center
-
- Creating new bindings
-
-Each module of the generator system has an specific role.
-
-1. Provide enough data about the classes and functions.
-2. Generate valid code, with modifications from typesystems and injected codes.
-3. Modify the API to expose the objects in a way that fits you target language best.
-4. Insert customizations where handwritten code is needed.
-
-.. figure:: images/shibokenqtarch.png
- :scale: 80
- :align: center
-
- Runtime architecture
-
-The newly created binding will run on top of Shiboken which takes
-care of interfacing Python and the underlying C++ library.
-
-Handwritten inputs
-==================
-
-Creating new bindings involves creating two pieces of "code": the typesystem and
-the inject code.
-
-:typesystem: XML files that provides the developer with a tool to customize the
- way that the generators will see the classes and functions. For
- example, functions can be renamed, have its signature changed and
- many other actions.
-:inject code: allows the developer to insert handwritten code where the generated
- code is not suitable or needs some customization.
-
-.. _command-line:
-
-Command line options
-********************
-
-Usage
------
-
-::
-
- shiboken [options] header-file typesystem-file
-
-
-Options
--------
-
-``--disable-verbose-error-messages``
- Disable verbose error messages. Turn the CPython code hard to debug but saves a few kilobytes
- in the generated binding.
-
-.. _parent-heuristic:
-
-``--enable-parent-ctor-heuristic``
- This flag enable an useful heuristic which can save a lot of work related to object ownership when
- writing the typesystem.
- For more info, check :ref:`ownership-parent-heuristics`.
-
-.. _pyside-extensions:
-
-``--enable-pyside-extensions``
- Enable pyside extensions like support for signal/slots. Use this if you are creating a binding based
- on PySide.
-
-.. _return-heuristic:
-
-``--enable-return-value-heuristic``
- Enable heuristics to detect parent relationship on return values.
- For more info, check :ref:`return-value-heuristics`.
-
-.. _avoid-protected-hack:
-
-``--avoid-protected-hack``
- Avoid the use of the '#define protected public' hack.
-
-.. _use-isnull-as-nb_nonzero:
-
-``--use-isnull-as-nb_nonzero``
- If a class have an isNull() const method, it will be used to
- compute the value of boolean casts
-
-.. _api-version:
-
-``--api-version=<version>``
- Specify the supported api version used to generate the bindings.
-
-.. _documentation-only:
-
-``--documentation-only``
- Do not generate any code, just the documentation.
-
-.. _drop-type-entries:
-
-``--drop-type-entries="<TypeEntry0>[;TypeEntry1;...]"``
- Semicolon separated list of type system entries (classes, namespaces,
- global functions and enums) to be dropped from generation.
-
-.. _generation-set:
-
-``--generation-set``
- Generator set to be used (e.g. qtdoc).
-
-.. _skip-deprecated:
-
-``--skip-deprecated``
- Skip deprecated functions.
-
-.. _diff:
-
-``--diff``
- Print a diff of wrapper files.
-
-.. _dryrun:
-
-``--dryrun``
- Dry run, do not generate wrapper files.
-
-.. _--project-file:
-
-``--project-file=<file>``
- Text file containing a description of the binding project.
- Replaces and overrides command line arguments.
-
-.. _include-paths:
-
-``-I<path>, --include-paths=<path>[:<path>:...]``
- Include paths used by the C++ parser.
-
-... _system-include-paths:
-
-``-isystem<path>, --system-include-paths=<path>[:<path>:...]``
- System include paths used by the C++ parser
-
-.. _framework-include-paths:
-
-``-F<path>, --framework-include-paths=<path>[:<path>:...]``
- Framework include paths used by the C++ parser
-
-.. _language-level:
-
-``--language-level=, -std=<level>``
- C++ Language level (c++11..c++17, default=c++14)
-
-.. _typesystem-paths:
-
-``-T<path>, --typesystem-paths=<path>[:<path>:...]``
- Paths used when searching for type system files.
-
-.. _output-directory:
-
-``--output-directory=[dir]``
- The directory where the generated files will be written.
-
-.. _license-file=[license-file]:
-
-``--license-file=[license-file]``
- File used for copyright headers of generated files.
-
-.. _no-suppress-warnings:
-
-``--no-suppress-warnings``
- Show all warnings.
-
-.. _silent:
-
-``--silent``
- Avoid printing any message.
-
-.. _debug-level:
-
-``--debug-level=[sparse|medium|full]``
- Set the debug level.
-
-.. _help:
-
-``--help``
- Display this help and exit.
-
-.. _version:
-
-``--version``
- Output version information and exit.
-
-QtDocGenerator Options
-----------------------
-
-.. _doc-parser:
-
-``--doc-parser=<parser>``
- The documentation parser used to interpret the documentation
- input files (qdoc|doxygen).
-
-.. _documentation-code-snippets-dir:
-
-``--documentation-code-snippets-dir=<dir>``
- Directory used to search code snippets used by the documentation.
-
-.. _documentation-data-dir:
-
-``--documentation-data-dir=<dir>``
- Directory with XML files generated by documentation tool.
-
-.. _documentation-extra-sections-dir=<dir>:
-
-``--documentation-extra-sections-dir=<dir>``
- Directory used to search for extra documentation sections.
-
-.. _library-source-dir:
-
-``--library-source-dir=<dir>``
- Directory where library source code is located.
-
-.. _additional-documentation:
-
-``--additional-documentation=<file>``
- List of additional XML files to be converted to .rst files
- (for example, tutorials).
-
-.. _project-file:
-
-********************
-Binding Project File
-********************
-
-Instead of directing the Generator behavior via command line, the binding
-developer can write a text project file describing the same information, and
-avoid the hassle of a long stream of command line arguments.
-
-.. _project-file-structure:
-
-The project file structure
-==========================
-
-Here follows a comprehensive example of a generator project file.
-
- .. code-block:: ini
-
- [generator-project]
- generator-set = path/to/generator/CHOICE_GENERATOR
- header-file = DIR/global.h" />
- typesystem-file = DIR/typesystem_for_your_binding.xml
- output-directory location="OUTPUTDIR" />
- include-path = path/to/library/being/wrapped/headers/1
- include-path = path/to/library/being/wrapped/headers/2
- typesystem-path = path/to/directory/containing/type/system/files/1
- typesystem-path = path/to/directory/containing/type/system/files/2
- enable-parent-ctor-heuristic
-
-
-Project file tags
-=================
-
-The generator project file tags are in direct relation to the
-:ref:`command line arguments <command-line>`. All of the current command line
-options provided by |project| were already seen on the
-:ref:`project-file-structure`, for new command line options provided by
-additional generator modules (e.g.: qtdoc, Shiboken) could also be used in the
-generator project file following simple conversion rules.
-
-For tags without options, just write as an empty tag without any attributes.
-Example:
-
- .. code-block:: bash
-
- --BOOLEAN-ARGUMENT
-
-becomes
-
- .. code-block:: ini
-
- BOOLEAN-ARGUMENT
-
-and
-
- .. code-block:: bash
-
- --VALUE-ARGUMENT=VALUE
-
-becomes
-
- .. code-block:: ini
-
- VALUE-ARGUMENT = VALUE
-
-
diff --git a/sources/shiboken2/doc/shibokenmodule.rst b/sources/shiboken2/doc/shibokenmodule.rst
deleted file mode 100644
index 150998ccd..000000000
--- a/sources/shiboken2/doc/shibokenmodule.rst
+++ /dev/null
@@ -1,79 +0,0 @@
-.. module:: shiboken
-
-.. |maya| unicode:: Maya U+2122
-
-Shiboken module
-***************
-
-Functions
-^^^^^^^^^
-
-.. container:: function_list
-
- * def :meth:`isValid<shiboken.isValid>` (obj)
- * def :meth:`wrapInstance<shiboken.wrapInstance>` (address, type)
- * def :meth:`getCppPointer<shiboken.getCppPointer>` (obj)
- * def :meth:`delete<shiboken.delete>` (obj)
- * def :meth:`isOwnedByPython<shiboken.isOwnedByPython>` (obj)
- * def :meth:`wasCreatedByPython<shiboken.wasCreatedByPython>` (obj)
- * def :meth:`dump<shiboken.dump>` (obj)
-
-Detailed description
-^^^^^^^^^^^^^^^^^^^^
-
-This Python module can be used to access internal information related to our
-binding technology. Access to this internal information is required to e.g.:
-integrate PySide with Qt based programs that offer Python scripting like |maya|
-or just for debug purposes.
-
-Some function description refer to "Shiboken based objects", wich means
-Python objects instances of any Python Type created using Shiboken.
-
-
-.. function:: isValid(obj)
-
- Given a Python object, returns True if the object methods can be called
- without an exception being thrown. A Python wrapper becomes invalid when
- the underlying C++ object is destroyed or unreachable.
-
-.. function:: wrapInstance(address, type)
-
- Creates a Python wrapper for a C++ object instantiated at a given memory
- address - the returned object type will be the same given by the user.
-
- The type must be a Shiboken type, the C++ object will not be
- destroyed when the returned Python object reach zero references.
-
- If the address is invalid or doesn't point to a C++ object of given type
- the behavior is undefined.
-
-.. function:: getCppPointer(obj)
-
- Returns a tuple of longs that contain the memory addresses of the
- C++ instances wrapped by the given object.
-
-.. function:: delete(obj)
-
- Deletes the C++ object wrapped by the given Python object.
-
-.. function:: isOwnedByPython(obj)
-
- Given a Python object, returns True if Python is responsible for deleting
- the underlying C++ object, False otherwise.
-
- If the object was not a Shiboken based object, a TypeError is
- thrown.
-
-.. function:: wasCreatedByPython(obj)
-
- Returns true if the given Python object was created by Python.
-
-.. function:: dump(obj)
-
- Returns a string with implementation-defined information about the
- object.
- This method should be used **only** for debug purposes by developers
- creating their own bindings as no guarantee is provided that
- the string format will be the same across different versions.
-
- If the object is not a Shiboken based object, a TypeError is thrown.
diff --git a/sources/shiboken2/doc/typesystem.rst b/sources/shiboken2/doc/typesystem.rst
deleted file mode 100644
index 01c19ac7d..000000000
--- a/sources/shiboken2/doc/typesystem.rst
+++ /dev/null
@@ -1,57 +0,0 @@
-Type System Reference
-=====================
-
-The typesystem is used by a binding generator or any other software using the APIExtractor library
-to map a C++ library API onto a higher level language.
-
-The typesystem specification is a handwritten XML document listing the types
-that will be available in the generated target language API; types that are not
-declared in the specification will be ignored along with everything depending on
-them. In addition, it is possible to manipulate and modify types and functions.
-It is even possible to use the typesystem specification to inject arbitrary
-code into the source files, such as an extra member function.
-
-Below there is a complete reference guide to the various nodes (XML tags) of the typesystem.
-For usage examples, take a look at the typesystem files used to generate PySide2. These files
-can be found in the PySide2/<QT_MODULE_NAME> directory of the PySide2 package.
-
-Define types
-------------
-
-.. toctree::
- :maxdepth: 1
-
- typesystem_specifying_types.rst
-
-Modifying types
----------------
-
-.. toctree::
- :maxdepth: 1
-
- typesystem_arguments.rst
- typesystem_codeinjection.rst
- typesystem_converters.rst
- typesystem_templates.rst
- typesystem_modify_function.rst
- typesystem_manipulating_objects.rst
- typesystem_conversionrule.rst
- typesystem_documentation.rst
- typesystem_variables.rst
-
-Object ownership
-----------------
-
-.. toctree::
- :maxdepth: 1
-
- typesystem_ownership.rst
-
-Extra options and Python caveats
---------------------------------
-
-.. toctree::
- :maxdepth: 1
-
- typesystem_solving_compilation.rst
- typesystem_sequenceprotocol.rst
diff --git a/sources/shiboken2/doc/typesystem_arguments.rst b/sources/shiboken2/doc/typesystem_arguments.rst
deleted file mode 100644
index 28a5c80bc..000000000
--- a/sources/shiboken2/doc/typesystem_arguments.rst
+++ /dev/null
@@ -1,206 +0,0 @@
-.. _modifying-arguments:
-
-Modifying Arguments
--------------------
-
-.. _conversionrule:
-
-conversion-rule
-^^^^^^^^^^^^^^^
-
- The conversion-rule node allows you to write customized code to convert
- the given argument between the target language and C++, and it is a child of the modify-argument node:
-
- .. code-block:: xml
-
- <modify-argument index="2">
- <!-- for the second argument of the function -->
- <conversion-rule class="target | native">
- // the code
- </conversion-rule>
- </modify-argument>
-
- This node is typically used in combination with the replace-type and
- remove-argument nodes. The given code is used instead of the generator's
- conversion code.
-
- Writing %N in the code (where N is a number), will insert the name of the
- nth argument. Alternatively, %in and %out which will be replaced with the
- name of the conversion's input and output variable, respectively. Note the
- output variable must be declared explicitly, for example:
-
- .. code-block:: xml
-
- <conversion-rule class="native">
- bool %out = (bool) %in;
- </conversion-rule>
-
- .. note:: You can also use the conversion-rule node to specify :ref:`a conversion code which will be used instead of the generator's conversion code everywhere for a given type <conversion-rule-on-types>`.
-
-.. _remove-argument:
-
-remove-argument
-^^^^^^^^^^^^^^^
-
- The remove-argument node removes the given argument from the function's
- signature, and it is a child of the modify-argument node.
-
- .. code-block:: xml
-
- <modify-argument>
- <remove-argument />
- </modify-argument>
-
-.. _rename-to:
-
-rename to
-^^^^^^^^^
-
- The 'rename to' node is used to rename a argument and use this new name in the generated code.
-
- .. code-block:: xml
-
- <modify-argument>
- <rename to='...' />
- </modify-argument>
-
-.. _remove-default-expression:
-
-remove-default-expression
-^^^^^^^^^^^^^^^^^^^^^^^^^
-
- The remove-default-expression node disables the use of the default expression
- for the given argument, and it is a child of the modify-argument node.
-
- .. code-block:: xml
-
- <modify-argument...>
- <remove-default-expression />
- </modify-argument>
-
-.. _replace-default-expression:
-
-replace-default-expression
-^^^^^^^^^^^^^^^^^^^^^^^^^^
-
- The replace-default-expression node replaces the specified argument with the
- expression specified by the ``with`` attribute, and it is a child of the
- modify-argument node.
-
- .. code-block:: xml
-
- <modify-argument>
- <replace-default-expression with="..." />
- </modify-argument>
-
-.. _replace-type:
-
-replace-type
-^^^^^^^^^^^^
-
- The replace-type node replaces the type of the given argument to the one
- specified by the ``modified-type`` attribute, and it is a child of the
- modify-argument node.
-
- .. code-block:: xml
-
- <modify-argument>
- <replace-type modified-type="..." />
- </modify-argument>
-
- If the new type is a class, the ``modified-type`` attribute must be set to
- the fully qualified name (including name of the package as well as the class
- name).
-
-.. _define-ownership:
-
-define-ownership
-^^^^^^^^^^^^^^^^
-
- The define-ownership tag indicates that the function changes the ownership
- rules of the argument object. The ``class`` attribute specifies the class of
- function where to inject the ownership altering code. The ``owner`` attribute
- specifies the new ownership of the object. It accepts the following values:
-
- * target: the target language will assume full ownership of the object.
- The native resources will be deleted when the target language
- object is finalized.
- * c++: The native code assumes full ownership of the object. The target
- language object will not be garbage collected.
- * default: The object will get default ownership, depending on how it
- was created.
-
- .. code-block:: xml
-
- <modify-argument>
- <define-ownership class="target | native"
- owner="target | c++ | default" />
- </modify-argument>
-
-.. _reference-count:
-
-reference-count
-^^^^^^^^^^^^^^^
-
- The reference-count tag dictates how an argument should be handled by the
- target language reference counting system (if there is any), it also indicates
- the kind of relationship the class owning the function being modified has with
- the argument. For instance, in a model/view relation a view receiving a model
- as argument for a **setModel** method should increment the model's reference
- counting, since the model should be kept alive as much as the view lives.
- Remember that out hypothetical view could not become parent of the model,
- since the said model could be used by other views as well.
- The ``action`` attribute specifies what should be done to the argument
- reference counting when the modified method is called. It accepts the
- following values:
-
- * add: increments the argument reference counter.
- * add-all: increments the reference counter for each item in a collection.
- * remove: decrements the argument reference counter.
- * set: will assign the argument to the variable containing the reference.
- * ignore: does nothing with the argument reference counter
- (sounds worthless, but could be used in situations
- where the reference counter increase is mandatory
- by default).
-
- .. code-block:: xml
-
- <modify-argument>
- <reference-count action="add|add-all|remove|set|ignore" variable-name="..." />
- </modify-argument>
-
-
- The variable-name attribute specifies the name used for the variable that
- holds the reference(s).
-
-.. _replace-value:
-
-replace-value
-^^^^^^^^^^^^^
-
- The ``replace-value`` attribute lets you replace the return statement of a
- function with a fixed string. This attribute can only be used for the
- argument at ``index`` 0, which is always the function's return value.
-
- .. code-block:: xml
-
- <modify-argument index="0" replace-value="this"/>
-
-.. _parent:
-
-parent
-^^^^^^
-
- The parent node lets you define the argument parent which will
- take ownership of argument and will destroy the C++ child object when the
- parent is destroyed.
-
- .. code-block:: xml
-
- <modify-argument index="1">
- <parent index="this" action="add | remove" />
- </modify-argument>
-
- In the ``index`` argument you must specify the parent argument. The action
- *add* creates a parent link between objects, while *remove* will undo the
- parentage relationship.
diff --git a/sources/shiboken2/doc/typesystem_codeinjection.rst b/sources/shiboken2/doc/typesystem_codeinjection.rst
deleted file mode 100644
index c891fd2cd..000000000
--- a/sources/shiboken2/doc/typesystem_codeinjection.rst
+++ /dev/null
@@ -1,399 +0,0 @@
-.. _codeinjectionsemantics:
-
-************************
-Code Injection Semantics
-************************
-
-:std:doc:`API Extractor <shibokengenerator>` provides the
-:ref:`inject-code <inject-code>` tag
-allowing the user to put custom written code to on specific locations of the generated code.
-Yet this is only part of what is needed to generate proper binding code, where the custom code
-should be written to depends upon the technology used on the generated binding code.
-
-This is the ``inject-code`` tag options that matters to |project|.
-
- .. code-block:: xml
-
- <inject-code class="native | target" position="beginning | end">
- // custom code
- </inject-code>
-
-
-Conventions
-===========
-
-**C++ Wrapper**
- This term refers to a generated C++ class that extends a class from the
- wrapped library. It is used only when a wrapped C++ class is polymorphic,
- i.e. it has or inherits any virtual methods.
-
-**Python Wrapper**
- The code that exports the C++ wrapped class to Python. **Python wrapper**
- refers to all the code needed to export a C++ class to Python, and
- **Python method/function wrapper** means the specific function that calls
- the C++ method/function on behalf of Python.
-
-**Native**
- This is a possible value for the ``class`` attribute of the ``inject-code``
- tag, it means things more akin to the C++ side.
-
-**Target**
- Another ``class`` attribute value, it indicates things more close to the
- Python side.
-
-inject-code tag
-===============
-
-The following table describes the semantics of ``inject-code`` tag as used on
-|project|.
-
- +---------------+------+---------+--------------------------------------------------------------+
- |Parent Tag |Class |Position |Meaning |
- +===============+======+=========+==============================================================+
- |value-type, |native|beginning|Write to the beginning of a class wrapper ``.cpp`` file, right|
- |object-type | | |after the ``#include`` clauses. A common use would be to write|
- | | | |prototypes for custom functions whose definitions are put on a|
- | | | |``native/end`` code injection. |
- | | +---------+--------------------------------------------------------------+
- | | |end |Write to the end of a class wrapper ``.cpp`` file. Could be |
- | | | |used to write custom/helper functions definitions for |
- | | | |prototypes declared on ``native/beginning``. |
- | +------+---------+--------------------------------------------------------------+
- | |target|beginning|Put custom code on the beginning of the wrapper initializer |
- | | | |function (``init_CLASS(PyObject *module)``). This could be |
- | | | |used to manipulate the ``PyCLASS_Type`` structure before |
- | | | |registering it on Python. |
- | | +---------+--------------------------------------------------------------+
- | | |end |Write the given custom code at the end of the class wrapper |
- | | | |initializer function (``init_CLASS(PyObject *module)``). The |
- | | | |code here will be executed after all the wrapped class |
- | | | |components have been initialized. |
- +---------------+------+---------+--------------------------------------------------------------+
- |modify-function|native|beginning|Code here is put on the virtual method override of a C++ |
- | | | |wrapper class (the one responsible for passing C++ calls to a |
- | | | |Python override, if there is any), right after the C++ |
- | | | |arguments have been converted but before the Python call. |
- | | +---------+--------------------------------------------------------------+
- | | |end |This code injection is put in a virtual method override on the|
- | | | |C++ wrapper class, after the call to Python and before |
- | | | |dereferencing the Python method and tuple of arguments. |
- | +------+---------+--------------------------------------------------------------+
- | |target|beginning|This code is injected on the Python method wrapper |
- | | | |(``PyCLASS_METHOD(...)``), right after the decisor have found |
- | | | |which signature to call and also after the conversion of the |
- | | | |arguments to be used, but before the actual call. |
- | | +---------+--------------------------------------------------------------+
- | | |end |This code is injected on the Python method wrapper |
- | | | |(``PyCLASS_METHOD(...)``), right after the C++ method call, |
- | | | |but still inside the scope created by the overload for each |
- | | | |signature. |
- | +------+---------+--------------------------------------------------------------+
- | |shell |beginning|Used only for virtual functions. The code is injected when the|
- | | | |function does not has a Python implementation, then the code |
- | | | |is inserted before c++ call |
- | | +---------+--------------------------------------------------------------+
- | | |end |Same as above, but the code is inserted after c++ call |
- +---------------+------+---------+--------------------------------------------------------------+
- |typesystem |native|beginning|Write code to the beginning of the module ``.cpp`` file, right|
- | | | |after the ``#include`` clauses. This position has a similar |
- | | | |purpose as the ``native/beginning`` position on a wrapper |
- | | | |class ``.cpp`` file, namely write function prototypes, but not|
- | | | |restricted to this use. |
- | | +---------+--------------------------------------------------------------+
- | | |end |Write code to the end of the module ``.cpp`` file. Usually |
- | | | |implementations for function prototypes inserted at the |
- | | | |beginning of the file with a ``native/beginning`` code |
- | | | |injection. |
- | +------+---------+--------------------------------------------------------------+
- | |target|beginning|Insert code at the start of the module initialization function|
- | | | |(``initMODULENAME()``), before the calling ``Py_InitModule``. |
- | | +---------+--------------------------------------------------------------+
- | | |end |Insert code at the end of the module initialization function |
- | | | |(``initMODULENAME()``), but before the checking that emits a |
- | | | |fatal error in case of problems importing the module. |
- +---------------+------+---------+--------------------------------------------------------------+
-
-
-Anatomy of Code Injection
-=========================
-
-To make things clear let's use a simplified example of generated wrapper code
-and the places where each kind of code injection goes.
-
-Below is the example C++ class for whom wrapper code will be generated.
-
- .. code-block:: c++
-
- class InjectCode {
- public:
- InjectCode();
- double overloadedMethod(int arg);
- double overloadedMethod(double arg);
- virtual int virtualMethod(int arg);
- };
-
-From the C++ class, |project| will generate a ``injectcode_wrapper.cpp`` file
-with the binding code. The next section will use a simplified version of the
-generated wrapper code with the injection spots marked with comments.
-
-Noteworthy Cases
-----------------
-
-The type system description system gives the binding developer a lot of
-flexibility, which is power, which comes with responsibility. Some modifications
-to the wrapped API will not be complete without some code injection.
-
-
-Removing arguments and setting a default values for them
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-A simple case is when a function have one argument removed, as when the C++
-method ``METHOD(ARG)`` is modified to be used from Python as ``METHOD()``;
-of course the binding developer must provide some guidelines to the generator
-on what to do to call it. The most common solution is to remove the argument and
-set a default value for it at the same time, so the original C++ method could be
-called without problems.
-
-Removing arguments and calling the method with your own hands
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-If the argument is removed and no default value is provided, the generator will
-not write any call to the method and expect the ``modify-function - target/beginning``
-code injection to call the original C++ method on its own terms. If even this
-custom code is not provided the generator will put an ``#error`` clause to
-prevent compilation of erroneous binding code.
-
-Calling the method with your own hands always!
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-If your custom code to be injected contains a call to the wrapped C++ method,
-it surely means that you don't want the generator to write another call to the
-same method. As expected |project| will detect the user written call on the code
-injection and will not write its own call, but for this to work properly the
-binding developer must use the template variable ``%FUNCTION_NAME`` instead
-of writing the actual name of the wrapped method/function.
-
-In other words, use
-
- .. code-block:: xml
-
- <inject-code class="target" position="beginning | end">
- %CPPSELF.originalMethodName();
- </inject-code>
-
-
-instead of
-
-
- .. code-block:: xml
-
- <inject-code class="target" position="beginning | end">
- %CPPSELF.%FUNCTION_NAME();
- </inject-code>
-
-
-Code Injection for Functions/Methods
-====================================
-
-
-.. _codeinjecting_method_native:
-
-On The Native Side
-------------------
-
-Notice that this is only used when there is a C++ wrapper, i.e. the wrapped
-class is polymorphic.
-
- .. code-block:: c++
-
- int InjectCodeWrapper::virtualMethod(int arg)
- {
- PyObject* method = BindingManager::instance().getOverride(this, "virtualMethod");
- if (!py_override)
- return this->InjectCode::virtualMethod(arg);
-
- (... here C++ arguments are converted to Python ...)
-
- // INJECT-CODE: <modify-function><inject-code class="native" position="beginning">
- // Uses: pre method call custom code, modify the argument before the
- // Python call.
-
- (... Python method call goes in here ...)
-
- // INJECT-CODE: <modify-function><inject-code class="native" position="end">
- // Uses: post method call custom code, modify the result before delivering
- // it to C++ caller.
-
- (... Python method and argument tuple are dereferenced here ...)
-
- return Shiboken::Converter<int>::toCpp(method_result);
- }
-
-
-On The Target Side
-------------------
-
-All the overloads of a method from C++ are gathered together on a single Python
-method that uses an overload decisor to call the correct C++ method based on the
-arguments passed by the Python call. Each overloaded method signature has its
-own ``beginning`` and ``end`` code injections.
-
- .. code-block:: c++
-
- static PyObject*
- PyInjectCode_overloadedMethod(PyObject* self, PyObject* arg)
- {
- PyObject* py_result = 0;
- if (PyFloat_Check(arg)) {
- double cpp_arg0 = Shiboken::Converter<double >::toCpp(arg);
-
- // INJECT-CODE: <modify-function><inject-code class="target" position="beginning">
- // Uses: pre method call custom code.
-
- py_result = Shiboken::Converter<double >::toPython(
- PyInjectCode_cptr(self)->InjectCode::overloadedMethod(cpp_arg0)
- );
-
- // INJECT-CODE: <modify-function><inject-code class="target" position="end">
- // Uses: post method call custom code.
-
- } else if (PyNumber_Check(arg)) {
- (... other overload calling code ...)
- } else goto PyInjectCode_overloadedMethod_TypeError;
-
- if (PyErr_Occurred() || !py_result)
- return 0;
-
- return py_result;
-
- PyInjectCode_overloadedMethod_TypeError:
- PyErr_SetString(PyExc_TypeError, "'overloadedMethod()' called with wrong parameters.");
- return 0;
- }
-
-
-.. _codeinjecting_classes:
-
-Code Injection for Wrapped Classes
-==================================
-
-.. _codeinjecting_classes_native:
-
-On The Native Side
-------------------
-
-Those injections go in the body of the ``CLASSNAME_wrapper.cpp`` file for the
-wrapped class.
-
- .. code-block:: c++
-
- // Start of ``CLASSNAME_wrapper.cpp``
- #define protected public
- // default includes
- #include <shiboken.h>
- (...)
- #include "injectcode_wrapper.h"
- using namespace Shiboken;
-
- // INJECT-CODE: <value/object-type><inject-code class="native" position="beginning">
- // Uses: prototype declarations
-
- (... C++ wrapper virtual methods, if any ...)
-
- (... Python wrapper code ...)
-
- PyAPI_FUNC(void)
- init_injectcode(PyObject *module)
- {
- (...)
- }
-
- (...)
-
- // INJECT-CODE: <value/object-type><inject-code class="native" position="end">
- // Uses: definition of functions prototyped at ``native/beginning``.
-
- // End of ``CLASSNAME_wrapper.cpp``
-
-
-.. _codeinjecting_classes_target:
-
-On The Target Side
-------------------
-
-Code injections to the class Python initialization function.
-
- .. code-block:: c++
-
- // Start of ``CLASSNAME_wrapper.cpp``
-
- (...)
-
- PyAPI_FUNC(void)
- init_injectcode(PyObject *module)
- {
- // INJECT-CODE: <value/object-type><inject-code class="target" position="beginning">
- // Uses: Alter something in the PyInjectCode_Type (tp_flags value for example)
- // before registering it.
-
- if (PyType_Ready(&PyInjectCode_Type) < 0)
- return;
-
- Py_INCREF(&PyInjectCode_Type);
- PyModule_AddObject(module, "InjectCode",
- ((PyObject*)&PyInjectCode_Type));
-
- // INJECT-CODE: <value/object-type><inject-code class="target" position="end">
- // Uses: do something right after the class is registered, like set some static
- // variable injected on this same file elsewhere.
- }
-
- (...)
-
- // End of ``CLASSNAME_wrapper.cpp``
-
-Code Injection for Modules
-==========================
-
-The C++ libraries are wrapped as Python modules, a collection of classes,
-functions, enums and namespaces. |project| creates wrapper files for all of
-them and also one extra ``MODULENAME_module_wrapper.cpp`` to register the whole
-module. Code injection xml tags who have the ``typesystem`` tag as parent will
-be put on this file.
-
-On The Native Side
-------------------
-
-This works exactly as the class wrapper code injections :ref:`codeinjecting_classes_native`.
-
-On The Target Side
-------------------
-
-This is very similar to class wrapper code injections :ref:`codeinjecting_classes_target`.
-Notice that the inject code at ``target/end`` is inserted before the check for errors
-to prevent bad custom code to pass unnoticed.
-
- .. code-block:: c++
-
- // Start of ``MODULENAME_module_wrapper.cpp``
-
- (...)
- initMODULENAME()
- {
- // INJECT-CODE: <typesystem><inject-code class="target" position="beginning">
- // Uses: do something before the module is created.
-
- PyObject* module = Py_InitModule("MODULENAME", MODULENAME_methods);
-
- (... initialization of wrapped classes, namespaces, functions and enums ...)
-
- // INJECT-CODE: <typesystem><inject-code class="target" position="end">
- // Uses: do something after the module is registered and initialized.
-
- if (PyErr_Occurred())
- Py_FatalError("can't initialize module sample");
- }
-
- (...)
-
- // Start of ``MODULENAME_module_wrapper.cpp``
diff --git a/sources/shiboken2/doc/typesystem_conversionrule.rst b/sources/shiboken2/doc/typesystem_conversionrule.rst
deleted file mode 100644
index 27e7a72de..000000000
--- a/sources/shiboken2/doc/typesystem_conversionrule.rst
+++ /dev/null
@@ -1,116 +0,0 @@
-.. _conversion-rule-tag:
-
-Conversion Rule Tag
--------------------
-
-.. _conversion-rule:
-
-conversion-rule
-^^^^^^^^^^^^^^^
-
- The **conversion-rule** tag specifies how a **primitive-type**, a **container-type**,
- or a **value-type** may be converted to and from the native C++ language types to the
- target language types.
-
- .. code-block:: xml
-
- <value-type>
- <conversion-rule>
- <native-to-target>
- // Code to convert a native value to a target language object.
- </native-to-target>
- <target-to-native>
- <add-conversion type='TARGETTYPEA' check='TARGETTYPEA_CHECK(%in)'>
- // Code to convert target language type object of type TARGETTYPEA
- // to the C++ native type represented by the value/primitive/container-type.
- </add-conversion>
- <add-conversion type='TARGETTYPEB' check='TARGETTYPEB_CHECK(%in)'>
- // Code to convert target language type object of type TARGETTYPEB
- // to the C++ native type represented by the value/primitive/container-type.
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </value-type>
-
- The example above show the structure of a complete conversion rule. Each of the
- child tags comprising the conversion rule are described in their own sections
- below.
-
-
-.. _native-to-target:
-
-native-to-target
-^^^^^^^^^^^^^^^^
-
- The **native-to-target** tag tells how to convert a native C++ value to its
- target language equivalent. The text inside the tag is a C++ code the takes
- an input value an does what's needed to convert it to the output value.
- ``insert-template`` tags may be used to insert commonly repeating code.
-
- .. code-block:: xml
-
- <conversion-rule>
- <native-to-target>
- // Code to convert a native value to a target language object.
- </native-to-target>
- </conversion-rule>
-
- Use the replace node to modify the template code.
- Notice that the generator must provide type system variables for the input
- and output values and types, namely **%in**, **%out**, **%INTYPE** and
- **%OUTTYPE**. In the case of container types, **%INTYPE** refers to the
- full container type (e.g. **"list<int>"**) and **%INTYPE_0**, **%INTYPE_1**,
- **%INTYPE_#**, should be replaced by the types used in the container template
- (e.g. **%INTYPE_0** correspondes to **"int"** for **"list<int>"**).
-
- The ``file`` and ``snippet`` attributes are also supported (see :ref:`inject-code` nodes).
-
-.. _target-to-native:
-
-target-to-native
-^^^^^^^^^^^^^^^^
-
- The **target-to-native** tag encloses at least one, but usually many, conversions
- from target language values to C++ native values. The *optional* attribute
- ``replace`` tells if the target language to C++ conversions will be added to, or if
- they will replace the implicit conversions collected by *ApiExtractor*. The default
- value for it is *yes*.
-
-
- .. code-block:: xml
-
- <conversion-rule>
- <target-to-native replace='yes|no'>\
- // List of target to native conversions meant to replace or expand
- // the already existing implicit conversions.
- </target-to-native>
- </conversion-rule>
-
-
-.. _add-conversion:
-
-add-conversion
-^^^^^^^^^^^^^^
-
- Each **add-conversion** tag adds a rule for conversion of a target language type,
- indicated by the ``type`` attribute, to the C++ native type represented by the
- **primitive-type**, a **container-type**, or **value-type**, to which the parent
- **conversion-rule** belongs.
-
- .. code-block:: xml
-
- <target-to-native>
- <add-conversion type='TARGETTYPE' check='TARGETTYPECHECK(%in)'>
- // Code to convert target language type object of type TARGETTYPE_A
- // to the C++ native type represented by the value/primitive/container-type.
- </add-conversion>
- <target-to-native>
-
- The ``check`` attribute tells how a target value should be checked to see if it belongs to
- the type expected. This attribute is *optional*, for it can be derived from the ``type``
- attribute, but it isn't unusual that some special check is needed. The variables
- **%in**, **%out**, **%INTYPE**, **%INTYPE_#**, and **%OUTTYPE**, must be provided by
- the generator as in the ``native-to-target`` tag.
-
- The ``file`` and ``snippet`` attributes are also supported (see :ref:`inject-code` nodes).
-
diff --git a/sources/shiboken2/doc/typesystem_converters.rst b/sources/shiboken2/doc/typesystem_converters.rst
deleted file mode 100644
index 872daa187..000000000
--- a/sources/shiboken2/doc/typesystem_converters.rst
+++ /dev/null
@@ -1,291 +0,0 @@
-****************************
-User Defined Type Conversion
-****************************
-
-In the process of creating Python bindings of a C++ library, most of the C++
-classes will have wrappers representing them in Python land.
-But there may be other classes that are very simple and/or have a Python type
-as a direct counter part. (Example: a "Complex" class, that represents complex
-numbers, has a Python equivalent in the "complex" type.) Such classes, instead
-of getting a Python wrapper, normally have conversions rules, from Python to
-C++ and vice-versa.
-
- .. code-block:: c++
-
- // C++ class
- struct Complex {
- Complex(double real, double imag);
- double real() const;
- double imag() const;
- };
-
- // Converting from C++ to Python using the CPython API:
- PyObject* pyCpxObj = PyComplex_FromDoubles(complex.real(), complex.imag());
-
- // Converting from Python to C++:
- double real = PyComplex_RealAsDouble(pyCpxObj);
- double imag = PyComplex_ImagAsDouble(pyCpxObj);
- Complex cpx(real, imag);
-
-
-For the user defined conversion code to be inserted in the proper places,
-the "<conversion-rule>" tag must be used.
-
- .. code-block:: xml
-
- <primitive-type name="Complex" target-lang-api-name="PyComplex">
- <include file-name="complex.h" location="global"/>
-
- <conversion-rule>
-
- <native-to-target>
- return PyComplex_FromDoubles(%in.real(), %in.imag());
- </native-to-target>
-
- <target-to-native>
- <!-- The 'check' attribute can be derived from the 'type' attribute,
- it is defined here to test the CHECKTYPE type system variable. -->
- <add-conversion type="PyComplex" check="%CHECKTYPE[Complex](%in)">
- double real = PyComplex_RealAsDouble(%in);
- double imag = PyComplex_ImagAsDouble(%in);
- %out = %OUTTYPE(real, imag);
- </add-conversion>
- </target-to-native>
-
- </conversion-rule>
-
- </primitive-type>
-
-
-The details will be given later, but the gist of it are the tags
-:ref:`native-to-target <native-to-target>`, which has only one conversion from C++ to Python, and
-:ref:`native-to-native <target-to-native>`, that may define the conversion of multiple Python types
-to C++'s "Complex" type.
-
-.. image:: images/converter.png
- :height: 240px
- :align: center
-
-|project| expects the code for :ref:`native-to-target <native-to-target>`, to directly return the
-Python result of the conversion, and the added conversions inside the
-:ref:`target-to-native <target-to-native>` must attribute the Python to C++ conversion result to
-the :ref:`%out <out>` variable.
-
-Expanding on the last example, if the binding developer want a Python 2-tuple
-of numbers to be accepted by wrapped C++ functions with "Complex" arguments,
-an :ref:`add-conversion <add-conversion>` tag and a custom check must be added.
-Here's how to do it:
-
- .. code-block:: xml
-
- <!-- Code injection at module level. -->
- <inject-code class="native" position="beginning">
- static bool Check2TupleOfNumbers(PyObject* pyIn) {
- if (!PySequence_Check(pyIn) || !(PySequence_Size(pyIn) == 2))
- return false;
- Shiboken::AutoDecRef pyReal(PySequence_GetItem(pyIn, 0));
- if (!SbkNumber_Check(pyReal))
- return false;
- Shiboken::AutoDecRef pyImag(PySequence_GetItem(pyIn, 1));
- if (!SbkNumber_Check(pyImag))
- return false;
- return true;
- }
- </inject-code>
-
- <primitive-type name="Complex" target-lang-api-name="PyComplex">
- <include file-name="complex.h" location="global"/>
-
- <conversion-rule>
-
- <native-to-target>
- return PyComplex_FromDoubles(%in.real(), %in.imag());
- </native-to-target>
-
- <target-to-native>
-
- <add-conversion type="PyComplex">
- double real = PyComplex_RealAsDouble(%in);
- double imag = PyComplex_ImagAsDouble(%in);
- %out = %OUTTYPE(real, imag);
- </add-conversion>
-
- <add-conversion type="PySequence" check="Check2TupleOfNumbers(%in)">
- Shiboken::AutoDecRef pyReal(PySequence_GetItem(%in, 0));
- Shiboken::AutoDecRef pyImag(PySequence_GetItem(%in, 1));
- double real = %CONVERTTOCPP[double](pyReal);
- double imag = %CONVERTTOCPP[double](pyImag);
- %out = %OUTTYPE(real, imag);
- </add-conversion>
-
- </target-to-native>
-
- </conversion-rule>
-
- </primitive-type>
-
-
-.. _container_conversions:
-
-Container Conversions
-=====================
-
-Converters for :ref:`container-type <container-type>` are pretty much the same as for other type,
-except that they make use of the type system variables
-:ref:`%INTYPE_# <intype_n>` and :ref:`%OUTTYPE_# <outtype_n>`.
-|project| combines the conversion code for containers with the conversion
-defined (or automatically generated) for the containers.
-
- .. code-block:: xml
-
- <container-type name="std::map" type="map">
- <include file-name="map" location="global"/>
-
- <conversion-rule>
-
- <native-to-target>
- PyObject* %out = PyDict_New();
- %INTYPE::const_iterator it = %in.begin();
- for (; it != %in.end(); ++it) {
- %INTYPE_0 key = it->first;
- %INTYPE_1 value = it->second;
- PyDict_SetItem(%out,
- %CONVERTTOPYTHON[%INTYPE_0](key),
- %CONVERTTOPYTHON[%INTYPE_1](value));
- }
- return %out;
- </native-to-target>
-
- <target-to-native>
-
- <add-conversion type="PyDict">
- PyObject* key;
- PyObject* value;
- Py_ssize_t pos = 0;
- while (PyDict_Next(%in, &amp;pos, &amp;key, &amp;value)) {
- %OUTTYPE_0 cppKey = %CONVERTTOCPP[%OUTTYPE_0](key);
- %OUTTYPE_1 cppValue = %CONVERTTOCPP[%OUTTYPE_1](value);
- %out.insert(%OUTTYPE::value_type(cppKey, cppValue));
- }
- </add-conversion>
-
- </target-to-native>
- </conversion-rule>
- </container-type>
-
-
-.. _variables_and_functions:
-
-Variables & Functions
-=====================
-
-
-.. _in:
-
-**%in**
-
- Variable replaced by the C++ input variable.
-
-
-.. _out:
-
-**%out**
-
- Variable replaced by the C++ output variable. Needed to convey the
- result of a Python to C++ conversion.
-
-
-.. _intype:
-
-**%INTYPE**
-
- Used in Python to C++ conversions. It is replaced by the name of type for
- which the conversion is being defined. Don't use the type's name directly.
-
-
-.. _intype_n:
-
-**%INTYPE_#**
-
- Replaced by the name of the #th type used in a container.
-
-
-.. _outtype:
-
-**%OUTTYPE**
-
- Used in Python to C++ conversions. It is replaced by the name of type for
- which the conversion is being defined. Don't use the type's name directly.
-
-
-.. _outtype_n:
-
-**%OUTTYPE_#**
-
- Replaced by the name of the #th type used in a container.
-
-
-.. _checktype:
-
-**%CHECKTYPE[CPPTYPE]**
-
- Replaced by a |project| type checking function for a Python variable.
- The C++ type is indicated by ``CPPTYPE``.
-
-
-.. _oldconverters:
-
-Converting The Old Converters
-=============================
-
-If you use |project| for your bindings, and has defined some type conversions
-using the ``Shiboken::Converter`` template, then you must update your converters
-to the new scheme.
-
-Previously your conversion rules were declared in one line, like this:
-
-
- .. code-block:: xml
-
- <primitive-type name="Complex" target-lang-api-name="PyComplex">
- <include file-name="complex.h" location="global"/>
- <conversion-rule file="complex_conversions.h"/>
- </primitive-type>
-
-
-And implemented in a separate C++ file, like this:
-
-
- .. code-block:: c++
-
- namespace Shiboken {
- template<> struct Converter<Complex>
- {
- static inline bool checkType(PyObject* pyObj) {
- return PyComplex_Check(pyObj);
- }
- static inline bool isConvertible(PyObject* pyObj) {
- return PyComplex_Check(pyObj);
- }
- static inline PyObject* toPython(void* cppobj) {
- return toPython(*reinterpret_cast<Complex*>(cppobj));
- }
- static inline PyObject* toPython(const Complex& cpx) {
- return PyComplex_FromDoubles(cpx.real(), cpx.imag());
- }
- static inline Complex toCpp(PyObject* pyobj) {
- double real = PyComplex_RealAsDouble(pyobj);
- double imag = PyComplex_ImagAsDouble(pyobj);
- return Complex(real, imag);
- }
- };
- }
-
-
-In this case, the parts of the implementation that will be used in the new
-conversion-rule are the ones in the two last method
-``static inline PyObject* toPython(const Complex& cpx)`` and
-``static inline Complex toCpp(PyObject* pyobj)``. The ``isConvertible`` method
-is gone, and the ``checkType`` is now an attribute of the :ref:`add-conversion <add-conversion>`
-tag. Refer back to the first example in this page and you will be able to
-correlate the above template with the new scheme of conversion rule definition.
diff --git a/sources/shiboken2/doc/typesystem_documentation.rst b/sources/shiboken2/doc/typesystem_documentation.rst
deleted file mode 100644
index d73e43cb1..000000000
--- a/sources/shiboken2/doc/typesystem_documentation.rst
+++ /dev/null
@@ -1,43 +0,0 @@
-Manipulating Documentation
---------------------------
-
-inject-documentation
-^^^^^^^^^^^^^^^^^^^^
-
- The inject-documentation node inserts the documentation into the generated
- documentation. This node is a child of the object-type, value-type and
- modify-function nodes.
-
- .. code-block:: xml
-
- <value-type>
- <inject-documentation mode="append | prepend | replace" format="native | target" >
- // the documentation
- </inject-code>
- </value-type>
-
- The **mode** attribute default value is *replace*.
-
- The **format** attribute specifies when the documentation injection will
- occur and it accepts the following values:
-
- * native: Before XML<->Backend transformation occur, so the injected code *must* be a valid XML.
- * target: After XML<->Backend transformation occur, so the injected code *must* be a valid backend format.
-
- At the moment the only supported backend is Sphinx.
-
-modify-documentation
-^^^^^^^^^^^^^^^^^^^^
-
- The modify-documentation node allows you to change the auto-generated
- documentation. API Extractor transforms XML's from qdoc (the Qt documentation
- tool) into .rst files to be processed later using Sphinx. You can modify
- the XML before the transformation takes place.
-
- .. code-block:: xml
-
- <modify-documentation xpath="...">
- <!-- new documentation -->
- </modify-documentation>
-
- The **xpath** attribute is the XPath to the node that you want to modify.
diff --git a/sources/shiboken2/doc/typesystem_manipulating_objects.rst b/sources/shiboken2/doc/typesystem_manipulating_objects.rst
deleted file mode 100644
index f76289bc4..000000000
--- a/sources/shiboken2/doc/typesystem_manipulating_objects.rst
+++ /dev/null
@@ -1,190 +0,0 @@
-.. _manipulating-object-and-value-types:
-
-Manipulating Object and Value Types
------------------------------------
-
-.. _inject-code:
-
-inject-code
-^^^^^^^^^^^
- The inject-code node inserts the given code into the generated code for the
- given type or function, and it is a child of the :ref:`object-type`, :ref:`value-type`,
- :ref:`modify-function` and :ref:`add-function` nodes.
-
- The code can be embedded into XML (be careful to use the correct XML entities
- for characters like '<', '>', '&'):
-
- .. code-block:: xml
-
- <value-type>
- <inject-code class="native | target | target-declaration"
- position="beginning | end" since="...">
- // the code
- </inject-code>
- </value-type>
-
- or obtained from an external file:
-
- .. code-block:: xml
-
- <value-type>
- <inject-code class="native | target | target-declaration"
- position="beginning | end" since="..."
- file="external_source.cpp"
- snippet="label"/>
- </value-type>
-
-
- The ``class`` attribute specifies which module of the generated code that
- will be affected by the code injection. The ``class`` attribute accepts the
- following values:
-
- * native: The c++ code
- * target: The binding code
- * target-declaration: The code will be injected into the generated header
- file containing the c++ wrapper class definition.
- * file: The file name
- * snippet: The snippet label (optional)
-
- If the ``position`` attribute is set to *beginning* (the default), the code
- is inserted at the beginning of the function. If it is set to *end*, the code
- is inserted at the end of the function.
-
- The ``since`` attribute specify the API version where this code was injected.
-
- If a ``snippet`` label is given, the code between annotations of the form
-
- .. code-block:: c++
-
- // @snippet label
- ...
- // @snippet label
-
- will be extracted.
-
-modify-field
-^^^^^^^^^^^^
-
- The modify-field node allows you to alter the access privileges for a given
- C++ field when mapping it onto the target language, and it is a child of an
- :ref:`object-type` or a :ref:`value-type` node.
-
- .. code-block:: xml
-
- <object-type>
- <modify-field name="..."
- write="true | false"
- read="true | false" />
- </object-type>
-
- The ``name`` attribute is the name of the field, the *optional* ``write``
- and ``read`` attributes specify the field's access privileges in the target
- language API (both are set to true by default).
- The ``remove`` attribute is an *optional* attribute, which can mark the field
- to be discarded on generation; it has the same purpose of the deprecated tag
- :ref:`remove`.
-
-.. _modify-function:
-
-modify-function
-^^^^^^^^^^^^^^^
-
- The modify-function node allows you to modify a given C++ function when mapping
- it onto the target language, and it is a child of an :ref:`object-type` or a :ref:`value-type`
- node. Use the :ref:`modify-argument` node to specify which argument the modification
- affects.
-
- .. code-block:: xml
-
- <object-type>
- <modify-function signature="..."
- since="..."
- remove="all | c++"
- access="public | private | protected"
- allow-thread="true | auto | false"
- exception-handling="off | auto-off | auto-on | on"
- rename="..." />
- </object-type>
-
- The ``signature`` attribute is a normalized C++ signature, excluding return
- values but including potential const declarations.
-
- The ``since`` attribute specify the API version when this function was modified.
-
- The ``allow-thread`` attribute specifies whether a function should be wrapped
- into ``Py_BEGIN_ALLOW_THREADS`` and ``Py_END_ALLOW_THREADS``, that is,
- temporarily release the GIL (global interpreter lock). Doing so is required
- for any thread-related function (wait operations), functions that might call
- a virtual function (potentially reimplemented in Python), and recommended for
- lengthy I/O operations or similar. It has performance costs, though.
- The value ``auto`` means that it will be turned off for functions for which
- it is deemed to be safe, for example, simple getters.
- The attribute defaults to ``false``.
-
- The ``exception-handling`` attribute specifies whether to generate exception
- handling code (nest the function call into try / catch statements). It accepts
- the following values:
-
- * no, false: Do not generate exception handling code
- * auto-off: Generate exception handling code for functions
- declaring a non-empty ``throw`` list
- * auto-on: Generate exception handling code unless function
- declares ``noexcept``
- * yes, true: Always generate exception handling code
-
- The ``remove``, ``access`` and ``rename`` attributes are *optional* attributes
- for added convenience; they serve the same purpose as the deprecated tags :ref:`remove`, :ref:`access` and :ref:`rename`.
-
-.. _add-function:
-
-add-function
-^^^^^^^^^^^^
-
- The add-function node allows you to add a given function onto the target language,
- and it is a child of an :ref:`object-type` or :ref:`value-type` nodes if the
- function is supposed to be a method, or :ref:`namespace` and :ref:`typesystem` if
- the function is supposed to be a function inside a namespace or a global function.
-
- Typically when adding a function some code must be injected to provide the function
- logic. This can be done using the :ref:`inject-code` node.
-
- .. code-block:: xml
-
- <object-type>
- <add-function signature="..." return-type="..." access="public | protected" static="yes | no" since="..."/>
- </object-type>
-
- The ``return-type`` attribute defaults to *void*, the ``access`` to *public* and the ``static`` one to *no*.
-
- The ``since`` attribute specify the API version when this function was added.
-
- Within the signature, names for the function parameters can be specified by
- enclosing them within the delimiter *@*:
-
- .. code-block:: c++
-
- void foo(int @parameter1@,float)
-
-.. _conversion-rule-on-types:
-
-conversion-rule
-^^^^^^^^^^^^^^^
-
- The conversion-rule node allows you to write customized code to convert the given argument between the target
- language and C++, and is a child of the :ref:`value-type`, :ref:`object-type`, :ref:`primitive-type` and
- :ref:`container-type` nodes.
-
- The code pointed by the file attribute is very tied to the generator using APIExtractor, so it don't follow any
- rules, but the generator rules..
-
- .. code-block:: xml
-
- <value-type name="Foo">
- <convertion-rule file="my_converter_implementation.h" since="..."/>
- </value-type>
-
- The ``since`` attribute specify the API version when this conversion rule became valid.
-
- .. note:: You can also use the conversion-rule node to specify :ref:`how the conversion of a single function argument should be done in a function <conversion-rule>`.
-
- The ``file`` and ``snippet`` attributes are also supported (see :ref:`inject-code` nodes).
diff --git a/sources/shiboken2/doc/typesystem_modify_function.rst b/sources/shiboken2/doc/typesystem_modify_function.rst
deleted file mode 100644
index 071cea4f5..000000000
--- a/sources/shiboken2/doc/typesystem_modify_function.rst
+++ /dev/null
@@ -1,78 +0,0 @@
-.. _modifying-functions:
-
-Modifying Functions
--------------------
-
-.. _modify-argument:
-
-modify-argument
-^^^^^^^^^^^^^^^
-
- The modify-argument node specifies which of the given function's arguments the
- modification affects, and is a child of the modify-function node. Use the
- remove-argument, replace-default-expression, remove-default-expression,
- replace-type, reference-count and define-ownership nodes to specify the details
- of the modification.
-
- .. code-block:: xml
-
- <modify-function>
- <modify-argument index="return | this | 1 ..." >
- // modifications
- </modify-argument>
- </modify-function>
-
- Set the ``index`` attribute to "1" for the first argument, "2" for the second
- one and so on. Alternatively, set it to "return" or "this" if you want to
- modify the function's return value or the object the function is called upon,
- respectively.
-
-.. _remove:
-
-remove
-^^^^^^
-
- The remove node removes the given method from the generated target language
- API, and it is a child of the modify-function node.
-
- .. code-block:: xml
-
- <modify-function>
- <remove class="all" />
- </modify-function>
-
- .. warning:: This tag is deprecated, use the ``remove`` attribute from :ref:`modify-function` tag instead.
-
-.. _access:
-
-access
-^^^^^^
-
- The access node changes the access privileges of the given function in the
- generated target language API, and it is a child of the modify-function node.
-
- .. code-block:: xml
-
- <modify-function>
- <access modifier="public | protected | private"/>
- </modify-function>
-
- .. warning:: This tag is deprecated, use the ``access`` attribute from :ref:`modify-function` tag instead.
-
-.. _rename:
-
-rename
-^^^^^^
-
- The rename node changes the name of the given function in the generated target
- language API, and it is a child of the modify-function node.
-
- .. code-block:: xml
-
- <modify-function>
- <rename to="..." />
- </modify-function>
-
- The ``to`` attribute is the new name of the function.
-
- .. warning:: This tag is deprecated, use the ``rename`` attribute from :ref:`modify-function` tag instead.
diff --git a/sources/shiboken2/doc/typesystem_ownership.rst b/sources/shiboken2/doc/typesystem_ownership.rst
deleted file mode 100644
index 69b61ff00..000000000
--- a/sources/shiboken2/doc/typesystem_ownership.rst
+++ /dev/null
@@ -1,229 +0,0 @@
-****************
-Object ownership
-****************
-
-One of the main things a binding developer should have in mind is
-how the C++ instances lives will cope with Python's reference count.
-The last thing you want is to crash a program due to a segfault
-when your C++ instance was deleted and the
-wrapper object tries to access the invalid memory there.
-
-In this section we'll show how |project| deals with object ownership
-and parentship, taking advantage of the information provided by the
-APIExtractor.
-
-Ownership basics
-================
-
-As any python binding, |project|-based bindings uses reference counting
-to handle the life of the wrapper object (the Python object that contains the
-C++ object, do not confuse with the *wrapped* C++ object).
-When a reference count reaches zero, the wrapper is deleted by Python garbage
-collector and tries to delete the wrapped instance, but sometimes the wrapped
-C++ object is already deleted, or maybe the C++ object should not be freed after
-the Python wrapper go out of scope and die, because C++ is already taking care of
-the wrapped instance.
-
-In order to handle this, you should tell the
-generator whether the instance's ownership belongs to the binding or
-to the C++ Library. When belonging to the binding, we are sure that the C++ object
-won't be deleted by C++ code and we can call the C++ destructor when the refcount
-reaches 0. Otherwise, instances owned by C++ code can be destroyed arbitrarily,
-without notifying the Python wrapper of its destruction.
-
-Invalidating objects
-====================
-
-To prevent segfaults and double frees, the wrapper objects are invalidated.
-An invalidated can't be passed as argument or have an attribute or method accessed.
-Trying to do this will raise RuntimeError.
-
-The following situations can invalidate an object:
-
-C++ taking ownership
---------------------
-
- When an object is passed to a function or method that takes ownership of it, the wrapper
- is invalidated as we can't be sure of when the object is destroyed, unless it has a
- :ref:`virtual destructor <ownership-virt-method>` or the transfer is due to the special case
- of :ref:`parent ownership <ownership-parent>`.
-
- Besides being passed as argument, the called object can have its ownership changed, like
- the `setParent` method in Qt's `QObject`.
-
-Invalidate after use
---------------------
-
- Objects marked with *invalidate-after-use* in the type system description always are
- virtual method arguments provided by a C++ originated call. They should be
- invalidated right after the Python function returns.
-
-.. _ownership-virt-method:
-
-Objects with virtual methods
-----------------------------
-
- A little bit of implementation details:
- virtual methods are supported by creating a C++ class, the **shell**, that inherits
- from the class with virtual methods, the native one, and override those methods to check if
- any derived class in Python also override it.
-
- If the class has a virtual destructor (and C++ classes with virtual methods should have), this
- C++ instance invalidates the wrapper only when the overridden destructor is called.
-
- One exception to this rule is when the object is created in C++, like in a
- factory method. This way the wrapped object is a C++ instance of the native
- class, not the shell one, and we cannot know when it is destroyed.
-
-.. _ownership-parent:
-
-Parent-child relationship
-=========================
-
-One special type of ownership is the parent-child relationship.
-Being a child of an object means that when the object's parent dies,
-the C++ instance also dies, so the Python references will be invalidated.
-Qt's QObject system, for example, implements this behavior, but this is valid
-for any C++ library with similar behavior.
-
-.. _ownership-parent-heuristics:
-
-Parentship heuristics
----------------------
-
- As the parent-child relationship is very common, |project| tries to automatically
- infer what methods falls into the parent-child scheme, adding the extra
- directives related to ownership.
-
- This heuristic will be triggered when generating code for a method and:
-
- * The function is a constructor.
- * The argument name is `parent`.
- * The argument type is a pointer to an object.
-
- When triggered, the heuristic will set the argument named "parent"
- as the parent of the object being created by the constructor.
-
- The main focus of this process was to remove a lot of hand written code from
- type system when binding Qt libraries. For Qt, this heuristic works in all cases,
- but be aware that it might not when binding your own libraries.
-
- To activate this heuristic, use the :ref:`--enable-parent-ctor-heuristic <parent-heuristic>`
- command line switch.
-
-.. _return-value-heuristics:
-
-Return value heuristics
------------------------
-
- When enabled, object returned as pointer in C++ will become child of the object on which the method
- was called.
-
- To activate this heuristic, use the :ref:`--enable-return-value-heuristic <return-heuristic>`
-
-Common pitfalls
-===============
-
-Not saving unowned objects references
--------------------------------------
-
- Sometimes when you pass an instance as argument to a method and the receiving
- instance will need that object to live indefinitely, but will not take ownership
- of the argument instance. In this case, you should hold a reference to the argument
- instance.
-
- For example, let's say that you have a renderer class that will use a source class
- in a setSource method but will not take ownership of it. The following code is wrong,
- because when `render` is called the `Source` object created during the call to `setSource`
- is already destroyed.
-
- .. code-block:: python
-
- renderer.setModel(Source())
- renderer.render()
-
- To solve this, you should hold a reference to the source object, like in
-
- .. code-block:: python
-
- source = Source()
- renderer.setSource(source)
- renderer.render()
-
-
-Ownership Management in the Typesystem
-=======================================
-
-Ownership transfer from C++ to target
--------------------------------------
-
- When an object currently owned by C++ has its ownership transferred
- back to the target language, the binding can know for sure when the object will be deleted and
- tie the C++ instance existence to the wrapper, calling the C++ destructor normally when the
- wrapper is deleted.
-
- .. code-block:: xml
-
- <modify-argument index="1">
- <define-ownership class="target" owner="target" />
- </modify-argument>
-
-Ownership transfer from target to C++
--------------------------------------
-
- In the opposite direction, when an object ownership is transferred from the target language
- to C++, the native code takes full control of the object life and you don't
- know when that object will be deleted, rendering the wrapper object invalid,
- unless you're wrapping an object with a virtual destructor,
- so you can override it and be notified of its destruction.
-
- By default it's safer to just render the wrapper
- object invalid and raise some error if the user tries to access
- one of this objects members or pass it as argument to some function, to avoid unpleasant segfaults.
- Also you should avoid calling the C++ destructor when deleting the wrapper.
-
- .. code-block:: xml
-
- <modify-argument index="1">
- <define-ownership class="target" owner="c++" />
- </modify-argument>
-
-
-Parent-child relationship
--------------------------
-
-One special type of relationship is the parent-child. When an object is called
-the parent of another object (the child), the former is in charge of deleting its
-child when deleted and the target language can trust that the child will be alive
-as long as the parent is, unless some other method can take the C++ ownership away from the parent.
-
-One of the main uses of this scheme is Qt's object system, with ownership among QObject-derived
-classes, creating "trees" of instances.
-
- .. code-block:: xml
-
- <modify-argument index="this">
- <parent index="1" action="add">
- </modify-argument>
-
-In this example, the instance with the method that is being invoked (indicated by 'index="this"' on
-modify-argument) will be marked as a child
-of the first argument using the `parent` tag. To remove ownership, just use "remove" in the action attribute. **Removing
-parentship also transfers the ownership back to python.**
-
-Invalidation after use
-----------------------
-
-Sometimes an object is created as a virtual method call argument and destroyed after the
-call returned. In this case, you should use the ``invalidate-after-use`` attribute in the
-``modify-argument`` tag to mark the wrapper as invalid right after the virtual method returns.
-
- .. code-block:: xml
-
- <modify-argument index="2" invalidate-after-use="yes"/>
-
-In this example the second argument will be invalidated after this method call.
-
-See `Object Trees and Object Ownership`_.
-
-.. _`Object Trees and Object Ownership`: http://doc.qt.io/qt-5/objecttrees.html
diff --git a/sources/shiboken2/doc/typesystem_sequenceprotocol.rst b/sources/shiboken2/doc/typesystem_sequenceprotocol.rst
deleted file mode 100644
index 26ae3b220..000000000
--- a/sources/shiboken2/doc/typesystem_sequenceprotocol.rst
+++ /dev/null
@@ -1,29 +0,0 @@
-Sequence Protocol
------------------
-
-Support for the sequence protocol is achieved adding functions with special
-names, this is done using the add-function tag.
-
-The special function names are:
-
- ============= =============================================== ==================== ===================
- Function name Parameters Return type CPython equivalent
- ============= =============================================== ==================== ===================
- __len__ PyObject* self Py_ssize_t PySequence_Size
- __getitem__ PyObject* self, Py_ssize_t _i PyObject* PySequence_GetItem
- __setitem__ PyObject* self, Py_ssize_t _i, PyObject* _value int PySequence_SetItem
- __contains__ PyObject* self, PyObject* _value int PySequence_Contains
- __concat__ PyObject* self, PyObject* _other PyObject* PySequence_Concat
- ============= =============================================== ==================== ===================
-
-You just need to inform the function name to the add-function tag, without any
-parameter or return type information, when you do it, |project| will create a C
-function with parameters and return type defined by the table above.
-
-The function needs to follow the same semantics of the *CPython equivalent*
-function, the only way to do it is using the
-:doc:`inject-code <codeinjectionsemantics>` tag.
-
-A concrete example how to add sequence protocol support to a class can be found
-on shiboken tests, more precisely in the definition of the Str class in
-``tests/samplebinding/typesystem_sample.xml``.
diff --git a/sources/shiboken2/doc/typesystem_solving_compilation.rst b/sources/shiboken2/doc/typesystem_solving_compilation.rst
deleted file mode 100644
index 23ab9012d..000000000
--- a/sources/shiboken2/doc/typesystem_solving_compilation.rst
+++ /dev/null
@@ -1,70 +0,0 @@
-Solving compilation problems
-----------------------------
-
-suppress-warning
-^^^^^^^^^^^^^^^^
-
- The generator will generate several warnings which may be irrelevant to the
- user. The suppress-warning node suppresses the specified warning, and it is
- a child of the typesystem node.
-
- .. code-block:: xml
-
- <typesystem>
- <suppress-warning text="..." />
- </typesystem>
-
- The **text** attribute is the warning text to suppress, and may contain the *
- wildcard (use "" to escape regular expression matching if the warning contain
- a regular "*").
-
-extra-includes
-^^^^^^^^^^^^^^
-
- The extra-includes node contains declarations of additional include files,
- and it can be a child of the interface-type, namespace-type, value-type and
- object-type nodes.
-
- The generator automatically tries to read the global header for each type but
- sometimes it is required to include extra files in the generated C++ code to
- make sure that the code compiles. These files must be listed using include
- nodes within the extra-include node:
-
- .. code-block:: xml
-
- <value-type>
- <extra-includes>
- <include file-name="..." location="global | local"/>
- </extra-includes>
- </value-type>
-
- The **file-name** attribute is the file to include, such as "QStringList".
- The **location** attribute is where the file is located: *global* means that
- the file is located in $INCLUDEPATH and will be included using #include <...>,
- *local* means that the file is in a local directory and will be included
- using #include "...".
-
-
-include
-^^^^^^^
-
- The include node specifies the name and location of a file that must be
- included, and it is a child of the interface-type, namespace-type, value-type,
- object-type or extra-includes nodes
-
- The generator automatically tries to read the global header for each type. Use
- the include node to override this behavior, providing an alternative file. The
- include node can also be used to specify extra include files.
-
- .. code-block:: xml
-
- <value-type>
- <include file-name="..."
- location="global | local"/>
- </value-type>
-
- The **file-name** attribute is the file to include, such as "QStringList".
- The **location** attribute is where the file is located: *global* means that
- the file is located in $INCLUDEPATH and will be included using #include <...>,
- *local* means that the file is in a local directory and will be included
- using #include "...".
diff --git a/sources/shiboken2/doc/typesystem_specifying_types.rst b/sources/shiboken2/doc/typesystem_specifying_types.rst
deleted file mode 100644
index 27267faab..000000000
--- a/sources/shiboken2/doc/typesystem_specifying_types.rst
+++ /dev/null
@@ -1,481 +0,0 @@
-Specifying Types
-----------------
-
-.. _typesystem:
-
-Including Snippets
-^^^^^^^^^^^^^^^^^^
-
-There might be repetitive XML code, for example function modifications that
-need to be done on classes that are not related by type inheritance.
-It is possible to split out such snippets and include them via an entity reference.
-
-.. code-block:: xml
-
- <typesystem>
- <object-type name="A">
- &common_function_modifications;
- </object-type>
- <object-type name="B">
- &common_function_modifications;
- </object-type>
- </typesystem>
-
-The entity name is interpreted as file name (with suffix **xml**) appended and resolved
-in the type system paths passed as command line argument.
-
-Note that this is not a standard externally parsed entity due to the limitations
-of the underlying parser.
-
-typesystem
-^^^^^^^^^^
-
- This is the root node containing all the type system information. It can
- have a number of attributes, described below.
-
- .. code-block:: xml
-
- <typesystem package="..." default-superclass="..." allow-thread="..." exception-handling="...">
- </typesystem>
-
- The **package** attribute is a string describing the package to be used,
- e.g. "QtCore".
- The *optional* **default-superclass** attribute is the canonical C++ base class
- name of all objects, e.g., "object".
-
- The *optional* attributes **allow-thread** and **exception-handling**
- specify the default handling for the corresponding function modification
- (see :ref:`modify-function`).
-
-load-typesystem
-^^^^^^^^^^^^^^^
-
- The load-typesystem node specifies which type systems to load when mapping
- multiple libraries to another language or basing one library on another, and
- it is a child of the typesystem node.
-
- .. code-block:: xml
-
- <typesystem>
- <load-typesystem name="..." generate="yes | no" />
- </typesystem>
-
- The **name** attribute is the filename of the typesystem to load, the
- **generate** attribute specifies whether code should be generated or not. The
- later must be specified when basing one library on another, making the generator
- able to understand inheritance hierarchies, primitive mapping, parameter types
- in functions, etc.
-
- Most libraries will be based on both the QtCore and QtGui modules, in which
- case code generation for these libraries will be disabled.
-
-
-rejection
-^^^^^^^^^
-
- The rejection node rejects the given class, or the specified function or
- field, and it is a child of the typesystem node.
-
- .. code-block:: xml
-
- <typesystem>
- <rejection class="..."
- function-name="..."
- field-name="..." />
- </typesystem>
-
- The **class** attribute is the C++ class name of the class to reject. Use the
- *optional* **function-name** or **field-name** attributes to reject a particular
- function or field. Note that the **field-name** and **function-name** cannot
- be specified at the same time. To remove all occurrences of a given field or
- function, set the class attribute to \*.
-
-.. _primitive-type:
-
-primitive-type
-^^^^^^^^^^^^^^
-
- The primitive-type node describes how a primitive type is mapped from C++ to
- the target language, and is a child of the typesystem node. Note that most
- primitives are already specified in the QtCore typesystem.
-
- .. code-block:: xml
-
- <typesystem>
- <primitive-type name="..."
- since="..."
- until="..."
- target-name="..."
- default-constructor="..."
- preferred-conversion="yes | no" />
- </typesystem>
-
- The **name** attribute is the name of the primitive in C++, the optional,
- **target-name** attribute is the name of the primitive type in the target
- language. If the later two attributes are not specified their default value
- will be the same as the **name** attribute.
-
- The *optional* **since** value is used to specify the API version in which
- the type was introduced.
-
- Similarly, the *optional* **until** value can be used to specify the API
- version in which the type will be obsoleted.
-
- If the *optional* **preferred-conversion** attribute is set to *no*, it
- indicates that this version of the primitive type is not the preferred C++
- equivalent of the target language type. For example, in Python both "qint64"
- and "long long" become "long" but we should prefer the "qint64" version. For
- this reason we mark "long long" with preferred-conversion="no".
-
- The *optional* **default-constructor** specifies the minimal constructor
- call to build one value of the primitive-type. This is not needed when the
- primitive-type may be built with a default constructor (the one without
- arguments).
-
- The *optional* **preferred-conversion** attribute tells how to build a default
- instance of the primitive type. It should be a constructor call capable of
- creating a instance of the primitive type. Example: a class "Foo" could have
- a **preferred-conversion** value set to "Foo()". Usually this attribute is
- used only for classes declared as primitive types and not for primitive C++
- types, but that depends on the application using *ApiExtractor*.
-
-
-.. _namespace:
-
-namespace-type
-^^^^^^^^^^^^^^
-
- The namespace-type node maps the given C++ namespace to the target language,
- and it is a child of the typesystem node. Note that within namespaces, the
- generator only supports enums (i.e., no functions or classes).
-
- .. code-block:: xml
-
- <typesystem>
- <namespace-type name="..."
- visible="true | auto | false"
- generate="yes | no"
- package="..."
- since="..."
- revision="..." />
- </typesystem>
-
- The **name** attribute is the name of the namespace, e.g., "Qt".
-
- The *optional* **visible** attribute is used specify whether the
- namespace is visible in the target language name. Its default value is
- **auto**. It means that normal namespaces are visible, but inline namespaces
- (as introduced in C++ 11) will not be visible.
-
- The detection of inline namespaces requires shiboken to be built
- using LLVM 9.0.
-
- The *optional* **generate** is a legacy attribute. Specifying
- **no** is equivalent to **visible="false"**.
-
- The **package** attribute can be used to override the package of the type system.
-
- The *optional* **since** value is used to specify the API version of this type.
-
- The **revision** attribute can be used to specify a revision for each type, easing the
- production of ABI compatible bindings.
-
-enum-type
-^^^^^^^^^
-
- The enum-type node maps the given enum from C++ to the target language,
- and it is a child of the typesystem node. Use the reject-enum-value to
- reject values.
-
- .. code-block:: xml
-
- <typesystem>
- <enum-type name="..."
- identified-by-value="..."
- class="yes | no"
- since="..."
- flags="yes | no"
- flags-revision="..."
- lower-bound="..."
- upper-bound="..."
- force-integer="yes | no"
- extensible="yes | no"
- revision="..." />
- </typesystem>
-
- The **name** attribute is the fully qualified C++ name of the enum
- (e.g.,"Qt::FillRule"). If the *optional* **flags** attribute is set to *yes*
- (the default is *no*), the generator will expect an existing QFlags<T> for the
- given enum type. The **lower-bound** and **upper-bound** attributes are used
- to specify runtime bounds checking for the enum value. The value must be a
- compilable target language statement, such as "QGradient.Spread.PadSpread"
- (taking again Python as an example). If the **force-integer** attribute is
- set to *yes* (the default is *no*), the generated target language code will
- use the target language integers instead of enums. And finally, the
- **extensible** attribute specifies whether the given enum can be extended
- with user values (the default is *no*).
-
- The *optional* **since** value is used to specify the API version of this type.
-
- The attribute **identified-by-value** helps to specify anonymous enums using the
- name of one of their values, which is unique for the anonymous enum scope.
- Notice that the **enum-type** tag can either have **name** or **identified-by-value**
- but not both.
-
- The **revision** attribute can be used to specify a revision for each type, easing the
- production of ABI compatible bindings.
-
- The **flags-revision** attribute has the same purposes of **revision** attribute but
- is used for the QFlag related to this enum.
-
-
-reject-enum-value
-^^^^^^^^^^^^^^^^^
-
- The reject-enum-value node rejects the enum value specified by the **name**
- attribute, and it is a child of the enum-type node.
-
- .. code-block:: xml
-
- <enum-type>
- <reject-enum-value name="..."/>
- </enum-type>
-
- This node is used when a C++ enum implementation has several identical numeric
- values, some of which are typically obsolete.
-
-.. _value-type:
-
-value-type
-^^^^^^^^^^
-
- The value-type node indicates that the given C++ type is mapped onto the target
- language as a value type. This means that it is an object passed by value on C++,
- i.e. it is stored in the function call stack. It is a child of the :ref:`typesystem` node.
-
- .. code-block:: xml
-
- <typesystem>
- <value-type name="..." since="..."
- copyable="yes | no"
- allow-thread="..."
- exception-handling="..."
- hash-function="..."
- stream="yes | no"
- default-constructor="..."
- revision="..." />
- </typesystem>
-
- The **name** attribute is the fully qualified C++ class name, such as
- "QMatrix" or "QPainterPath::Element". The **copyable** attribute is used to
- force or not specify if this type is copyable. The *optional* **hash-function**
- attribute informs the function name of a hash function for the type.
-
- The *optional* attribute **stream** specifies whether this type will be able to
- use externally defined operators, like QDataStream << and >>. If equals to **yes**,
- these operators will be called as normal methods within the current class.
-
- The *optional* **since** value is used to specify the API version of this type.
-
- The *optional* **default-constructor** specifies the minimal constructor
- call to build one instance of the value-type. This is not needed when the
- value-type may be built with a default constructor (the one without arguments).
- Usually a code generator may guess a minimal constructor for a value-type based
- on its constructor signatures, thus **default-constructor** is used only in
- very odd cases.
-
- The **revision** attribute can be used to specify a revision for each type, easing the
- production of ABI compatible bindings.
-
- The *optional* attributes **allow-thread** and **exception-handling**
- specify the default handling for the corresponding function modification
- (see :ref:`modify-function`).
-
-.. _object-type:
-
-object-type
-^^^^^^^^^^^
-
- The object-type node indicates that the given C++ type is mapped onto the target
- language as an object type. This means that it is an object passed by pointer on
- C++ and it is stored on the heap. It is a child of the :ref:`typesystem` node.
-
- .. code-block:: xml
-
- <typesystem>
- <object-type name="..."
- since="..."
- copyable="yes | no"
- allow-thread="..."
- exception-handling="..."
- hash-function="..."
- stream="yes | no"
- revision="..." />
- </typesystem>
-
- The **name** attribute is the fully qualified C++ class name. If there is no
- C++ base class, the default-superclass attribute can be used to specify a
- superclass for the given type, in the generated target language API. The
- **copyable** and **hash-function** attributes are the same as described for
- :ref:`value-type`.
-
- The *optional* attribute **stream** specifies whether this type will be able to
- use externally defined operators, like QDataStream << and >>. If equals to **yes**,
- these operators will be called as normal methods within the current class.
-
- The *optional* **since** value is used to specify the API version of this type.
-
- The **revision** attribute can be used to specify a revision for each type, easing the
- production of ABI compatible bindings.
-
- The *optional* attributes **allow-thread** and **exception-handling**
- specify the default handling for the corresponding function modification
- (see :ref:`modify-function`).
-
-interface-type
-^^^^^^^^^^^^^^
-
- This type is deprecated and no longer has any effect. Use object-type instead.
-
-.. _container-type:
-
-container-type
-^^^^^^^^^^^^^^
-
- The container-type node indicates that the given class is a container and
- must be handled using one of the conversion helpers provided by attribute **type**.
-
- .. code-block:: xml
-
- <typesystem>
- <container-type name="..."
- since="..."
- type ="..." />
- </typesystem>
-
- The **name** attribute is the fully qualified C++ class name. The **type**
- attribute is used to indicate what conversion rule will be applied to the
- container. It can be: *list*, *string-list*, *linked-list*, *vector*, *stack*,
- *queue*, *set*, *map*, *multi-map*, *hash*, *multi-hash* or *pair*.
-
- The *optional* **since** value is used to specify the API version of this container.
-
-typedef-type
-^^^^^^^^^^^^
-
- The typedef-type allows for specifying typedefs in the typesystem. They
- are mostly equivalent to spelling out the typedef in the included header, which
- is often complicated when trying to wrap libraries whose source code cannot be
- easily extended.
-
- .. code-block:: xml
-
- <typesystem>
- <typedef-type name="..."
- source="..."
- since="..." />
- </typesystem>
-
- The **source** attribute is the source. Example:
-
- .. code-block:: xml
-
- <namespace-type name='std'>
- <value-type name='optional' generate='no'/>\n"
- </namespace-type>
- <typedef-type name="IntOptional" source="std::optional&lt;int&gt;"/>
-
- is equivalent to
-
- .. code-block:: c++
-
- typedef std::optional<int> IntOptional;
-
- The *optional* **since** value is used to specify the API version of this type.
-
-.. _custom-type:
-
-custom-type
-^^^^^^^^^^^
-
- The custom-type node simply makes the parser aware of the existence of a target
- language type, thus avoiding errors when trying to find a type used in function
- signatures and other places. The proper handling of the custom type is meant to
- be done by a generator using the APIExractor.
-
- .. code-block:: xml
-
- <typesystem>
- <custom-type name="..." />
- </typesystem>
-
- The **name** attribute is the name of the custom type, e.g., "PyObject".
-
-.. _smart-pointer-type:
-
-smart-pointer-type
-^^^^^^^^^^^^^^^^^^
-
- The smart pointer type node indicates that the given class is a smart pointer
- and requires inserting calls to **getter** to access the pointeee.
- Currently, only the **type** *shared* is supported and the usage is limited
- to function return values.
- **ref-count-method** specifies the name of the method used to do reference counting.
-
- The *optional* attribute **instantiations** specifies for which instantiations
- of the smart pointer wrappers will be generated (comma-separated list).
- By default, this will happen for all instantiations found by code parsing.
- This might be a problem when linking different modules, since wrappers for the
- same instantiation might be generated into different modules, which then clash.
- Providing an instantiations list makes it possible to specify which wrappers
- will be generated into specific modules.
-
- .. code-block:: xml
-
- <typesystem>
- <smart-pointer-type name="..."
- since="..."
- type="..."
- getter="..."
- ref-count-method="..."
- instantiations="..."/>
- </typesystem>
-
-.. _function:
-
-function
-^^^^^^^^
-
- The function node indicates that the given C++ global function is mapped onto
- the target language.
-
- .. code-block:: xml
-
- <typesystem>
- <function signature="..." rename="..." since="..."/>
- </typesystem>
-
- This tag has some limitations, it doesn't support function modifications, besides you
- can't add a function overload using :ref:`add-function` tag to an existent function.
- These limitation will be addressed in future versions of ApiExtractor.
-
- The function tag has two *optional* attributes: **since**, whose value is used to specify
- the API version of this function, and **rename**, to modify the function name.
-
-.. _system_include:
-
-system-include
-^^^^^^^^^^^^^^
-
- The optional **system-include** specifies the name of a system include
- file or a system include path (indicated by a trailing slash) to be
- parsed. Normally, include files considered to be system include
- files are skipped by the C++ code parser. Its primary use case
- is exposing classes from the STL library.
-
- .. code-block:: xml
-
- <typesystem>
- <system-include file-name="memory"/>
- <system-include file-name="/usr/include/Qt/"/>
- </typesystem>
diff --git a/sources/shiboken2/doc/typesystem_templates.rst b/sources/shiboken2/doc/typesystem_templates.rst
deleted file mode 100644
index 31b155c5a..000000000
--- a/sources/shiboken2/doc/typesystem_templates.rst
+++ /dev/null
@@ -1,55 +0,0 @@
-.. _using-code-templates:
-
-Using Code Templates
---------------------
-
-template
-^^^^^^^^
-
- The template node registers a template that can be used to avoid duplicate
- code when extending the generated code, and it is a child of the typesystem
- node.
-
- .. code-block:: xml
-
- <typesystem>
- <template name="my_template">
- // the code
- </template>
- </typesystem>
-
- Use the insert-template node to insert the template code (identified by the
- template's ``name`` attribute) into the generated code base.
-
-
-insert-template
-^^^^^^^^^^^^^^^
-
- The insert-template node includes the code template identified by the name
- attribute, and it can be a child of the inject-code, conversion-rule, template,
- custom-constructor and custom-destructor nodes.
-
- .. code-block:: xml
-
- <inject-code class="target" position="beginning">
- <insert-template name="my_template" />
- </inject-code>
-
- Use the replace node to modify the template code.
-
-
-replace
-^^^^^^^
-
- The replace node allows you to modify template code before inserting it into
- the generated code, and it can be a child of the insert-template node.
-
- .. code-block:: xml
-
- <insert-template name="my_template">
- <replace from="..." to="..." />
- </insert-template>
-
- This node will replace the attribute ``from`` with the value pointed by
- ``to``.
-
diff --git a/sources/shiboken2/doc/typesystem_variables.rst b/sources/shiboken2/doc/typesystem_variables.rst
deleted file mode 100644
index 73d4dd12c..000000000
--- a/sources/shiboken2/doc/typesystem_variables.rst
+++ /dev/null
@@ -1,359 +0,0 @@
-*********************
-Type System Variables
-*********************
-
-User written code can be placed in arbitrary places using the
-:ref:`inject-code <inject-code>` tag. To ease the binding developer
-work, the injected code can make use of special variables that will be replaced
-by the correct values. This also shields the developer from some |project|
-implementation specifics.
-
-
-.. _variables:
-
-Variables
-=========
-
-
-.. _cpp_return_argument:
-
-**%0**
-
- Replaced by the C++ return variable of the Python method/function wrapper.
-
-
-.. _arg_number:
-
-**%#**
-
- Replaced by the name of a C++ argument in the position indicated by ``#``.
- The argument counting starts with ``%1``, since ``%0`` represents the return
- variable name. If the number indicates a variable that was removed in the
- type system description, but there is a default value for it, this value will
- be used. Consider this example:
-
- .. code-block:: c++
-
- void argRemoval(int a0, int a1 = 123);
-
-
- .. code-block:: xml
-
- <modify-function signature="argRemoval(int, int)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- </modify-function>
-
- The ``%1`` will be replaced by the C++ argument name, and ``%2`` will get the
- value ``123``.
-
-
-.. _argument_names:
-
-**%ARGUMENT_NAMES**
-
- Replaced by a comma separated list with the names of all C++ arguments that
- were not removed on the type system description for the method/function. When
- the removed argument has a default value (original or provided in the type
- system), this value will be inserted in the argument list. If you want to remove
- the argument so completely that it doesn't appear in any form on the
- ``%ARGUMENT_NAMES`` replacement, don't forget to remove also its default value
- with the :ref:`remove-default-expression <remove-default-expression>` type system tag.
-
-
- Take the following method and related type system description as an example:
-
- .. code-block:: c++
-
- void argRemoval(int a0, Point a1 = Point(1, 2), bool a2 = true, Point a3 = Point(3, 4), int a4 = 56);
-
-
- .. code-block:: xml
-
- <modify-function signature="argRemoval(int, Point, bool, Point, int)">
- <modify-argument index="2">
- <remove-argument/>
- <replace-default-expression with="Point(6, 9)"/>
- </modify-argument>
- <modify-argument index="4">
- <remove-argument/>
- </modify-argument>
- </modify-function>
-
- As seen on the XML description, the function's ``a1`` and ``a3`` arguments
- were removed. If any ``inject-code`` for this function uses ``%ARGUMENT_NAMES``
- the resulting list will be the equivalent of using individual argument type
- system variables this way:
-
- .. code-block:: c++
-
- %1, Point(6, 9), %3, Point(3, 4), %5
-
-
-.. _arg_type:
-
-**%ARG#_TYPE**
-
- Replaced by the type of a C++ argument in the position indicated by ``#``.
- The argument counting starts with ``%1``, since ``%0`` represents the return
- variable in other contexts, but ``%ARG0_TYPE`` will not translate to the
- return type, as this is already done by the
- :ref:`%RETURN_TYPE <return_type>` variable.
- Example:
-
- .. code-block:: c++
-
- void argRemoval(int a0, int a1 = 123);
-
-
- .. code-block:: xml
-
- <modify-function signature="argRemoval(int, int)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- </modify-function>
-
- The ``%1`` will be replaced by the C++ argument name, and ``%2`` will get the
- value ``123``.
-
-
-.. _converttocpp:
-
-**%CONVERTTOCPP[CPPTYPE]**
-
- Replaced by a |project| conversion call that converts a Python variable
- to a C++ variable of the type indicated by ``CPPTYPE``.
-
- Typically, this is a variable assignment:
-
- .. code-block:: c++
-
- double value = %CONVERTTOCPP[double](pyValue);
-
- Pointer assignments are also possible:
-
- .. code-block:: c++
-
- void f(double *valuePtr)
- {
- *valuePtr = %CONVERTTOCPP[double](pyValue);
-
- Note however, that for variable definitions, the type must
- be a space-delimited token:
-
- .. code-block:: c++
-
- double * valuePtr = %CONVERTTOCPP[double](pyValue);
-
- since it otherwise would be indistinguishable from the pointer assignment
- above.
-
- It is possible to use "auto" as type.
-
-.. _converttopython:
-
-**%CONVERTTOPYTHON[CPPTYPE]**
-
- Replaced by a |project| conversion call that converts a C++ variable of the
- type indicated by ``CPPTYPE`` to the proper Python object.
-
-
-.. _isconvertible:
-
-**%ISCONVERTIBLE[CPPTYPE]**
-
- Replaced by a |project| "isConvertible" call that checks if a Python
- variable is convertible (via an implicit conversion or cast operator call)
- to a C++ variable of the type indicated by ``CPPTYPE``.
-
-
-.. _checktype:
-
-**%CHECKTYPE[CPPTYPE]**
-
- Replaced by a |project| "checkType" call that verifies if a Python
- if of the type indicated by ``CPPTYPE``.
-
-
-.. _cppself:
-
-**%CPPSELF**
-
- Replaced by the wrapped C++ object instance that owns the method in which the
- code with this variable was inserted.
-
-.. _cpptype:
-
-**%CPPTYPE**
-
- Replaced by the original name of the C++ class, without any namespace prefix,
- that owns the method in which the code with this variable was inserted. It will
- work on class level code injections also. Notice that ``CPPTYPE`` differs from
- the :ref:`%TYPE <type>` variable, for this latter may be translated to the original
- C++ class name or to the C++ wrapper class name.
-
- Namespaces will are treated as classes, so ``CPPTYPE`` will work for them and their
- enclosed functions as well.
-
-.. _function_name:
-
-**%FUNCTION_NAME**
-
- Replaced by the name of a function or method.
-
-
-
-.. _py_return_argument:
-
-**%PYARG_0**
-
- Replaced by the name of the Python return variable of the Python method/function wrapper.
-
-
-.. _pyarg:
-
-**%PYARG_#**
-
- Similar to ``%#``, but is replaced by the Python arguments (PyObjects)
- received by the Python wrapper method.
-
- If used in the context of a native code injection, i.e. in a virtual method
- override, ``%PYARG_#`` will be translated to one item of the Python tuple
- holding the arguments that should be passed to the Python override for this
- virtual method.
-
- The example
-
- .. code-block:: c++
-
- long a = PyInt_AS_LONG(%PYARG_1);
-
-
- is equivalent of
-
- .. code-block:: c++
-
- long a = PyInt_AS_LONG(PyTuple_GET_ITEM(%PYTHON_ARGUMENTS, 0));
-
-
- The generator tries to be smart with attributions, but it will work for the
- only simplest cases.
-
- This example
-
- .. code-block:: c++
-
- Py_DECREF(%PYARG_1);
- %PYARG_1 = PyInt_FromLong(10);
-
-
- is equivalent of
-
- .. code-block:: c++
-
- Py_DECREF(PyTuple_GET_ITEM(%PYTHON_ARGUMENTS, 0));
- PyTuple_SET_ITEM(%PYTHON_ARGUMENTS, 0, PyInt_FromLong(10));
-
-
-.. _pyself:
-
-**%PYSELF**
-
- Replaced by the Python wrapper variable (a PyObject) representing the instance
- bounded to the Python wrapper method which receives the custom code.
-
-
-.. _python_arguments:
-
-**%PYTHON_ARGUMENTS**
-
- Replaced by the pointer to the Python tuple with Python objects converted from
- the C++ arguments received on the binding override of a virtual method.
- This tuple is the same passed as arguments to the Python method overriding the
- C++ parent's one.
-
-
-.. _python_method_override:
-
-**%PYTHON_METHOD_OVERRIDE**
-
- This variable is used only on :ref:`native method code injections
- <codeinjecting_method_native>`, i.e. on the binding overrides for C++ virtual
- methods. It is replaced by a pointer to the Python method override.
-
-
-.. _pythontypeobject:
-
-**%PYTHONTYPEOBJECT**
-
- Replaced by the Python type object for the context in which it is inserted:
- method or class modification.
-
-
-.. _beginallowthreads:
-
-**%BEGIN_ALLOW_THREADS**
-
- Replaced by a thread state saving procedure.
- Must match with a :ref:`%END_ALLOW_THREADS <endallowthreads>` variable.
-
-
-.. _endallowthreads:
-
-**%END_ALLOW_THREADS**
-
- Replaced by a thread state restoring procedure.
- Must match with a :ref:`%BEGIN_ALLOW_THREADS <beginallowthreads>` variable.
-
-
-.. _return_type:
-
-**%RETURN_TYPE**
-
- Replaced by the type returned by a function or method.
-
-
-.. _type:
-
-**%TYPE**
-
- Replaced by the name of the class to which a function belongs. May be used
- in code injected at method or class level.
-
-
-.. _example:
-
-Example
-=======
-
-Just to illustrate the usage of the variables described in the previous
-sections, below is an excerpt from the type system description of a |project|
-test. It changes a method that received ``argc/argv`` arguments into something
-that expects a Python sequence instead.
-
- .. code-block:: xml
-
- <modify-function signature="overloadedMethod(int, char**)">
- <modify-argument index="1">
- <replace-type modified-type="PySequence" />
- </modify-argument>
- <modify-argument index="2">
- <remove-argument />
- </modify-argument>
- <inject-code class="target" position="beginning">
- int argc;
- char** argv;
- if (!PySequence_to_argc_argv(%PYARG_1, &amp;argc, &amp;argv)) {
- PyErr_SetString(PyExc_TypeError, "error");
- return 0;
- }
- %RETURN_TYPE foo = %CPPSELF.%FUNCTION_NAME(argc, argv);
- %0 = %CONVERTTOPYTHON[%RETURN_TYPE](foo);
-
- for (int i = 0; i &lt; argc; ++i)
- delete[] argv[i];
- delete[] argv;
- </inject-code>
- </modify-function>
diff --git a/sources/shiboken2/generator/CMakeLists.txt b/sources/shiboken2/generator/CMakeLists.txt
deleted file mode 100644
index 1a3f4e5c4..000000000
--- a/sources/shiboken2/generator/CMakeLists.txt
+++ /dev/null
@@ -1,63 +0,0 @@
-project(shibokengenerator)
-
-set(shiboken2_SRC
-generator.cpp
-shiboken2/cppgenerator.cpp
-shiboken2/headergenerator.cpp
-shiboken2/overloaddata.cpp
-shiboken2/shibokengenerator.cpp
-main.cpp
-)
-
-add_executable(shiboken2 ${shiboken2_SRC})
-add_executable(Shiboken2::shiboken2 ALIAS shiboken2)
-add_dependencies(shiboken2 apiextractor)
-set_target_properties(shiboken2 PROPERTIES OUTPUT_NAME shiboken2${shiboken2_SUFFIX})
-target_include_directories(shiboken2 PRIVATE
- ${CMAKE_CURRENT_SOURCE_DIR}/shiboken2
- ${CMAKE_CURRENT_SOURCE_DIR}/qtdoc
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${apiextractor_SOURCE_DIR}
- )
-target_link_libraries(shiboken2 apiextractor Qt${QT_MAJOR_VERSION}::Core)
-if (NOT DISABLE_DOCSTRINGS)
- target_sources(shiboken2 PRIVATE qtdoc/qtdocgenerator.cpp)
- target_compile_definitions(shiboken2 PUBLIC DOCSTRINGS_ENABLED)
-endif()
-
-configure_file(shibokenconfig.h.in "${CMAKE_CURRENT_BINARY_DIR}/shibokenconfig.h" @ONLY)
-
-install(TARGETS shiboken2
- EXPORT Shiboken2Targets
- DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
-
-set(shiboken_generator_package_name "shiboken2_generator")
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/_config.py.in"
- "${CMAKE_CURRENT_BINARY_DIR}/_config.py" @ONLY)
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/_config.py"
- DESTINATION "${PYTHON_SITE_PACKAGES}/${shiboken_generator_package_name}")
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/__init__.py.in"
- "${CMAKE_CURRENT_BINARY_DIR}/__init__.py" @ONLY)
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/__init__.py"
- DESTINATION "${PYTHON_SITE_PACKAGES}/${shiboken_generator_package_name}")
-
-# shiboken2 setuptools entry point
-install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/../shiboken_tool.py
- DESTINATION bin
- PERMISSIONS
- OWNER_EXECUTE OWNER_WRITE OWNER_READ
- GROUP_EXECUTE GROUP_READ
- WORLD_EXECUTE WORLD_READ)
-
-# Use absolute path instead of relative path, to avoid ninja build errors due to
-# duplicate file dependency inconsistency.
-set(shiboken_version_relative_path "${CMAKE_CURRENT_SOURCE_DIR}/../shiboken_version.py")
-get_filename_component(shiboken_version_path ${shiboken_version_relative_path} ABSOLUTE)
-configure_file("${shiboken_version_path}"
- "${CMAKE_CURRENT_BINARY_DIR}/_git_shiboken_generator_version.py" @ONLY)
-
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/_git_shiboken_generator_version.py"
- DESTINATION "${PYTHON_SITE_PACKAGES}/${shiboken_generator_package_name}")
diff --git a/sources/shiboken2/generator/__init__.py.in b/sources/shiboken2/generator/__init__.py.in
deleted file mode 100644
index 4be6a833b..000000000
--- a/sources/shiboken2/generator/__init__.py.in
+++ /dev/null
@@ -1,2 +0,0 @@
-__version__ = "@FINAL_PACKAGE_VERSION@"
-__version_info__ = (@shiboken_MAJOR_VERSION@, @shiboken_MINOR_VERSION@, @shiboken_MICRO_VERSION@, "@shiboken_PRE_RELEASE_VERSION_TYPE@", "@shiboken_PRE_RELEASE_VERSION@")
diff --git a/sources/shiboken2/generator/_config.py.in b/sources/shiboken2/generator/_config.py.in
deleted file mode 100644
index 985735fa4..000000000
--- a/sources/shiboken2/generator/_config.py.in
+++ /dev/null
@@ -1,9 +0,0 @@
-version = "@FINAL_PACKAGE_VERSION@"
-version_info = (@shiboken_MAJOR_VERSION@, @shiboken_MINOR_VERSION@, @shiboken_MICRO_VERSION@, "@shiboken_PRE_RELEASE_VERSION_TYPE@", "@shiboken_PRE_RELEASE_VERSION@")
-
-@PACKAGE_BUILD_DATE@
-@PACKAGE_BUILD_COMMIT_DATE@
-@PACKAGE_BUILD_COMMIT_HASH@
-@PACKAGE_BUILD_COMMIT_HASH_DESCRIBED@
-@PACKAGE_SETUP_PY_PACKAGE_TIMESTAMP_ASSIGNMENT@
-@PACKAGE_SETUP_PY_PACKAGE_VERSION_ASSIGNMENT@
diff --git a/sources/shiboken2/generator/generator.cpp b/sources/shiboken2/generator/generator.cpp
deleted file mode 100644
index 88ba1f04f..000000000
--- a/sources/shiboken2/generator/generator.cpp
+++ /dev/null
@@ -1,989 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "generator.h"
-#include "abstractmetalang.h"
-#include "parser/codemodel.h"
-#include "messages.h"
-#include "reporthandler.h"
-#include "fileout.h"
-#include "apiextractor.h"
-#include "typesystem.h"
-
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QFileInfo>
-#include <QtCore/QRegularExpression>
-#include <QDebug>
-#include <typedatabase.h>
-
-/**
- * DefaultValue is used for storing default values of types for which code is
- * generated in different contexts:
- *
- * Context | Example: "Class *" | Example: "Class" with default Constructor
- * --------------------+-------------------------------+------------------------------------------
- * Variable | var{nullptr}; | var;
- * initializations | |
- * --------------------+-------------------------------+------------------------------------------
- * Return values | return nullptr; | return {}
- * --------------------+-------------------------------+------------------------------------------
- * constructor | static_cast<Class *>(nullptr) | Class()
- * arguments lists | |
- * (recursive, precise | |
- * matching). | |
- */
-
-DefaultValue::DefaultValue(Type t, QString value) :
- m_type(t), m_value(std::move(value))
-{
-}
-
-DefaultValue::DefaultValue(QString customValue) :
- m_type(Custom), m_value(std::move(customValue))
-{
-}
-
-QString DefaultValue::returnValue() const
-{
- switch (m_type) {
- case DefaultValue::Error:
- return QLatin1String("#error");
- case DefaultValue::Boolean:
- return QLatin1String("false");
- case DefaultValue::CppScalar:
- return QLatin1String("0");
- case DefaultValue::Custom:
- case DefaultValue::Enum:
- return m_value;
- case DefaultValue::Pointer:
- return QLatin1String("nullptr");
- case DefaultValue::Void:
- return QString();
- case DefaultValue::DefaultConstructorWithDefaultValues:
- return m_value + QLatin1String("()");
- case DefaultValue::DefaultConstructor:
- break;
- }
- return QLatin1String("{}");
-}
-
-QString DefaultValue::initialization() const
-{
- switch (m_type) {
- case DefaultValue::Error:
- return QLatin1String("#error");
- case DefaultValue::Boolean:
- return QLatin1String("{false}");
- case DefaultValue::CppScalar:
- return QLatin1String("{0}");
- case DefaultValue::Custom:
- return QLatin1String(" = ") + m_value;
- case DefaultValue::Enum:
- return QLatin1Char('{') + m_value + QLatin1Char('}');
- case DefaultValue::Pointer:
- return QLatin1String("{nullptr}");
- case DefaultValue::Void:
- Q_ASSERT(false);
- break;
- case DefaultValue::DefaultConstructor:
- case DefaultValue::DefaultConstructorWithDefaultValues:
- break;
- }
- return QString();
-}
-
-QString DefaultValue::constructorParameter() const
-{
- switch (m_type) {
- case DefaultValue::Error:
- return QLatin1String("#error");
- case DefaultValue::Boolean:
- return QLatin1String("false");
- case DefaultValue::CppScalar: {
- // PYSIDE-846: Use static_cast in case of "unsigned long" and similar
- const QString cast = m_value.contains(QLatin1Char(' '))
- ? QLatin1String("static_cast<") + m_value + QLatin1Char('>')
- : m_value;
- return cast + QLatin1String("(0)");
- }
- case DefaultValue::Custom:
- case DefaultValue::Enum:
- return m_value;
- case DefaultValue::Pointer:
- // Be precise here to be able to differentiate between constructors
- // taking different pointer types, cf
- // QTreeWidgetItemIterator(QTreeWidget *) and
- // QTreeWidgetItemIterator(QTreeWidgetItemIterator *).
- return QLatin1String("static_cast<") + m_value + QLatin1String("*>(nullptr)");
- case DefaultValue::Void:
- Q_ASSERT(false);
- break;
- case DefaultValue::DefaultConstructor:
- case DefaultValue::DefaultConstructorWithDefaultValues:
- break;
- }
- return m_value + QLatin1String("()");
-}
-
-QString GeneratorContext::smartPointerWrapperName() const
-{
- Q_ASSERT(m_type == SmartPointer);
- return m_preciseClassType->cppSignature();
-}
-
-struct Generator::GeneratorPrivate
-{
- const ApiExtractor *apiextractor = nullptr;
- QString outDir;
- // License comment
- QString licenseComment;
- QString moduleName;
- QStringList instantiatedContainersNames;
- QVector<const AbstractMetaType *> instantiatedContainers;
- QVector<const AbstractMetaType *> instantiatedSmartPointers;
-
-};
-
-Generator::Generator() : m_d(new GeneratorPrivate)
-{
-}
-
-Generator::~Generator()
-{
- delete m_d;
-}
-
-bool Generator::setup(const ApiExtractor &extractor)
-{
- m_d->apiextractor = &extractor;
- const auto moduleEntry = TypeDatabase::instance()->defaultTypeSystemType();
- if (!moduleEntry || !moduleEntry->generateCode()) {
- qCWarning(lcShiboken) << "Couldn't find the package name!!";
- return false;
- }
-
- collectInstantiatedContainersAndSmartPointers();
-
- return doSetup();
-}
-
-QString Generator::getSimplifiedContainerTypeName(const AbstractMetaType *type)
-{
- const QString signature = type->cppSignature();
- if (!type->typeEntry()->isContainer() && !type->typeEntry()->isSmartPointer())
- return signature;
- QString typeName = signature;
- if (type->isConstant())
- typeName.remove(0, sizeof("const ") / sizeof(char) - 1);
- switch (type->referenceType()) {
- case NoReference:
- break;
- case LValueReference:
- typeName.chop(1);
- break;
- case RValueReference:
- typeName.chop(2);
- break;
- }
- while (typeName.endsWith(QLatin1Char('*')) || typeName.endsWith(QLatin1Char(' ')))
- typeName.chop(1);
- return typeName;
-}
-
-// Strip a "const QSharedPtr<const Foo> &" or similar to "QSharedPtr<Foo>" (PYSIDE-1016/454)
-const AbstractMetaType *canonicalSmartPtrInstantiation(const AbstractMetaType *type)
-{
- AbstractMetaTypeList instantiations = type->instantiations();
- Q_ASSERT(instantiations.size() == 1);
- const bool needsFix = type->isConstant() || type->referenceType() != NoReference;
- const bool pointeeNeedsFix = instantiations.constFirst()->isConstant();
- if (!needsFix && !pointeeNeedsFix)
- return type;
- auto fixedType = type->copy();
- fixedType->setReferenceType(NoReference);
- fixedType->setConstant(false);
- if (pointeeNeedsFix) {
- auto fixedPointeeType = instantiations.constFirst()->copy();
- fixedPointeeType->setConstant(false);
- fixedType->setInstantiations(AbstractMetaTypeList(1, fixedPointeeType));
- }
- return fixedType;
-}
-
-static inline const TypeEntry *pointeeTypeEntry(const AbstractMetaType *smartPtrType)
-{
- return smartPtrType->instantiations().constFirst()->typeEntry();
-}
-
-void Generator::addInstantiatedContainersAndSmartPointers(const AbstractMetaType *type,
- const QString &context)
-{
- if (!type)
- return;
- const AbstractMetaTypeList &instantiations = type->instantiations();
- for (const AbstractMetaType *t : instantiations)
- addInstantiatedContainersAndSmartPointers(t, context);
- const auto typeEntry = type->typeEntry();
- const bool isContainer = typeEntry->isContainer();
- if (!isContainer
- && !(typeEntry->isSmartPointer() && typeEntry->generateCode())) {
- return;
- }
- if (type->hasTemplateChildren()) {
- QString piece = isContainer ? QStringLiteral("container") : QStringLiteral("smart pointer");
- QString warning =
- QString::fromLatin1("Skipping instantiation of %1 '%2' because it has template"
- " arguments.").arg(piece, type->originalTypeDescription());
- if (!context.isEmpty())
- warning.append(QStringLiteral(" Calling context: %1").arg(context));
-
- qCWarning(lcShiboken).noquote().nospace() << warning;
- return;
-
- }
- QString typeName = getSimplifiedContainerTypeName(type);
- if (isContainer) {
- if (!m_d->instantiatedContainersNames.contains(typeName)) {
- m_d->instantiatedContainersNames.append(typeName);
- m_d->instantiatedContainers.append(type);
- }
- } else {
- // Is smart pointer. Check if the (const?) pointee is already known
- auto pt = pointeeTypeEntry(type);
- const bool present =
- std::any_of(m_d->instantiatedSmartPointers.cbegin(), m_d->instantiatedSmartPointers.cend(),
- [pt] (const AbstractMetaType *t) {
- return pointeeTypeEntry(t) == pt;
- });
- if (!present)
- m_d->instantiatedSmartPointers.append(canonicalSmartPtrInstantiation(type));
- }
-
-}
-
-void Generator::collectInstantiatedContainersAndSmartPointers(const AbstractMetaFunction *func)
-{
- addInstantiatedContainersAndSmartPointers(func->type(), func->signature());
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments)
- addInstantiatedContainersAndSmartPointers(arg->type(), func->signature());
-}
-
-void Generator::collectInstantiatedContainersAndSmartPointers(const AbstractMetaClass *metaClass)
-{
- if (!metaClass->typeEntry()->generateCode())
- return;
- const AbstractMetaFunctionList &funcs = metaClass->functions();
- for (const AbstractMetaFunction *func : funcs)
- collectInstantiatedContainersAndSmartPointers(func);
- const AbstractMetaFieldList &fields = metaClass->fields();
- for (const AbstractMetaField *field : fields)
- addInstantiatedContainersAndSmartPointers(field->type(), field->name());
- const AbstractMetaClassList &innerClasses = metaClass->innerClasses();
- for (AbstractMetaClass *innerClass : innerClasses)
- collectInstantiatedContainersAndSmartPointers(innerClass);
-}
-
-void Generator::collectInstantiatedContainersAndSmartPointers()
-{
- const AbstractMetaFunctionList &funcs = globalFunctions();
- for (const AbstractMetaFunction *func : funcs)
- collectInstantiatedContainersAndSmartPointers(func);
- const AbstractMetaClassList &classList = classes();
- for (const AbstractMetaClass *metaClass : classList)
- collectInstantiatedContainersAndSmartPointers(metaClass);
-}
-
-QVector<const AbstractMetaType *> Generator::instantiatedContainers() const
-{
- return m_d->instantiatedContainers;
-}
-
-QVector<const AbstractMetaType *> Generator::instantiatedSmartPointers() const
-{
- return m_d->instantiatedSmartPointers;
-}
-
-Generator::OptionDescriptions Generator::options() const
-{
- return OptionDescriptions();
-}
-
-bool Generator::handleOption(const QString & /* key */, const QString & /* value */)
-{
- return false;
-}
-
-AbstractMetaClassList Generator::classes() const
-{
- return m_d->apiextractor->classes();
-}
-
-AbstractMetaClassList Generator::classesTopologicalSorted(const Dependencies &additionalDependencies) const
-{
- return m_d->apiextractor->classesTopologicalSorted(additionalDependencies);
-}
-
-AbstractMetaFunctionList Generator::globalFunctions() const
-{
- return m_d->apiextractor->globalFunctions();
-}
-
-AbstractMetaEnumList Generator::globalEnums() const
-{
- return m_d->apiextractor->globalEnums();
-}
-
-PrimitiveTypeEntryList Generator::primitiveTypes() const
-{
- return m_d->apiextractor->primitiveTypes();
-}
-
-ContainerTypeEntryList Generator::containerTypes() const
-{
- return m_d->apiextractor->containerTypes();
-}
-
-const AbstractMetaEnum *Generator::findAbstractMetaEnum(const TypeEntry *typeEntry) const
-{
- return m_d->apiextractor->findAbstractMetaEnum(typeEntry);
-}
-
-const AbstractMetaEnum *Generator::findAbstractMetaEnum(const AbstractMetaType *metaType) const
-{
- return m_d->apiextractor->findAbstractMetaEnum(metaType->typeEntry());
-}
-
-QString Generator::licenseComment() const
-{
- return m_d->licenseComment;
-}
-
-void Generator::setLicenseComment(const QString &licenseComment)
-{
- m_d->licenseComment = licenseComment;
-}
-
-QString Generator::packageName() const
-{
- return TypeDatabase::instance()->defaultPackageName();
-}
-
-QString Generator::moduleName() const
-{
- if (m_d->moduleName.isEmpty()) {
- m_d->moduleName = packageName();
- m_d->moduleName.remove(0, m_d->moduleName.lastIndexOf(QLatin1Char('.')) + 1);
- }
- return m_d->moduleName;
-}
-
-QString Generator::outputDirectory() const
-{
- return m_d->outDir;
-}
-
-void Generator::setOutputDirectory(const QString &outDir)
-{
- m_d->outDir = outDir;
-}
-
-bool Generator::generateFileForContext(const GeneratorContext &context)
-{
- const AbstractMetaClass *cls = context.metaClass();
-
- if (!shouldGenerate(cls))
- return true;
-
- const QString fileName = fileNameForContext(context);
- if (fileName.isEmpty())
- return true;
-
- QString filePath = outputDirectory() + QLatin1Char('/') + subDirectoryForClass(cls)
- + QLatin1Char('/') + fileName;
- FileOut fileOut(filePath);
-
- generateClass(fileOut.stream, context);
-
- return fileOut.done() != FileOut::Failure;
-}
-
-QString Generator::getFileNameBaseForSmartPointer(const AbstractMetaType *smartPointerType,
- const AbstractMetaClass *smartPointerClass) const
-{
- const AbstractMetaType *innerType = smartPointerType->getSmartPointerInnerType();
- QString fileName = smartPointerClass->qualifiedCppName().toLower();
- fileName.replace(QLatin1String("::"), QLatin1String("_"));
- fileName.append(QLatin1String("_"));
- fileName.append(innerType->name().toLower());
-
- return fileName;
-}
-
-GeneratorContext Generator::contextForClass(const AbstractMetaClass *c) const
-{
- GeneratorContext result;
- result.m_metaClass = c;
- return result;
-}
-
-GeneratorContext Generator::contextForSmartPointer(const AbstractMetaClass *c,
- const AbstractMetaType *t) const
-{
- GeneratorContext result;
- result.m_metaClass = c;
- result.m_preciseClassType = t;
- result.m_type = GeneratorContext::SmartPointer;
- return result;
-}
-
-bool Generator::generate()
-{
- const AbstractMetaClassList &classList = m_d->apiextractor->classes();
- for (AbstractMetaClass *cls : classList) {
- if (!generateFileForContext(contextForClass(cls)))
- return false;
- }
-
- const auto smartPointers = m_d->apiextractor->smartPointers();
- for (const AbstractMetaType *type : qAsConst(m_d->instantiatedSmartPointers)) {
- AbstractMetaClass *smartPointerClass =
- AbstractMetaClass::findClass(smartPointers, type->typeEntry());
- if (!smartPointerClass) {
- qCWarning(lcShiboken, "%s",
- qPrintable(msgCannotFindSmartPointer(type->cppSignature(),
- smartPointers)));
- return false;
- }
- if (!generateFileForContext(contextForSmartPointer(smartPointerClass, type)))
- return false;
- }
- return finishGeneration();
-}
-
-bool Generator::shouldGenerateTypeEntry(const TypeEntry *type) const
-{
- return (type->codeGeneration() & TypeEntry::GenerateTargetLang)
- && NamespaceTypeEntry::isVisibleScope(type);
-}
-
-bool Generator::shouldGenerate(const AbstractMetaClass *metaClass) const
-{
- return shouldGenerateTypeEntry(metaClass->typeEntry());
-}
-
-void verifyDirectoryFor(const QString &file)
-{
- QDir dir = QFileInfo(file).absoluteDir();
- if (!dir.exists()) {
- if (!dir.mkpath(dir.absolutePath())) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("unable to create directory '%1'").arg(dir.absolutePath());
- }
- }
-}
-
-void Generator::replaceTemplateVariables(QString &code, const AbstractMetaFunction *func)
-{
- const AbstractMetaClass *cpp_class = func->ownerClass();
- if (cpp_class)
- code.replace(QLatin1String("%TYPE"), cpp_class->name());
-
- const AbstractMetaArgumentList &argument = func->arguments();
- for (AbstractMetaArgument *arg : argument)
- code.replace(QLatin1Char('%') + QString::number(arg->argumentIndex() + 1), arg->name());
-
- //template values
- code.replace(QLatin1String("%RETURN_TYPE"), translateType(func->type(), cpp_class));
- code.replace(QLatin1String("%FUNCTION_NAME"), func->originalName());
-
- if (code.contains(QLatin1String("%ARGUMENT_NAMES"))) {
- QString str;
- QTextStream aux_stream(&str);
- writeArgumentNames(aux_stream, func, Generator::SkipRemovedArguments);
- code.replace(QLatin1String("%ARGUMENT_NAMES"), str);
- }
-
- if (code.contains(QLatin1String("%ARGUMENTS"))) {
- QString str;
- QTextStream aux_stream(&str);
- writeFunctionArguments(aux_stream, func, Options(SkipDefaultValues) | SkipRemovedArguments);
- code.replace(QLatin1String("%ARGUMENTS"), str);
- }
-}
-
-QTextStream &formatCode(QTextStream &s, const QString &code, Indentor &indentor)
-{
- // detect number of spaces before the first character
- const QStringList lst(code.split(QLatin1Char('\n')));
- static const QRegularExpression nonSpaceRegex(QStringLiteral("[^\\s]"));
- Q_ASSERT(nonSpaceRegex.isValid());
- int spacesToRemove = 0;
- for (const QString &line : lst) {
- if (!line.trimmed().isEmpty()) {
- spacesToRemove = line.indexOf(nonSpaceRegex);
- if (spacesToRemove == -1)
- spacesToRemove = 0;
- break;
- }
- }
-
- static const QRegularExpression emptyLine(QStringLiteral("^\\s*[\\r]?[\\n]?\\s*$"));
- Q_ASSERT(emptyLine.isValid());
-
- for (QString line : lst) {
- if (!line.isEmpty() && !emptyLine.match(line).hasMatch()) {
- while (line.constEnd()->isSpace())
- line.chop(1);
- int limit = 0;
- for(int i = 0; i < spacesToRemove; ++i) {
- if (!line[i].isSpace())
- break;
- limit++;
- }
-
- s << indentor << line.remove(0, limit);
- }
- s << Qt::endl;
- }
- return s;
-}
-
-AbstractMetaFunctionList Generator::implicitConversions(const TypeEntry *type) const
-{
- if (type->isValue()) {
- if (const AbstractMetaClass *metaClass = AbstractMetaClass::findClass(classes(), type))
- return metaClass->implicitConversions();
- }
- return AbstractMetaFunctionList();
-}
-
-AbstractMetaFunctionList Generator::implicitConversions(const AbstractMetaType *metaType) const
-{
- return implicitConversions(metaType->typeEntry());
-}
-
-bool Generator::isObjectType(const TypeEntry *type)
-{
- if (type->isComplex())
- return Generator::isObjectType(static_cast<const ComplexTypeEntry *>(type));
- return type->isObject();
-}
-bool Generator::isObjectType(const ComplexTypeEntry *type)
-{
- return type->isObject();
-}
-bool Generator::isObjectType(const AbstractMetaClass *metaClass)
-{
- return Generator::isObjectType(metaClass->typeEntry());
-}
-bool Generator::isObjectType(const AbstractMetaType *metaType)
-{
- return isObjectType(metaType->typeEntry());
-}
-
-bool Generator::isPointer(const AbstractMetaType *type)
-{
- return type->indirections() > 0
- || type->isNativePointer()
- || type->isValuePointer();
-}
-
-bool Generator::isCString(const AbstractMetaType *type)
-{
- return type->isNativePointer()
- && type->indirections() == 1
- && type->name() == QLatin1String("char");
-}
-
-bool Generator::isVoidPointer(const AbstractMetaType *type)
-{
- return type->isNativePointer()
- && type->indirections() == 1
- && type->name() == QLatin1String("void");
-}
-
-QString Generator::getFullTypeName(const TypeEntry *type) const
-{
- QString result = type->qualifiedCppName();
- if (type->isArray())
- type = static_cast<const ArrayTypeEntry *>(type)->nestedTypeEntry();
- if (!type->isCppPrimitive())
- result.prepend(QLatin1String("::"));
- return result;
-}
-
-QString Generator::getFullTypeName(const AbstractMetaType *type) const
-{
- if (isCString(type))
- return QLatin1String("const char*");
- if (isVoidPointer(type))
- return QLatin1String("void*");
- if (type->typeEntry()->isContainer())
- return QLatin1String("::") + type->cppSignature();
- QString typeName;
- if (type->typeEntry()->isComplex() && type->hasInstantiations())
- typeName = getFullTypeNameWithoutModifiers(type);
- else
- typeName = getFullTypeName(type->typeEntry());
- return typeName + QString::fromLatin1("*").repeated(type->indirections());
-}
-
-QString Generator::getFullTypeName(const AbstractMetaClass *metaClass) const
-{
- return QLatin1String("::") + metaClass->qualifiedCppName();
-}
-
-QString Generator::getFullTypeNameWithoutModifiers(const AbstractMetaType *type) const
-{
- if (isCString(type))
- return QLatin1String("const char*");
- if (isVoidPointer(type))
- return QLatin1String("void*");
- if (!type->hasInstantiations())
- return getFullTypeName(type->typeEntry());
- QString typeName = type->cppSignature();
- if (type->isConstant())
- typeName.remove(0, sizeof("const ") / sizeof(char) - 1);
- switch (type->referenceType()) {
- case NoReference:
- break;
- case LValueReference:
- typeName.chop(1);
- break;
- case RValueReference:
- typeName.chop(2);
- break;
- }
- while (typeName.endsWith(QLatin1Char('*')) || typeName.endsWith(QLatin1Char(' ')))
- typeName.chop(1);
- return QLatin1String("::") + typeName;
-}
-
-DefaultValue Generator::minimalConstructor(const AbstractMetaType *type) const
-{
- if (!type || (type->referenceType() == LValueReference && Generator::isObjectType(type)))
- return DefaultValue(DefaultValue::Error);
-
- if (type->isContainer()) {
- QString ctor = type->cppSignature();
- if (ctor.endsWith(QLatin1Char('*'))) {
- ctor.chop(1);
- return DefaultValue(DefaultValue::Pointer, ctor.trimmed());
- }
- if (ctor.startsWith(QLatin1String("const ")))
- ctor.remove(0, sizeof("const ") / sizeof(char) - 1);
- if (ctor.endsWith(QLatin1Char('&'))) {
- ctor.chop(1);
- ctor = ctor.trimmed();
- }
- return DefaultValue(DefaultValue::DefaultConstructor, QLatin1String("::") + ctor);
- }
-
- if (type->isNativePointer())
- return DefaultValue(DefaultValue::Pointer, type->typeEntry()->qualifiedCppName());
- if (Generator::isPointer(type))
- return DefaultValue(DefaultValue::Pointer, QLatin1String("::") + type->typeEntry()->qualifiedCppName());
-
- if (type->typeEntry()->isSmartPointer())
- return minimalConstructor(type->typeEntry());
-
- if (type->typeEntry()->isComplex()) {
- auto cType = static_cast<const ComplexTypeEntry *>(type->typeEntry());
- if (cType->hasDefaultConstructor())
- return DefaultValue(DefaultValue::Custom, cType->defaultConstructor());
- auto ctor = minimalConstructor(AbstractMetaClass::findClass(classes(), cType));
- if (ctor.isValid() && type->hasInstantiations()) {
- QString v = ctor.value();
- v.replace(getFullTypeName(cType), getFullTypeNameWithoutModifiers(type));
- ctor.setValue(v);
- }
- return ctor;
- }
-
- return minimalConstructor(type->typeEntry());
-}
-
-DefaultValue Generator::minimalConstructor(const TypeEntry *type) const
-{
- if (!type)
- return DefaultValue(DefaultValue::Error);
-
- if (type->isCppPrimitive()) {
- const QString &name = type->qualifiedCppName();
- return name == QLatin1String("bool")
- ? DefaultValue(DefaultValue::Boolean)
- : DefaultValue(DefaultValue::CppScalar, name);
- }
-
- if (type->isEnum()) {
- const auto enumEntry = static_cast<const EnumTypeEntry *>(type);
- if (const auto *nullValue = enumEntry->nullValue())
- return DefaultValue(DefaultValue::Enum, nullValue->name());
- return DefaultValue(DefaultValue::Custom,
- QLatin1String("static_cast< ::") + type->qualifiedCppName()
- + QLatin1String(">(0)"));
- }
-
- if (type->isFlags()) {
- return DefaultValue(DefaultValue::Custom,
- type->qualifiedCppName() + QLatin1String("(0)"));
- }
-
- if (type->isPrimitive()) {
- QString ctor = static_cast<const PrimitiveTypeEntry *>(type)->defaultConstructor();
- // If a non-C++ (i.e. defined by the user) primitive type does not have
- // a default constructor defined by the user, the empty constructor is
- // heuristically returned. If this is wrong the build of the generated
- // bindings will tell.
- return ctor.isEmpty()
- ? DefaultValue(DefaultValue::DefaultConstructorWithDefaultValues, QLatin1String("::")
- + type->qualifiedCppName())
- : DefaultValue(DefaultValue::Custom, ctor);
- }
-
- if (type->isSmartPointer())
- return DefaultValue(DefaultValue::DefaultConstructor, type->qualifiedCppName());
-
- if (type->isComplex())
- return minimalConstructor(AbstractMetaClass::findClass(classes(), type));
-
- return DefaultValue(DefaultValue::Error);
-}
-
-static QString constructorCall(const QString &qualifiedCppName, const QStringList &args)
-{
- return QLatin1String("::") + qualifiedCppName + QLatin1Char('(')
- + args.join(QLatin1String(", ")) + QLatin1Char(')');
-}
-
-DefaultValue Generator::minimalConstructor(const AbstractMetaClass *metaClass) const
-{
- if (!metaClass)
- return DefaultValue(DefaultValue::Error);
-
- auto cType = static_cast<const ComplexTypeEntry *>(metaClass->typeEntry());
- if (cType->hasDefaultConstructor())
- return DefaultValue(DefaultValue::Custom, cType->defaultConstructor());
-
- const QString qualifiedCppName = cType->qualifiedCppName();
- // Obtain a list of constructors sorted by complexity and number of arguments
- QMultiMap<int, const AbstractMetaFunction *> candidates;
- const AbstractMetaFunctionList &constructors = metaClass->queryFunctions(AbstractMetaClass::Constructors);
- for (const AbstractMetaFunction *ctor : constructors) {
- if (!ctor->isUserAdded() && !ctor->isPrivate()
- && ctor->functionType() == AbstractMetaFunction::ConstructorFunction) {
- // No arguments: Default constructible
- const auto &arguments = ctor->arguments();
- if (arguments.isEmpty()) {
- return DefaultValue(DefaultValue::DefaultConstructor,
- QLatin1String("::") + qualifiedCppName);
- }
- // First argument has unmodified default: Default constructible with values
- if (arguments.constFirst()->hasUnmodifiedDefaultValueExpression()) {
- return DefaultValue(DefaultValue::DefaultConstructorWithDefaultValues,
- QLatin1String("::") + qualifiedCppName);
- }
- // Examine arguments, exclude functions taking a self parameter
- bool simple = true;
- bool suitable = true;
- for (int i = 0, size = arguments.size();
- suitable && i < size && !arguments.at(i)->hasOriginalDefaultValueExpression(); ++i) {
- const AbstractMetaArgument *arg = arguments.at(i);
- const TypeEntry *aType = arg->type()->typeEntry();
- suitable &= aType != cType;
- simple &= aType->isCppPrimitive() || aType->isEnum() || isPointer(arg->type());
- }
- if (suitable)
- candidates.insert(arguments.size() + (simple ? 0 : 100), ctor);
- }
- }
-
- for (auto it = candidates.cbegin(), end = candidates.cend(); it != end; ++it) {
- const AbstractMetaArgumentList &arguments = it.value()->arguments();
- QStringList args;
- bool ok = true;
- for (int i =0, size = arguments.size(); ok && i < size; ++i) {
- const AbstractMetaArgument *arg = arguments.at(i);
- if (arg->hasModifiedDefaultValueExpression()) {
- args << arg->defaultValueExpression(); // Spell out modified values
- break;
- }
- if (arg->hasOriginalDefaultValueExpression())
- break;
- auto argValue = minimalConstructor(arg->type());
- ok &= argValue.isValid();
- args << argValue.constructorParameter();
- }
- if (ok)
- return DefaultValue(DefaultValue::Custom, constructorCall(qualifiedCppName, args));
- }
-
- return DefaultValue(DefaultValue::Error);
-}
-
-// Should int be used for a (protected) enum when generating the public wrapper?
-bool Generator::useEnumAsIntForProtectedHack(const AbstractMetaType *metaType) const
-{
- if (metaType->isFlags())
- return true;
- if (!metaType->isEnum())
- return false;
- const AbstractMetaEnum *metaEnum = findAbstractMetaEnum(metaType);
- if (!metaEnum)
- return true;
- if (metaEnum->attributes() & AbstractMetaAttributes::Public) // No reason, type is public
- return false;
- // Only ordinary C-enums can be used as int, scoped enums fail when used
- // as function arguments.
- if (metaEnum->enumKind() == EnumKind::EnumClass)
- qWarning(lcShiboken, "%s", qPrintable(msgCannotUseEnumAsInt(metaEnum->name())));
- return true;
-}
-
-QString Generator::translateType(const AbstractMetaType *cType,
- const AbstractMetaClass *context,
- Options options) const
-{
- QString s;
- static int constLen = strlen("const");
-
- if (context && cType &&
- context->typeEntry()->isGenericClass() &&
- cType->originalTemplateType()) {
- cType = cType->originalTemplateType();
- }
-
- if (!cType) {
- s = QLatin1String("void");
- } else if (cType->isArray()) {
- s = translateType(cType->arrayElementType(), context, options) + QLatin1String("[]");
- } else if ((options & Generator::EnumAsInts) && useEnumAsIntForProtectedHack(cType)) {
- s = QLatin1String("int");
- } else {
- if (options & Generator::OriginalName) {
- s = cType->originalTypeDescription().trimmed();
- if ((options & Generator::ExcludeReference) && s.endsWith(QLatin1Char('&')))
- s.chop(1);
-
- // remove only the last const (avoid remove template const)
- if (options & Generator::ExcludeConst) {
- int index = s.lastIndexOf(QLatin1String("const"));
-
- if (index >= (s.size() - (constLen + 1))) // (VarType const) or (VarType const[*|&])
- s = s.remove(index, constLen);
- }
- } else if (options & Generator::ExcludeConst || options & Generator::ExcludeReference) {
- AbstractMetaType *copyType = cType->copy();
-
- if (options & Generator::ExcludeConst)
- copyType->setConstant(false);
-
- if (options & Generator::ExcludeReference)
- copyType->setReferenceType(NoReference);
-
- s = copyType->cppSignature();
- if (!copyType->typeEntry()->isVoid() && !copyType->typeEntry()->isCppPrimitive())
- s.prepend(QLatin1String("::"));
- delete copyType;
- } else {
- s = cType->cppSignature();
- }
- }
-
- return s;
-}
-
-
-QString Generator::subDirectoryForClass(const AbstractMetaClass *clazz) const
-{
- return subDirectoryForPackage(clazz->package());
-}
-
-QString Generator::subDirectoryForPackage(QString packageNameIn) const
-{
- if (packageNameIn.isEmpty())
- packageNameIn = packageName();
- packageNameIn.replace(QLatin1Char('.'), QDir::separator());
- return packageNameIn;
-}
-
-template<typename T>
-static QString getClassTargetFullName_(const T *t, bool includePackageName)
-{
- QString name = t->name();
- const AbstractMetaClass *context = t->enclosingClass();
- while (context) {
- // If the type was marked as 'visible=false' we should not use it in
- // the type name
- if (NamespaceTypeEntry::isVisibleScope(context->typeEntry())) {
- name.prepend(QLatin1Char('.'));
- name.prepend(context->name());
- }
- context = context->enclosingClass();
- }
- if (includePackageName) {
- name.prepend(QLatin1Char('.'));
- name.prepend(t->package());
- }
- return name;
-}
-
-QString getClassTargetFullName(const AbstractMetaClass *metaClass, bool includePackageName)
-{
- return getClassTargetFullName_(metaClass, includePackageName);
-}
-
-QString getClassTargetFullName(const AbstractMetaEnum *metaEnum, bool includePackageName)
-{
- return getClassTargetFullName_(metaEnum, includePackageName);
-}
-
-QString getClassTargetFullName(const AbstractMetaType *metaType, bool includePackageName)
-{
- QString name = metaType->cppSignature();
- name.replace(QLatin1String("::"), QLatin1String("_"));
- name.replace(QLatin1Char('<'), QLatin1Char('_'));
- name.remove(QLatin1Char('>'));
- name.remove(QLatin1Char(' '));
- if (includePackageName) {
- name.prepend(QLatin1Char('.'));
- name.prepend(metaType->package());
- }
- return name;
-}
-
-QString getFilteredCppSignatureString(QString signature)
-{
- signature.replace(QLatin1String("::"), QLatin1String("_"));
- signature.replace(QLatin1Char('<'), QLatin1Char('_'));
- signature.replace(QLatin1Char('>'), QLatin1Char('_'));
- signature.replace(QLatin1Char(' '), QLatin1Char('_'));
- return signature;
-}
diff --git a/sources/shiboken2/generator/generator.h b/sources/shiboken2/generator/generator.h
deleted file mode 100644
index 5a55422a1..000000000
--- a/sources/shiboken2/generator/generator.h
+++ /dev/null
@@ -1,433 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef GENERATOR_H
-#define GENERATOR_H
-
-#include "indentor.h"
-#include <abstractmetalang_typedefs.h>
-#include <typedatabase_typedefs.h>
-#include <dependency.h>
-#include <QtCore/QObject>
-#include <QtCore/QSharedPointer>
-#include <QtCore/QTextStream>
-#include <QtCore/QVector>
-
-class ApiExtractor;
-class AbstractMetaBuilder;
-class AbstractMetaFunction;
-class AbstractMetaClass;
-class AbstractMetaEnum;
-class TypeEntry;
-class ComplexTypeEntry;
-class AbstractMetaType;
-class EnumTypeEntry;
-class FlagsTypeEntry;
-
-QT_BEGIN_NAMESPACE
-class QFile;
-QT_END_NAMESPACE
-
-class PrimitiveTypeEntry;
-class ContainerTypeEntry;
-
-QTextStream &formatCode(QTextStream &s, const QString &code, Indentor &indentor);
-void verifyDirectoryFor(const QString &file);
-
-QString getClassTargetFullName(const AbstractMetaClass *metaClass, bool includePackageName = true);
-QString getClassTargetFullName(const AbstractMetaEnum *metaEnum, bool includePackageName = true);
-QString getClassTargetFullName(const AbstractMetaType *metaType, bool includePackageName = true);
-QString getFilteredCppSignatureString(QString signature);
-
-/**
- * PYSIDE-504: Handling the "protected hack"
- *
- * The problem: Creating wrappers when the class has private destructors.
- * You can see an example on Windows in qclipboard_wrapper.h and others.
- * Simply search for the text "// C++11: need to declare (unimplemented) destructor".
- *
- * The protected hack is the definition "#define protected public".
- * For most compilers, this "hack" is enabled, because the problem of private
- * destructors simply vanishes.
- *
- * If one does not want to use this hack, then a new problem arises:
- * C++11 requires that a destructor is declared in a wrapper class when it is
- * private in the base class. There is no implementation allowed!
- *
- * Unfortunately, MSVC in recent versions supports C++11, and due to restrictive
- * rules, it is impossible to use the hack with this compiler.
- * More unfortunate: Clang, when C++11 is enabled, also enforces a declaration
- * of a private destructor, but it falsely then creates a linker error!
- *
- * Originally, we wanted to remove the protected hack. But due to the Clang
- * problem, we gave up on removal of the protected hack and use it always
- * when we can. This might change again when the Clang problem is solved.
- */
-
-#ifdef Q_CC_MSVC
-const int alwaysGenerateDestructor = 1;
-#else
-const int alwaysGenerateDestructor = 0;
-#endif
-
-class DefaultValue
-{
-public:
- enum Type
- {
- Error,
- Boolean,
- CppScalar, // A C++ scalar type (int,..) specified by value()
- Custom, // A custom constructor/expression, uses value() as is
- DefaultConstructor, // For classes named value()
- DefaultConstructorWithDefaultValues, // as DefaultConstructor, but can't return {} though.
- Enum, // Enum value as specified by value()
- Pointer, // Pointer of type value()
- Void // "", for return values only
- };
-
- explicit DefaultValue(Type t = Error, QString value = QString());
- explicit DefaultValue(QString customValue);
-
- bool isValid() const { return m_type != Error; }
-
- QString returnValue() const;
- QString initialization() const;
- QString constructorParameter() const;
-
- QString value() const { return m_value; }
- void setValue(const QString &value) { m_value = value; }
-
- Type type() const { return m_type; }
- void setType(Type type) { m_type = type; }
-
-private:
- Type m_type;
- QString m_value;
-};
-
-/**
- * A GeneratorContext object contains a pointer to an AbstractMetaClass and/or a specialized
- * AbstractMetaType, for which code is currently being generated.
- *
- * The main case is when the context contains only an AbstractMetaClass pointer, which is used
- * by different methods to generate appropriate expressions, functions, type names, etc.
- *
- * The second case is for generation of code for smart pointers. In this case the m_metaClass member
- * contains the generic template class of the smart pointer, and the m_preciseClassType member
- * contains the instantiated template type, e.g. a concrete shared_ptr<int>. To
- * distinguish this case, the member m_forSmartPointer is set to true.
- *
- * In the future the second case might be generalized for all template type instantiations.
- */
-class GeneratorContext {
- friend class ShibokenGenerator;
- friend class Generator;
-public:
- enum Type { Class, WrappedClass, SmartPointer };
-
- GeneratorContext() = default;
-
- const AbstractMetaClass *metaClass() const { return m_metaClass; }
- const AbstractMetaType *preciseType() const { return m_preciseClassType; }
-
- bool forSmartPointer() const { return m_type == SmartPointer; }
- bool useWrapper() const { return m_type == WrappedClass; }
-
- QString wrapperName() const
- {
- Q_ASSERT(m_type == WrappedClass);
- return m_wrappername;
- }
-
- QString smartPointerWrapperName() const;
-
-private:
- const AbstractMetaClass *m_metaClass = nullptr;
- const AbstractMetaType *m_preciseClassType = nullptr;
- QString m_wrappername;
- Type m_type = Class;
-};
-
-/**
- * Base class for all generators. The default implementations does nothing,
- * you must subclass this to create your own generators.
- */
-class Generator
-{
-public:
- using OptionDescription = QPair<QString, QString>;
- using OptionDescriptions = QVector<OptionDescription>;
-
- /// Optiosn used around the generator code
- enum Option {
- NoOption = 0x00000000,
- ExcludeConst = 0x00000001,
- ExcludeReference = 0x00000002,
-
- EnumAsInts = 0x00000004,
- SkipName = 0x00000008,
- SkipReturnType = 0x00000010,
- OriginalName = 0x00000020,
- VirtualCall = 0x00000040,
- OriginalTypeDescription = 0x00000080,
- SkipRemovedArguments = 0x00000100,
-
- SkipDefaultValues = 0x00000200,
-
- WriteSelf = 0x00000400,
- ExcludeMethodConst = 0x00000800,
-
- ForceValueType = ExcludeReference | ExcludeConst
- };
- Q_DECLARE_FLAGS(Options, Option)
-
- Generator();
- virtual ~Generator();
-
- bool setup(const ApiExtractor &extractor);
-
- virtual OptionDescriptions options() const;
- virtual bool handleOption(const QString &key, const QString &value);
-
- /// Returns the classes used to generate the binding code.
- AbstractMetaClassList classes() const;
-
- /// Returns the output directory
- QString outputDirectory() const;
-
- /// Set the output directory
- void setOutputDirectory(const QString &outDir);
-
- /**
- * Start the code generation, be sure to call setClasses before callign this method.
- * For each class it creates a QTextStream, call the write method with the current
- * class and the associated text stream, then write the text stream contents if needed.
- * \see #write
- */
- bool generate();
-
- /// Returns the license comment to be prepended to each source file generated.
- QString licenseComment() const;
-
- /// Sets the license comment to be prepended to each source file generated.
- void setLicenseComment(const QString &licenseComment);
-
- /// Returns the generator's name. Used for cosmetic purposes.
- virtual const char *name() const = 0;
-
- /**
- * Retrieves the name of the currently processed module.
- * While package name is a complete package idetification, e.g. 'PySide.QtCore',
- * a module name represents the last part of the package, e.g. 'QtCore'.
- * If the target language separates the modules with characters other than
- * dots ('.') the generator subclass must overload this method.
- * \return a string representing the last part of a package name
- */
- QString moduleName() const;
-
- /**
- * Retrieves a list of constructors used in implicit conversions
- * available on the given type. The TypeEntry must be a value-type
- * or else it will return an empty list.
- * \param type a TypeEntry that is expected to be a value-type
- * \return a list of constructors that could be used as implicit converters
- */
- AbstractMetaFunctionList implicitConversions(const TypeEntry *type) const;
-
- /// Convenience function for implicitConversions(const TypeEntry *type).
- AbstractMetaFunctionList implicitConversions(const AbstractMetaType *metaType) const;
-
- /// Check if type is a pointer.
- static bool isPointer(const AbstractMetaType *type);
-
- /// Tells if the type or class is an Object (or QObject) Type.
- static bool isObjectType(const TypeEntry *type);
- static bool isObjectType(const ComplexTypeEntry *type);
- static bool isObjectType(const AbstractMetaType *metaType);
- static bool isObjectType(const AbstractMetaClass *metaClass);
-
- /// Returns true if the type is a C string (const char *).
- static bool isCString(const AbstractMetaType *type);
- /// Returns true if the type is a void pointer.
- static bool isVoidPointer(const AbstractMetaType *type);
-
-protected:
- /// Returns the classes, topologically ordered, used to generate the binding code.
- ///
- /// The classes are ordered such that derived classes appear later in the list than
- /// their parent classes.
- AbstractMetaClassList classesTopologicalSorted(const Dependencies &additionalDependencies = Dependencies()) const;
-
- /// Returns all global functions found by APIExtractor
- AbstractMetaFunctionList globalFunctions() const;
-
- /// Returns all global enums found by APIExtractor
- AbstractMetaEnumList globalEnums() const;
-
- /// Returns all primitive types found by APIExtractor
- PrimitiveTypeEntryList primitiveTypes() const;
-
- /// Returns all container types found by APIExtractor
- ContainerTypeEntryList containerTypes() const;
-
- /// Returns an AbstractMetaEnum for a given TypeEntry that is an EnumTypeEntry, or nullptr if not found.
- const AbstractMetaEnum *findAbstractMetaEnum(const TypeEntry *typeEntry) const;
-
- /// Returns an AbstractMetaEnum for a given AbstractMetaType that holds an EnumTypeEntry, or nullptr if not found.
- const AbstractMetaEnum *findAbstractMetaEnum(const AbstractMetaType *metaType) const;
-
- virtual GeneratorContext contextForClass(const AbstractMetaClass *c) const;
- GeneratorContext contextForSmartPointer(const AbstractMetaClass *c,
- const AbstractMetaType *t) const;
-
- /// Generates a file for given AbstractMetaClass or AbstractMetaType (smart pointer case).
- bool generateFileForContext(const GeneratorContext &context);
-
- /// Returns the file base name for a smart pointer.
- QString getFileNameBaseForSmartPointer(const AbstractMetaType *smartPointerType,
- const AbstractMetaClass *smartPointerClass) const;
-
- /// Returns true if the generator should generate any code for the TypeEntry.
- bool shouldGenerateTypeEntry(const TypeEntry *) const;
-
- /// Returns true if the generator should generate any code for the AbstractMetaClass.
- virtual bool shouldGenerate(const AbstractMetaClass *) const;
-
- /// Returns the subdirectory used to write the binding code of an AbstractMetaClass.
- virtual QString subDirectoryForClass(const AbstractMetaClass *clazz) const;
-
- /**
- * Translate metatypes to binding source format.
- * \param metatype a pointer to metatype
- * \param context the current meta class
- * \param option some extra options
- * \return the metatype translated to binding source format
- */
- QString translateType(const AbstractMetaType *metatype,
- const AbstractMetaClass *context,
- Options options = NoOption) const;
-
- /**
- * Function used to write the fucntion arguments on the class buffer.
- * \param s the class output buffer
- * \param metafunction the pointer to metafunction information
- * \param count the number of function arguments
- * \param options some extra options used during the parser
- */
- virtual void writeFunctionArguments(QTextStream &s,
- const AbstractMetaFunction *metafunction,
- Options options = NoOption) const = 0;
-
- virtual void writeArgumentNames(QTextStream &s,
- const AbstractMetaFunction *metafunction,
- Options options = NoOption) const = 0;
-
- void replaceTemplateVariables(QString &code, const AbstractMetaFunction *func);
-
- /**
- * Returns the package name.
- */
- QString packageName() const;
-
- // Returns the full name of the type.
- QString getFullTypeName(const TypeEntry *type) const;
- QString getFullTypeName(const AbstractMetaType *type) const;
- QString getFullTypeName(const AbstractMetaClass *metaClass) const;
-
- /**
- * Returns the full qualified C++ name for an AbstractMetaType, but removing modifiers
- * as 'const', '&', and '*' (except if the class is not derived from a template).
- * This is useful for instantiated templates.
- */
- QString getFullTypeNameWithoutModifiers(const AbstractMetaType *type) const;
-
- /**
- * Tries to build a minimal constructor for the type.
- * It will check first for a user defined default constructor.
- * Returns a null string if it fails.
- */
- DefaultValue minimalConstructor(const TypeEntry *type) const;
- DefaultValue minimalConstructor(const AbstractMetaType *type) const;
- DefaultValue minimalConstructor(const AbstractMetaClass *metaClass) const;
-
- /**
- * Returns the file name used to write the binding code of an AbstractMetaClass/Type.
- * \param context the GeneratorContext which contains an AbstractMetaClass or AbstractMetaType
- * for which the file name must be returned
- * \return the file name used to write the binding code for the class
- */
- virtual QString fileNameSuffix() const = 0;
- virtual QString fileNameForContext(const GeneratorContext &context) const = 0;
-
-
- virtual bool doSetup() = 0;
-
- /**
- * Write the bindding code for an AbstractMetaClass.
- * This is called by generate method.
- * \param s text stream to write the generated output
- * \param metaClass the class that should be generated
- */
- virtual void generateClass(QTextStream &s, const GeneratorContext &classContext) = 0;
- virtual bool finishGeneration() = 0;
-
- /**
- * Returns the subdirectory path for a given package
- * (aka module, aka library) name.
- * If the target language separates the package modules with characters other
- * than dots ('.') the generator subclass must overload this method.
- * /param packageName complete package name for which to return the subdirectory path
- * or nothing the use the name of the currently processed package
- * /return a string representing the subdirectory path for the given package
- */
- virtual QString subDirectoryForPackage(QString packageName = QString()) const;
-
- QVector<const AbstractMetaType *> instantiatedContainers() const;
- QVector<const AbstractMetaType *> instantiatedSmartPointers() const;
-
- static QString getSimplifiedContainerTypeName(const AbstractMetaType *type);
- void addInstantiatedContainersAndSmartPointers(const AbstractMetaType *type,
- const QString &context);
-
-private:
- bool useEnumAsIntForProtectedHack(const AbstractMetaType *cType) const;
-
- struct GeneratorPrivate;
- GeneratorPrivate *m_d;
- void collectInstantiatedContainersAndSmartPointers(const AbstractMetaFunction *func);
- void collectInstantiatedContainersAndSmartPointers(const AbstractMetaClass *metaClass);
- void collectInstantiatedContainersAndSmartPointers();
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(Generator::Options)
-using GeneratorPtr = QSharedPointer<Generator>;
-using Generators = QVector<GeneratorPtr>;
-
-#endif // GENERATOR_H
-
diff --git a/sources/shiboken2/generator/indentor.h b/sources/shiboken2/generator/indentor.h
deleted file mode 100644
index 111259f12..000000000
--- a/sources/shiboken2/generator/indentor.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef INDENTOR_H
-#define INDENTOR_H
-
-#include <QtCore/QTextStream>
-
-/**
-* Utility class to store the indentation level, use it in a QTextStream.
-*/
-
-template <int tabWidth>
-class IndentorBase
-{
-public:
- int total() const { return tabWidth * indent; }
-
- int indent = 0;
-};
-
-using Indentor = IndentorBase<4>;
-using Indentor1 = IndentorBase<1>;
-
-/**
-* Class that use the RAII idiom to set and unset the indentation level.
-*/
-
-template <int tabWidth>
-class IndentationBase
-{
-public:
- using Indentor = IndentorBase<tabWidth>;
-
- IndentationBase(Indentor &indentor, int count = 1) : m_count(count), indentor(indentor)
- {
- indentor.indent += m_count;
- }
-
- ~IndentationBase()
- {
- indentor.indent -= m_count;
- }
-
-private:
- const int m_count;
- Indentor &indentor;
-};
-
-using Indentation = IndentationBase<4>;
-
-template <int tabWidth>
-inline QTextStream &operator <<(QTextStream &s, const IndentorBase<tabWidth> &indentor)
-{
- for (int i = 0, total = indentor.total(); i < total; ++i)
- s << ' ';
- return s;
-}
-
-#endif // GENERATOR_H
diff --git a/sources/shiboken2/generator/main.cpp b/sources/shiboken2/generator/main.cpp
deleted file mode 100644
index 841691484..000000000
--- a/sources/shiboken2/generator/main.cpp
+++ /dev/null
@@ -1,643 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QCoreApplication>
-#include <QLibrary>
-#include <QtCore/QFile>
-#include <QtCore/QDir>
-#include <iostream>
-#include <apiextractor.h>
-#include <fileout.h>
-#include <reporthandler.h>
-#include <typedatabase.h>
-#include <messages.h>
-#include "generator.h"
-#include "shibokenconfig.h"
-#include "cppgenerator.h"
-#include "headergenerator.h"
-#include "qtdocgenerator.h"
-
-#ifdef _WINDOWS
-static const QChar pathSplitter = QLatin1Char(';');
-#else
-static const QChar pathSplitter = QLatin1Char(':');
-#endif
-
-static inline QString languageLevelOption() { return QStringLiteral("language-level"); }
-static inline QString includePathOption() { return QStringLiteral("include-paths"); }
-static inline QString frameworkIncludePathOption() { return QStringLiteral("framework-include-paths"); }
-static inline QString systemIncludePathOption() { return QStringLiteral("system-include-paths"); }
-static inline QString typesystemPathOption() { return QStringLiteral("typesystem-paths"); }
-static inline QString helpOption() { return QStringLiteral("help"); }
-static inline QString diffOption() { return QStringLiteral("diff"); }
-static inline QString dryrunOption() { return QStringLiteral("dry-run"); }
-static inline QString skipDeprecatedOption() { return QStringLiteral("skip-deprecated"); }
-
-static const char helpHint[] = "Note: use --help or -h for more information.\n";
-
-using CommandArgumentMap = QMap<QString, QString>;
-
-using OptionDescriptions = Generator::OptionDescriptions;
-
-static void printOptions(QTextStream &s, const OptionDescriptions &options)
-{
- s.setFieldAlignment(QTextStream::AlignLeft);
- for (const auto &od : options) {
- if (!od.first.startsWith(QLatin1Char('-')))
- s << "--";
- s << od.first;
- if (od.second.isEmpty()) {
- s << ", ";
- } else {
- s << Qt::endl;
- const auto lines = od.second.splitRef(QLatin1Char('\n'));
- for (const auto &line : lines)
- s << " " << line << Qt::endl;
- s << Qt::endl;
- }
- }
-}
-
-static bool processProjectFile(QFile &projectFile, QMap<QString, QString> &args)
-{
- QByteArray line = projectFile.readLine().trimmed();
- if (line.isEmpty() || line != "[generator-project]")
- return false;
-
- QStringList includePaths;
- QStringList frameworkIncludePaths;
- QStringList systemIncludePaths;
- QStringList typesystemPaths;
- QStringList apiVersions;
- QString languageLevel;
-
- while (!projectFile.atEnd()) {
- line = projectFile.readLine().trimmed();
- if (line.isEmpty())
- continue;
-
- int split = line.indexOf('=');
- QByteArray key;
- QString value;
- if (split > 0) {
- key = line.left(split - 1).trimmed();
- value = QString::fromUtf8(line.mid(split + 1).trimmed());
- } else {
- key = line;
- }
-
- if (key == "include-path")
- includePaths << QDir::toNativeSeparators(value);
- else if (key == "framework-include-path")
- frameworkIncludePaths << QDir::toNativeSeparators(value);
- else if (key == "system-include-paths")
- systemIncludePaths << QDir::toNativeSeparators(value);
- else if (key == "typesystem-path")
- typesystemPaths << QDir::toNativeSeparators(value);
- else if (key == "language-level")
- languageLevel = value;
- else if (key == "api-version")
- apiVersions << value;
- else if (key == "header-file")
- args.insert(QLatin1String("arg-1"), value);
- else if (key == "typesystem-file")
- args.insert(QLatin1String("arg-2"), value);
- else
- args.insert(QString::fromUtf8(key), value);
- }
-
- if (!includePaths.isEmpty())
- args.insert(includePathOption(), includePaths.join(pathSplitter));
-
- if (!frameworkIncludePaths.isEmpty())
- args.insert(frameworkIncludePathOption(),
- frameworkIncludePaths.join(pathSplitter));
- if (!systemIncludePaths.isEmpty()) {
- args.insert(systemIncludePathOption(),
- systemIncludePaths.join(pathSplitter));
- }
-
- if (!typesystemPaths.isEmpty())
- args.insert(typesystemPathOption(), typesystemPaths.join(pathSplitter));
- if (!apiVersions.isEmpty())
- args.insert(QLatin1String("api-version"), apiVersions.join(QLatin1Char('|')));
- if (!languageLevel.isEmpty())
- args.insert(languageLevelOption(), languageLevel);
- return true;
-}
-
-static CommandArgumentMap getInitializedArguments()
-{
- CommandArgumentMap args;
- QStringList arguments = QCoreApplication::arguments();
- QString appName = arguments.constFirst();
- arguments.removeFirst();
-
- QString projectFileName;
- for (const QString &arg : qAsConst(arguments)) {
- if (arg.startsWith(QLatin1String("--project-file"))) {
- int split = arg.indexOf(QLatin1Char('='));
- if (split > 0)
- projectFileName = arg.mid(split + 1).trimmed();
- break;
- }
- }
-
- if (projectFileName.isEmpty())
- return args;
-
- if (!QFile::exists(projectFileName)) {
- std::cerr << qPrintable(appName) << ": Project file \"";
- std::cerr << qPrintable(projectFileName) << "\" not found.";
- std::cerr << std::endl;
- return args;
- }
-
- QFile projectFile(projectFileName);
- if (!projectFile.open(QIODevice::ReadOnly))
- return args;
-
- if (!processProjectFile(projectFile, args)) {
- std::cerr << qPrintable(appName) << ": first line of project file \"";
- std::cerr << qPrintable(projectFileName) << "\" must be the string \"[generator-project]\"";
- std::cerr << std::endl;
- return args;
- }
-
- return args;
-}
-
-// Concatenate values of path arguments that can occur multiple times on the
-// command line.
-static void addPathOptionValue(const QString &option, const QString &value,
- CommandArgumentMap &args)
-{
- const CommandArgumentMap::iterator it = args.find(option);
- if (it != args.end())
- it.value().append(pathSplitter + value);
- else
- args.insert(option, value);
-}
-
-static void getCommandLineArg(QString arg, int &argNum, QMap<QString, QString> &args)
-{
- if (arg.startsWith(QLatin1String("--"))) {
- arg.remove(0, 2);
- const int split = arg.indexOf(QLatin1Char('='));
- if (split < 0) {
- args.insert(arg, QString());
- return;
- }
- const QString option = arg.left(split);
- const QString value = arg.mid(split + 1).trimmed();
- if (option == includePathOption() || option == frameworkIncludePathOption()
- || option == systemIncludePathOption() || option == typesystemPathOption()) {
- addPathOptionValue(option, value, args);
- } else {
- args.insert(option, value);
- }
- return;
- }
- if (arg.startsWith(QLatin1Char('-'))) {
- arg.remove(0, 1);
- if (arg.startsWith(QLatin1Char('I'))) // Shorthand path arguments -I/usr/include...
- addPathOptionValue(includePathOption(), arg.mid(1), args);
- else if (arg.startsWith(QLatin1Char('F')))
- addPathOptionValue(frameworkIncludePathOption(), arg.mid(1), args);
- else if (arg.startsWith(QLatin1String("isystem")))
- addPathOptionValue(systemIncludePathOption(), arg.mid(7), args);
- else if (arg.startsWith(QLatin1Char('T')))
- addPathOptionValue(typesystemPathOption(), arg.mid(1), args);
- else if (arg == QLatin1String("h"))
- args.insert(helpOption(), QString());
- else if (arg.startsWith(QLatin1String("std=")))
- args.insert(languageLevelOption(), arg.mid(4));
- else
- args.insert(arg, QString());
- return;
- }
- argNum++;
- args.insert(QStringLiteral("arg-") + QString::number(argNum), arg);
-}
-
-static QMap<QString, QString> getCommandLineArgs()
-{
- QMap<QString, QString> args = getInitializedArguments();
- QStringList arguments = QCoreApplication::arguments();
- arguments.removeFirst();
-
- int argNum = 0;
- for (const QString &carg : qAsConst(arguments))
- getCommandLineArg(carg.trimmed(), argNum, args);
-
- return args;
-}
-
-static inline Generators docGenerators()
-{
- Generators result;
-#ifdef DOCSTRINGS_ENABLED
- result.append(GeneratorPtr(new QtDocGenerator));
-#endif
- return result;
-}
-
-static inline Generators shibokenGenerators()
-{
- Generators result;
- result << GeneratorPtr(new CppGenerator) << GeneratorPtr(new HeaderGenerator);
- return result;
-}
-
-static inline QString languageLevelDescription()
-{
- return QLatin1String("C++ Language level (c++11..c++17, default=")
- + QLatin1String(clang::languageLevelOption(clang::emulatedCompilerLanguageLevel()))
- + QLatin1Char(')');
-}
-
-void printUsage()
-{
- QTextStream s(stdout);
- s << "Usage:\n "
- << "shiboken [options] header-file typesystem-file\n\n"
- << "General options:\n";
- QString pathSyntax;
- QTextStream(&pathSyntax) << "<path>[" << pathSplitter << "<path>"
- << pathSplitter << "...]";
- OptionDescriptions generalOptions = OptionDescriptions()
- << qMakePair(QLatin1String("api-version=<\"package mask\">,<\"version\">"),
- QLatin1String("Specify the supported api version used to generate the bindings"))
- << qMakePair(QLatin1String("debug-level=[sparse|medium|full]"),
- QLatin1String("Set the debug level"))
- << qMakePair(QLatin1String("documentation-only"),
- QLatin1String("Do not generates any code, just the documentation"))
- << qMakePair(QLatin1String("drop-type-entries=\"<TypeEntry0>[;TypeEntry1;...]\""),
- QLatin1String("Semicolon separated list of type system entries (classes, namespaces,\n"
- "global functions and enums) to be dropped from generation."))
- << qMakePair(QLatin1String("-F<path>"), QString())
- << qMakePair(QLatin1String("framework-include-paths=") + pathSyntax,
- QLatin1String("Framework include paths used by the C++ parser"))
- << qMakePair(QLatin1String("-isystem<path>"), QString())
- << qMakePair(QLatin1String("system-include-paths=") + pathSyntax,
- QLatin1String("System include paths used by the C++ parser"))
- << qMakePair(QLatin1String("generator-set=<\"generator module\">"),
- QLatin1String("generator-set to be used. e.g. qtdoc"))
- << qMakePair(skipDeprecatedOption(),
- QLatin1String("Skip deprecated functions"))
- << qMakePair(diffOption(),
- QLatin1String("Print a diff of wrapper files"))
- << qMakePair(dryrunOption(),
- QLatin1String("Dry run, do not generate wrapper files"))
- << qMakePair(QLatin1String("-h"), QString())
- << qMakePair(helpOption(),
- QLatin1String("Display this help and exit"))
- << qMakePair(QLatin1String("-I<path>"), QString())
- << qMakePair(QLatin1String("include-paths=") + pathSyntax,
- QLatin1String("Include paths used by the C++ parser"))
- << qMakePair(languageLevelOption() + QLatin1String("=, -std=<level>"),
- languageLevelDescription())
- << qMakePair(QLatin1String("license-file=<license-file>"),
- QLatin1String("File used for copyright headers of generated files"))
- << qMakePair(QLatin1String("no-suppress-warnings"),
- QLatin1String("Show all warnings"))
- << qMakePair(QLatin1String("output-directory=<path>"),
- QLatin1String("The directory where the generated files will be written"))
- << qMakePair(QLatin1String("project-file=<file>"),
- QLatin1String("text file containing a description of the binding project.\n"
- "Replaces and overrides command line arguments"))
- << qMakePair(QLatin1String("silent"),
- QLatin1String("Avoid printing any message"))
- << qMakePair(QLatin1String("-T<path>"), QString())
- << qMakePair(QLatin1String("typesystem-paths=") + pathSyntax,
- QLatin1String("Paths used when searching for typesystems"))
- << qMakePair(QLatin1String("version"),
- QLatin1String("Output version information and exit"));
- printOptions(s, generalOptions);
-
- const Generators generators = shibokenGenerators() + docGenerators();
- for (const GeneratorPtr &generator : generators) {
- const OptionDescriptions options = generator->options();
- if (!options.isEmpty()) {
- s << Qt::endl << generator->name() << " options:\n\n";
- printOptions(s, generator->options());
- }
- }
-}
-
-static inline void printVerAndBanner()
-{
- std::cout << "shiboken v" SHIBOKEN_VERSION << std::endl;
- std::cout << "Copyright (C) 2016 The Qt Company Ltd." << std::endl;
-}
-
-static inline void errorPrint(const QString &s)
-{
- QStringList arguments = QCoreApplication::arguments();
- arguments.pop_front();
- std::cerr << "shiboken: " << qPrintable(s)
- << "\nCommand line: " << qPrintable(arguments.join(QLatin1Char(' '))) << '\n';
-}
-
-static void parseIncludePathOption(const QString &option, HeaderType headerType,
- CommandArgumentMap &args,
- ApiExtractor &extractor)
-{
- const CommandArgumentMap::iterator it = args.find(option);
- if (it != args.end()) {
- const QStringList includePathListList =
- it.value().split(pathSplitter, Qt::SkipEmptyParts);
- args.erase(it);
- for (const QString &s : includePathListList) {
- auto path = QFile::encodeName(QDir::cleanPath(s));
- extractor.addIncludePath(HeaderPath{path, headerType});
- }
- }
-}
-
-int main(int argc, char *argv[])
-{
- // PYSIDE-757: Request a deterministic ordering of QHash in the code model
- // and type system.
- qSetGlobalQHashSeed(0);
- // needed by qxmlpatterns
- QCoreApplication app(argc, argv);
- ReportHandler::install();
- if (ReportHandler::isDebug(ReportHandler::SparseDebug))
- qCInfo(lcShiboken()).noquote().nospace() << QCoreApplication::arguments().join(QLatin1Char(' '));
-
- // Store command arguments in a map
- CommandArgumentMap args = getCommandLineArgs();
- Generators generators;
-
- CommandArgumentMap::iterator ait = args.find(QLatin1String("version"));
- if (ait != args.end()) {
- args.erase(ait);
- printVerAndBanner();
- return EXIT_SUCCESS;
- }
-
- QString generatorSet;
- ait = args.find(QLatin1String("generator-set"));
- if (ait == args.end()) // Also check QLatin1String("generatorSet") command line argument for backward compatibility.
- ait = args.find(QLatin1String("generatorSet"));
- if (ait != args.end()) {
- generatorSet = ait.value();
- args.erase(ait);
- }
-
- // Pre-defined generator sets.
- if (generatorSet == QLatin1String("qtdoc")) {
- generators = docGenerators();
- if (generators.isEmpty()) {
- errorPrint(QLatin1String("Doc strings extractions was not enabled in this shiboken build."));
- return EXIT_FAILURE;
- }
- } else if (generatorSet.isEmpty() || generatorSet == QLatin1String("shiboken")) {
- generators = shibokenGenerators();
- } else {
- errorPrint(QLatin1String("Unknown generator set, try \"shiboken\" or \"qtdoc\"."));
- return EXIT_FAILURE;
- }
-
- ait = args.find(QLatin1String("help"));
- if (ait != args.end()) {
- args.erase(ait);
- printUsage();
- return EXIT_SUCCESS;
- }
-
- ait = args.find(diffOption());
- if (ait != args.end()) {
- args.erase(ait);
- FileOut::diff = true;
- }
-
- ait = args.find(dryrunOption());
- if (ait != args.end()) {
- args.erase(ait);
- FileOut::dummy = true;
- }
-
- QString licenseComment;
- ait = args.find(QLatin1String("license-file"));
- if (ait != args.end()) {
- QFile licenseFile(ait.value());
- args.erase(ait);
- if (licenseFile.open(QIODevice::ReadOnly)) {
- licenseComment = QString::fromUtf8(licenseFile.readAll());
- } else {
- errorPrint(QStringLiteral("Could not open the file \"%1\" containing the license heading: %2").
- arg(QDir::toNativeSeparators(licenseFile.fileName()), licenseFile.errorString()));
- return EXIT_FAILURE;
- }
- }
-
- QString outputDirectory = QLatin1String("out");
- ait = args.find(QLatin1String("output-directory"));
- if (ait != args.end()) {
- outputDirectory = ait.value();
- args.erase(ait);
- }
-
- if (!QDir(outputDirectory).exists()) {
- if (!QDir().mkpath(outputDirectory)) {
- qCWarning(lcShiboken).noquote().nospace()
- << "Can't create output directory: " << QDir::toNativeSeparators(outputDirectory);
- return EXIT_FAILURE;
- }
- }
-
- // Create and set-up API Extractor
- ApiExtractor extractor;
- extractor.setLogDirectory(outputDirectory);
- ait = args.find(skipDeprecatedOption());
- if (ait != args.end()) {
- extractor.setSkipDeprecated(true);
- args.erase(ait);
- }
-
- ait = args.find(QLatin1String("silent"));
- if (ait != args.end()) {
- extractor.setSilent(true);
- args.erase(ait);
- } else {
- ait = args.find(QLatin1String("debug-level"));
- if (ait != args.end()) {
- if (!ReportHandler::setDebugLevelFromArg(ait.value())) {
- errorPrint(QLatin1String("Invalid debug level: ") + ait.value());
- return EXIT_FAILURE;
- }
- args.erase(ait);
- }
- }
- ait = args.find(QLatin1String("no-suppress-warnings"));
- if (ait != args.end()) {
- args.erase(ait);
- extractor.setSuppressWarnings(false);
- }
- ait = args.find(QLatin1String("api-version"));
- if (ait != args.end()) {
- const QStringList &versions = ait.value().split(QLatin1Char('|'));
- args.erase(ait);
- for (const QString &fullVersion : versions) {
- QStringList parts = fullVersion.split(QLatin1Char(','));
- QString package;
- QString version;
- package = parts.count() == 1 ? QLatin1String("*") : parts.constFirst();
- version = parts.constLast();
- if (!extractor.setApiVersion(package, version)) {
- errorPrint(msgInvalidVersion(package, version));
- return EXIT_FAILURE;
- }
- }
- }
-
- ait = args.find(QLatin1String("drop-type-entries"));
- if (ait != args.end()) {
- extractor.setDropTypeEntries(ait.value());
- args.erase(ait);
- }
-
- ait = args.find(QLatin1String("typesystem-paths"));
- if (ait != args.end()) {
- extractor.addTypesystemSearchPath(ait.value().split(pathSplitter));
- args.erase(ait);
- }
-
- parseIncludePathOption(includePathOption(), HeaderType::Standard,
- args, extractor);
- parseIncludePathOption(frameworkIncludePathOption(), HeaderType::Framework,
- args, extractor);
- parseIncludePathOption(systemIncludePathOption(), HeaderType::System,
- args, extractor);
-
- ait = args.find(QLatin1String("arg-1"));
- if (ait == args.end()) {
- errorPrint(QLatin1String("Required argument header-file is missing."));
- return EXIT_FAILURE;
- }
- const QString cppFileName = ait.value();
- args.erase(ait);
- const QFileInfo cppFileNameFi(cppFileName);
- if (!cppFileNameFi.isFile() && !cppFileNameFi.isSymLink()) {
- errorPrint(QLatin1Char('"') + cppFileName + QLatin1String("\" does not exist."));
- return EXIT_FAILURE;
- }
-
- ait = args.find(QLatin1String("arg-2"));
- if (ait == args.end()) {
- errorPrint(QLatin1String("Required argument typesystem-file is missing."));
- return EXIT_FAILURE;
- }
- const QString typeSystemFileName = ait.value();
- args.erase(ait);
- QString messagePrefix = QFileInfo(typeSystemFileName).baseName();
- if (messagePrefix.startsWith(QLatin1String("typesystem_")))
- messagePrefix.remove(0, 11);
- ReportHandler::setPrefix(QLatin1Char('(') + messagePrefix + QLatin1Char(')'));
-
- // Pass option to all generators (Cpp/Header generator have the same options)
- for (ait = args.begin(); ait != args.end(); ) {
- bool found = false;
- for (const GeneratorPtr &generator : qAsConst(generators))
- found |= generator->handleOption(ait.key(), ait.value());
- if (found)
- ait = args.erase(ait);
- else
- ++ait;
- }
-
- ait = args.find(languageLevelOption());
- if (ait != args.end()) {
- const QByteArray languageLevelBA = ait.value().toLatin1();
- args.erase(ait);
- const LanguageLevel level = clang::languageLevelFromOption(languageLevelBA.constData());
- if (level == LanguageLevel::Default) {
- std::cout << "Invalid argument for language level: \""
- << languageLevelBA.constData() << "\"\n" << helpHint;
- return EXIT_FAILURE;
- }
- extractor.setLanguageLevel(level);
- }
-
- /* Make sure to remove the project file's arguments (if any) and
- * --project-file, also the arguments of each generator before
- * checking if there isn't any existing arguments in argsHandler.
- */
- args.remove(QLatin1String("project-file"));
- CommandArgumentMap projectFileArgs = getInitializedArguments();
- for (auto it = projectFileArgs.cbegin(), end = projectFileArgs.cend(); it != end; ++it)
- args.remove(it.key());
-
- if (!args.isEmpty()) {
- errorPrint(msgLeftOverArguments(args));
- std::cout << helpHint;
- return EXIT_FAILURE;
- }
-
- if (typeSystemFileName.isEmpty()) {
- std::cout << "You must specify a Type System file." << std::endl << helpHint;
- return EXIT_FAILURE;
- }
-
- extractor.setCppFileName(cppFileNameFi.absoluteFilePath());
- extractor.setTypeSystem(typeSystemFileName);
-
- if (!extractor.run()) {
- errorPrint(QLatin1String("Error running ApiExtractor."));
- return EXIT_FAILURE;
- }
-
- if (!extractor.classCount())
- qCWarning(lcShiboken) << "No C++ classes found!";
-
- if (ReportHandler::isDebug(ReportHandler::FullDebug)
- || qEnvironmentVariableIsSet("SHIBOKEN_DUMP_CODEMODEL")) {
- qCInfo(lcShiboken) << "API Extractor:\n" << extractor
- << "\n\nType datase:\n" << *TypeDatabase::instance();
- }
-
- for (const GeneratorPtr &g : qAsConst(generators)) {
- g->setOutputDirectory(outputDirectory);
- g->setLicenseComment(licenseComment);
- ReportHandler::startProgress(QByteArray("Running ") + g->name() + "...");
- const bool ok = g->setup(extractor) && g->generate();
- ReportHandler::endProgress();
- if (!ok) {
- errorPrint(QLatin1String("Error running generator: ")
- + QLatin1String(g->name()) + QLatin1Char('.'));
- return EXIT_FAILURE;
- }
- }
-
- const QByteArray doneMessage = ReportHandler::doneMessage();
- std::cout << doneMessage.constData() << std::endl;
-
- return EXIT_SUCCESS;
-}
diff --git a/sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp b/sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp
deleted file mode 100644
index 014cc948e..000000000
--- a/sources/shiboken2/generator/qtdoc/qtdocgenerator.cpp
+++ /dev/null
@@ -1,2408 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtdocgenerator.h"
-#include <abstractmetalang.h>
-#include <messages.h>
-#include <reporthandler.h>
-#include <typesystem.h>
-#include <qtdocparser.h>
-#include <doxygenparser.h>
-#include <typedatabase.h>
-#include <algorithm>
-#include <QtCore/QStack>
-#include <QtCore/QRegularExpression>
-#include <QtCore/QTextStream>
-#include <QtCore/QXmlStreamReader>
-#include <QtCore/QFile>
-#include <QtCore/QDir>
-#include <fileout.h>
-#include <limits>
-
-static Indentor INDENT;
-
-static inline QString additionalDocumentationOption() { return QStringLiteral("additional-documentation"); }
-
-static inline QString nameAttribute() { return QStringLiteral("name"); }
-static inline QString titleAttribute() { return QStringLiteral("title"); }
-static inline QString fullTitleAttribute() { return QStringLiteral("fulltitle"); }
-static inline QString briefAttribute() { return QStringLiteral("brief"); }
-static inline QString briefStartElement() { return QStringLiteral("<brief>"); }
-static inline QString briefEndElement() { return QStringLiteral("</brief>"); }
-
-static inline QString none() { return QStringLiteral("None"); }
-
-static void stripPythonQualifiers(QString *s)
-{
- const int lastSep = s->lastIndexOf(QLatin1Char('.'));
- if (lastSep != -1)
- s->remove(0, lastSep + 1);
-}
-
-static bool shouldSkip(const AbstractMetaFunction* func)
-{
- // Constructors go to separate section
- if (DocParser::skipForQuery(func) || func->isConstructor())
- return true;
-
- // Search a const clone (QImage::bits() vs QImage::bits() const)
- if (func->isConstant())
- return false;
-
- const AbstractMetaArgumentList funcArgs = func->arguments();
- const AbstractMetaFunctionList &ownerFunctions = func->ownerClass()->functions();
- for (AbstractMetaFunction *f : ownerFunctions) {
- if (f != func
- && f->isConstant()
- && f->name() == func->name()
- && f->arguments().count() == funcArgs.count()) {
- // Compare each argument
- bool cloneFound = true;
-
- const AbstractMetaArgumentList fargs = f->arguments();
- for (int i = 0, max = funcArgs.count(); i < max; ++i) {
- if (funcArgs.at(i)->type()->typeEntry() != fargs.at(i)->type()->typeEntry()) {
- cloneFound = false;
- break;
- }
- }
- if (cloneFound)
- return true;
- }
- }
- return false;
-}
-
-static bool functionSort(const AbstractMetaFunction* func1, const AbstractMetaFunction* func2)
-{
- return func1->name() < func2->name();
-}
-
-class Pad
-{
-public:
- explicit Pad(char c, int count) : m_char(c), m_count(count) {}
-
- void write(QTextStream &str) const
- {
- for (int i = 0; i < m_count; ++i)
- str << m_char;
- }
-
-private:
- const char m_char;
- const int m_count;
-};
-
-inline QTextStream &operator<<(QTextStream &str, const Pad &pad)
-{
- pad.write(str);
- return str;
-}
-
-template <class String>
-static int writeEscapedRstText(QTextStream &str, const String &s)
-{
- int escaped = 0;
- for (const QChar &c : s) {
- switch (c.unicode()) {
- case '*':
- case '`':
- case '_':
- case '\\':
- str << '\\';
- ++escaped;
- break;
- }
- str << c;
- }
- return s.size() + escaped;
-}
-
-class escape
-{
-public:
- explicit escape(const QStringRef &s) : m_string(s) {}
-
- void write(QTextStream &str) const { writeEscapedRstText(str, m_string); }
-
-private:
- const QStringRef m_string;
-};
-
-inline QTextStream &operator<<(QTextStream &str, const escape &e)
-{
- e.write(str);
- return str;
-}
-
-// Return last character of a QString-buffered stream.
-static QChar lastChar(const QTextStream &str)
-{
- const QString *string = str.string();
- Q_ASSERT(string);
- return string->isEmpty() ? QChar() : *(string->crbegin());
-}
-
-static QTextStream &ensureEndl(QTextStream &s)
-{
- if (lastChar(s) != QLatin1Char('\n'))
- s << Qt::endl;
- return s;
-}
-
-static inline QVersionNumber versionOf(const TypeEntry *te)
-{
- if (te) {
- const auto version = te->version();
- if (!version.isNull() && version > QVersionNumber(0, 0))
- return version;
- }
- return QVersionNumber();
-}
-
-struct rstVersionAdded
-{
- explicit rstVersionAdded(const QVersionNumber &v) : m_version(v) {}
-
- const QVersionNumber m_version;
-};
-
-static QTextStream &operator<<(QTextStream &s, const rstVersionAdded &v)
-{
- s << ".. versionadded:: "<< v.m_version.toString() << "\n\n";
- return s;
-}
-
-static QByteArray rstDeprecationNote(const char *what)
-{
- return QByteArrayLiteral(".. note:: This ")
- + what + QByteArrayLiteral(" is deprecated.\n\n");
-}
-
-// RST anchor string: Anything else but letters, numbers, '_' or '.' replaced by '-'
-static inline bool isValidRstLabelChar(QChar c)
-{
- return c.isLetterOrNumber() || c == QLatin1Char('_') || c == QLatin1Char('.');
-}
-
-static QString toRstLabel(QString s)
-{
- for (int i = 0, size = s.size(); i < size; ++i) {
- if (!isValidRstLabelChar(s.at(i)))
- s[i] = QLatin1Char('-');
- }
- return s;
-}
-
-class rstLabel
-{
-public:
- explicit rstLabel(const QString &l) : m_label(l) {}
-
- friend QTextStream &operator<<(QTextStream &str, const rstLabel &a)
- {
- str << ".. _" << toRstLabel(a.m_label) << ":\n\n";
- return str;
- }
-
-private:
- const QString &m_label;
-};
-
-struct QtXmlToSphinx::LinkContext
-{
- enum Type
- {
- Method = 0x1, Function = 0x2,
- FunctionMask = Method | Function,
- Class = 0x4, Attribute = 0x8, Module = 0x10,
- Reference = 0x20, External= 0x40
- };
-
- enum Flags { InsideBold = 0x1, InsideItalic = 0x2 };
-
- explicit LinkContext(const QString &ref) : linkRef(ref) {}
-
- QString linkRef;
- QString linkText;
- Type type = Reference;
- int flags = 0;
-};
-
-static const char *linkKeyWord(QtXmlToSphinx::LinkContext::Type type)
-{
- switch (type) {
- case QtXmlToSphinx::LinkContext::Method:
- return ":meth:";
- case QtXmlToSphinx::LinkContext::Function:
- return ":func:";
- case QtXmlToSphinx::LinkContext::Class:
- return ":class:";
- case QtXmlToSphinx::LinkContext::Attribute:
- return ":attr:";
- case QtXmlToSphinx::LinkContext::Module:
- return ":mod:";
- case QtXmlToSphinx::LinkContext::Reference:
- return ":ref:";
- case QtXmlToSphinx::LinkContext::External:
- break;
- case QtXmlToSphinx::LinkContext::FunctionMask:
- break;
- }
- return "";
-}
-
-QTextStream &operator<<(QTextStream &str, const QtXmlToSphinx::LinkContext &linkContext)
-{
- // Temporarily turn off bold/italic since links do not work within
- if (linkContext.flags & QtXmlToSphinx::LinkContext::InsideBold)
- str << "**";
- else if (linkContext.flags & QtXmlToSphinx::LinkContext::InsideItalic)
- str << '*';
- str << ' ' << linkKeyWord(linkContext.type) << '`';
- const bool isExternal = linkContext.type == QtXmlToSphinx::LinkContext::External;
- if (!linkContext.linkText.isEmpty()) {
- writeEscapedRstText(str, linkContext.linkText);
- if (isExternal && !linkContext.linkText.endsWith(QLatin1Char(' ')))
- str << ' ';
- str << '<';
- }
- // Convert page titles to RST labels
- str << (linkContext.type == QtXmlToSphinx::LinkContext::Reference
- ? toRstLabel(linkContext.linkRef) : linkContext.linkRef);
- if (!linkContext.linkText.isEmpty())
- str << '>';
- str << '`';
- if (isExternal)
- str << '_';
- str << ' ';
- if (linkContext.flags & QtXmlToSphinx::LinkContext::InsideBold)
- str << "**";
- else if (linkContext.flags & QtXmlToSphinx::LinkContext::InsideItalic)
- str << '*';
- return str;
-}
-
-QtXmlToSphinx::QtXmlToSphinx(QtDocGenerator* generator, const QString& doc, const QString& context)
- : m_tableHasHeader(false), m_context(context), m_generator(generator), m_insideBold(false), m_insideItalic(false)
-{
- m_handlerMap.insert(QLatin1String("heading"), &QtXmlToSphinx::handleHeadingTag);
- m_handlerMap.insert(QLatin1String("brief"), &QtXmlToSphinx::handleParaTag);
- m_handlerMap.insert(QLatin1String("para"), &QtXmlToSphinx::handleParaTag);
- m_handlerMap.insert(QLatin1String("italic"), &QtXmlToSphinx::handleItalicTag);
- m_handlerMap.insert(QLatin1String("bold"), &QtXmlToSphinx::handleBoldTag);
- m_handlerMap.insert(QLatin1String("see-also"), &QtXmlToSphinx::handleSeeAlsoTag);
- m_handlerMap.insert(QLatin1String("snippet"), &QtXmlToSphinx::handleSnippetTag);
- m_handlerMap.insert(QLatin1String("dots"), &QtXmlToSphinx::handleDotsTag);
- m_handlerMap.insert(QLatin1String("codeline"), &QtXmlToSphinx::handleDotsTag);
- m_handlerMap.insert(QLatin1String("table"), &QtXmlToSphinx::handleTableTag);
- m_handlerMap.insert(QLatin1String("header"), &QtXmlToSphinx::handleRowTag);
- m_handlerMap.insert(QLatin1String("row"), &QtXmlToSphinx::handleRowTag);
- m_handlerMap.insert(QLatin1String("item"), &QtXmlToSphinx::handleItemTag);
- m_handlerMap.insert(QLatin1String("argument"), &QtXmlToSphinx::handleArgumentTag);
- m_handlerMap.insert(QLatin1String("teletype"), &QtXmlToSphinx::handleArgumentTag);
- m_handlerMap.insert(QLatin1String("link"), &QtXmlToSphinx::handleLinkTag);
- m_handlerMap.insert(QLatin1String("inlineimage"), &QtXmlToSphinx::handleInlineImageTag);
- m_handlerMap.insert(QLatin1String("image"), &QtXmlToSphinx::handleImageTag);
- m_handlerMap.insert(QLatin1String("list"), &QtXmlToSphinx::handleListTag);
- m_handlerMap.insert(QLatin1String("term"), &QtXmlToSphinx::handleTermTag);
- m_handlerMap.insert(QLatin1String("raw"), &QtXmlToSphinx::handleRawTag);
- m_handlerMap.insert(QLatin1String("underline"), &QtXmlToSphinx::handleItalicTag);
- m_handlerMap.insert(QLatin1String("superscript"), &QtXmlToSphinx::handleSuperScriptTag);
- m_handlerMap.insert(QLatin1String("code"), &QtXmlToSphinx::handleCodeTag);
- m_handlerMap.insert(QLatin1String("badcode"), &QtXmlToSphinx::handleCodeTag);
- m_handlerMap.insert(QLatin1String("legalese"), &QtXmlToSphinx::handleCodeTag);
- m_handlerMap.insert(QLatin1String("rst"), &QtXmlToSphinx::handleRstPassTroughTag);
- m_handlerMap.insert(QLatin1String("section"), &QtXmlToSphinx::handleAnchorTag);
- m_handlerMap.insert(QLatin1String("quotefile"), &QtXmlToSphinx::handleQuoteFileTag);
-
- // ignored tags
- m_handlerMap.insert(QLatin1String("generatedlist"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("tableofcontents"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("quotefromfile"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("skipto"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("target"), &QtXmlToSphinx::handleTargetTag);
- m_handlerMap.insert(QLatin1String("page"), &QtXmlToSphinx::handlePageTag);
- m_handlerMap.insert(QLatin1String("group"), &QtXmlToSphinx::handlePageTag);
-
- // useless tags
- m_handlerMap.insert(QLatin1String("description"), &QtXmlToSphinx::handleUselessTag);
- m_handlerMap.insert(QLatin1String("definition"), &QtXmlToSphinx::handleUselessTag);
- m_handlerMap.insert(QLatin1String("printuntil"), &QtXmlToSphinx::handleUselessTag);
- m_handlerMap.insert(QLatin1String("relation"), &QtXmlToSphinx::handleUselessTag);
-
- // Doxygen tags
- m_handlerMap.insert(QLatin1String("title"), &QtXmlToSphinx::handleHeadingTag);
- m_handlerMap.insert(QLatin1String("ref"), &QtXmlToSphinx::handleParaTag);
- m_handlerMap.insert(QLatin1String("computeroutput"), &QtXmlToSphinx::handleParaTag);
- m_handlerMap.insert(QLatin1String("detaileddescription"), &QtXmlToSphinx::handleParaTag);
- m_handlerMap.insert(QLatin1String("name"), &QtXmlToSphinx::handleParaTag);
- m_handlerMap.insert(QLatin1String("listitem"), &QtXmlToSphinx::handleItemTag);
- m_handlerMap.insert(QLatin1String("parametername"), &QtXmlToSphinx::handleItemTag);
- m_handlerMap.insert(QLatin1String("parameteritem"), &QtXmlToSphinx::handleItemTag);
- m_handlerMap.insert(QLatin1String("ulink"), &QtXmlToSphinx::handleLinkTag);
- m_handlerMap.insert(QLatin1String("itemizedlist"), &QtXmlToSphinx::handleListTag);
- m_handlerMap.insert(QLatin1String("parameternamelist"), &QtXmlToSphinx::handleListTag);
- m_handlerMap.insert(QLatin1String("parameterlist"), &QtXmlToSphinx::handleListTag);
-
- // Doxygen ignored tags
- m_handlerMap.insert(QLatin1String("highlight"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("linebreak"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("programlisting"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("xreftitle"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("sp"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("entry"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("simplesect"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("verbatim"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("xrefsect"), &QtXmlToSphinx::handleIgnoredTag);
- m_handlerMap.insert(QLatin1String("xrefdescription"), &QtXmlToSphinx::handleIgnoredTag);
-
- m_result = transform(doc);
-}
-
-void QtXmlToSphinx::pushOutputBuffer()
-{
- auto *buffer = new QString();
- m_buffers << buffer;
- m_output.setString(buffer);
-}
-
-QString QtXmlToSphinx::popOutputBuffer()
-{
- Q_ASSERT(!m_buffers.isEmpty());
- QString* str = m_buffers.pop();
- QString strcpy(*str);
- delete str;
- m_output.setString(m_buffers.isEmpty() ? 0 : m_buffers.top());
- return strcpy;
-}
-
-QString QtXmlToSphinx::expandFunction(const QString& function) const
-{
- const int firstDot = function.indexOf(QLatin1Char('.'));
- const AbstractMetaClass *metaClass = nullptr;
- if (firstDot != -1) {
- const QStringRef className = function.leftRef(firstDot);
- const AbstractMetaClassList &classes = m_generator->classes();
- for (const AbstractMetaClass *cls : classes) {
- if (cls->name() == className) {
- metaClass = cls;
- break;
- }
- }
- }
-
- return metaClass
- ? metaClass->typeEntry()->qualifiedTargetLangName()
- + function.right(function.size() - firstDot)
- : function;
-}
-
-QString QtXmlToSphinx::resolveContextForMethod(const QString& methodName) const
-{
- const QStringRef currentClass = m_context.splitRef(QLatin1Char('.')).constLast();
-
- const AbstractMetaClass *metaClass = nullptr;
- const AbstractMetaClassList &classes = m_generator->classes();
- for (const AbstractMetaClass *cls : classes) {
- if (cls->name() == currentClass) {
- metaClass = cls;
- break;
- }
- }
-
- if (metaClass) {
- AbstractMetaFunctionList funcList;
- const AbstractMetaFunctionList &methods = metaClass->queryFunctionsByName(methodName);
- for (AbstractMetaFunction *func : methods) {
- if (methodName == func->name())
- funcList.append(func);
- }
-
- const AbstractMetaClass *implementingClass = nullptr;
- for (AbstractMetaFunction *func : qAsConst(funcList)) {
- implementingClass = func->implementingClass();
- if (implementingClass->name() == currentClass)
- break;
- }
-
- if (implementingClass)
- return implementingClass->typeEntry()->qualifiedTargetLangName();
- }
-
- return QLatin1Char('~') + m_context;
-}
-
-QString QtXmlToSphinx::transform(const QString& doc)
-{
- Q_ASSERT(m_buffers.isEmpty());
- Indentation indentation(INDENT);
- if (doc.trimmed().isEmpty())
- return doc;
-
- pushOutputBuffer();
-
- QXmlStreamReader reader(doc);
-
- while (!reader.atEnd()) {
- QXmlStreamReader::TokenType token = reader.readNext();
- if (reader.hasError()) {
- QString message;
- QTextStream(&message) << "XML Error "
- << reader.errorString() << " at " << reader.lineNumber()
- << ':' << reader.columnNumber() << '\n' << doc;
- m_output << INDENT << message;
- qCWarning(lcShibokenDoc).noquote().nospace() << message;
- break;
- }
-
- if (token == QXmlStreamReader::StartElement) {
- QStringRef tagName = reader.name();
- TagHandler handler = m_handlerMap.value(tagName.toString(), &QtXmlToSphinx::handleUnknownTag);
- if (!m_handlers.isEmpty() && ( (m_handlers.top() == &QtXmlToSphinx::handleIgnoredTag) ||
- (m_handlers.top() == &QtXmlToSphinx::handleRawTag)) )
- handler = &QtXmlToSphinx::handleIgnoredTag;
-
- m_handlers.push(handler);
- }
- if (!m_handlers.isEmpty())
- (this->*(m_handlers.top()))(reader);
-
- if (token == QXmlStreamReader::EndElement) {
- m_handlers.pop();
- m_lastTagName = reader.name().toString();
- }
- }
-
- if (!m_inlineImages.isEmpty()) {
- // Write out inline image definitions stored in handleInlineImageTag().
- m_output << Qt::endl;
- for (const InlineImage &img : qAsConst(m_inlineImages))
- m_output << ".. |" << img.tag << "| image:: " << img.href << Qt::endl;
- m_output << Qt::endl;
- m_inlineImages.clear();
- }
-
- m_output.flush();
- QString retval = popOutputBuffer();
- Q_ASSERT(m_buffers.isEmpty());
- return retval;
-}
-
-static QString resolveFile(const QStringList &locations, const QString &path)
-{
- for (QString location : locations) {
- location.append(QLatin1Char('/'));
- location.append(path);
- if (QFileInfo::exists(location))
- return location;
- }
- return QString();
-}
-
-QString QtXmlToSphinx::readFromLocations(const QStringList &locations, const QString &path,
- const QString &identifier, QString *errorMessage)
-{
- QString resolvedPath;
- if (path.endsWith(QLatin1String(".cpp"))) {
- const QString pySnippet = path.left(path.size() - 3) + QLatin1String("py");
- resolvedPath = resolveFile(locations, pySnippet);
- }
- if (resolvedPath.isEmpty())
- resolvedPath = resolveFile(locations, path);
- if (resolvedPath.isEmpty()) {
- QTextStream(errorMessage) << "Could not resolve \"" << path << "\" in \""
- << locations.join(QLatin1String("\", \""));
- return QString(); // null
- }
- qCDebug(lcShibokenDoc).noquote().nospace() << "snippet file " << path
- << " [" << identifier << ']' << " resolved to " << resolvedPath;
- return readFromLocation(resolvedPath, identifier, errorMessage);
-}
-
-QString QtXmlToSphinx::readFromLocation(const QString &location, const QString &identifier,
- QString *errorMessage)
-{
- QFile inputFile;
- inputFile.setFileName(location);
- if (!inputFile.open(QIODevice::ReadOnly)) {
- QTextStream(errorMessage) << "Could not read code snippet file: "
- << QDir::toNativeSeparators(inputFile.fileName())
- << ": " << inputFile.errorString();
- return QString(); // null
- }
-
- QString code = QLatin1String(""); // non-null
- if (identifier.isEmpty()) {
- while (!inputFile.atEnd())
- code += QString::fromUtf8(inputFile.readLine());
- return code;
- }
-
- const QRegularExpression searchString(QLatin1String("//!\\s*\\[")
- + identifier + QLatin1String("\\]"));
- Q_ASSERT(searchString.isValid());
- static const QRegularExpression codeSnippetCode(QLatin1String("//!\\s*\\[[\\w\\d\\s]+\\]"));
- Q_ASSERT(codeSnippetCode.isValid());
-
- bool getCode = false;
-
- while (!inputFile.atEnd()) {
- QString line = QString::fromUtf8(inputFile.readLine());
- if (getCode && !line.contains(searchString)) {
- line.remove(codeSnippetCode);
- code += line;
- } else if (line.contains(searchString)) {
- if (getCode)
- break;
- getCode = true;
- }
- }
-
- if (!getCode) {
- QTextStream(errorMessage) << "Code snippet file found ("
- << QDir::toNativeSeparators(location) << "), but snippet ["
- << identifier << "] not found.";
- return QString(); // null
- }
-
- return code;
-}
-
-void QtXmlToSphinx::handleHeadingTag(QXmlStreamReader& reader)
-{
- static int headingSize = 0;
- static char type;
- static char types[] = { '-', '^' };
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- uint typeIdx = reader.attributes().value(QLatin1String("level")).toUInt();
- if (typeIdx >= sizeof(types))
- type = types[sizeof(types)-1];
- else
- type = types[typeIdx];
- } else if (token == QXmlStreamReader::EndElement) {
- m_output << Pad(type, headingSize) << Qt::endl << Qt::endl;
- } else if (token == QXmlStreamReader::Characters) {
- m_output << Qt::endl << Qt::endl;
- headingSize = writeEscapedRstText(m_output, reader.text().trimmed());
- m_output << Qt::endl;
- }
-}
-
-void QtXmlToSphinx::handleParaTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- pushOutputBuffer();
- } else if (token == QXmlStreamReader::EndElement) {
- QString result = popOutputBuffer().simplified();
- if (result.startsWith(QLatin1String("**Warning:**")))
- result.replace(0, 12, QLatin1String(".. warning:: "));
- else if (result.startsWith(QLatin1String("**Note:**")))
- result.replace(0, 9, QLatin1String(".. note:: "));
-
- m_output << INDENT << result << Qt::endl << Qt::endl;
- } else if (token == QXmlStreamReader::Characters) {
- const QStringRef text = reader.text();
- const QChar end = lastChar(m_output);
- if (!text.isEmpty() && INDENT.indent == 0 && !end.isNull()) {
- QChar start = text[0];
- if ((end == QLatin1Char('*') || end == QLatin1Char('`')) && start != QLatin1Char(' ') && !start.isPunct())
- m_output << '\\';
- }
- m_output << INDENT << escape(text);
- }
-}
-
-void QtXmlToSphinx::handleItalicTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement || token == QXmlStreamReader::EndElement) {
- m_insideItalic = !m_insideItalic;
- m_output << '*';
- } else if (token == QXmlStreamReader::Characters) {
- m_output << escape(reader.text().trimmed());
- }
-}
-
-void QtXmlToSphinx::handleBoldTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement || token == QXmlStreamReader::EndElement) {
- m_insideBold = !m_insideBold;
- m_output << "**";
- } else if (token == QXmlStreamReader::Characters) {
- m_output << escape(reader.text().trimmed());
- }
-}
-
-void QtXmlToSphinx::handleArgumentTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement || token == QXmlStreamReader::EndElement)
- m_output << "``";
- else if (token == QXmlStreamReader::Characters)
- m_output << reader.text().trimmed();
-}
-
-static inline QString functionLinkType() { return QStringLiteral("function"); }
-static inline QString classLinkType() { return QStringLiteral("class"); }
-
-static inline QString fixLinkType(const QStringRef &type)
-{
- // TODO: create a flag PROPERTY-AS-FUNCTION to ask if the properties
- // are recognized as such or not in the binding
- if (type == QLatin1String("property"))
- return functionLinkType();
- if (type == QLatin1String("typedef"))
- return classLinkType();
- return type.toString();
-}
-
-static inline QString linkSourceAttribute(const QString &type)
-{
- if (type == functionLinkType() || type == classLinkType())
- return QLatin1String("raw");
- return type == QLatin1String("enum") || type == QLatin1String("page")
- ? type : QLatin1String("href");
-}
-
-// "See also" links may appear as nested links:
-// <see-also>QAbstractXmlReceiver<link raw="isValid()" href="qxmlquery.html#isValid" type="function">isValid()</link>
-// which is handled in handleLinkTag
-// or direct text:
-// <see-also>rootIsDecorated()</see-also>
-// which is handled here.
-
-void QtXmlToSphinx::handleSeeAlsoTag(QXmlStreamReader& reader)
-{
- switch (reader.tokenType()) {
- case QXmlStreamReader::StartElement:
- m_output << INDENT << ".. seealso:: ";
- break;
- case QXmlStreamReader::Characters: {
- // Direct embedded link: <see-also>rootIsDecorated()</see-also>
- const QStringRef textR = reader.text().trimmed();
- if (!textR.isEmpty()) {
- const QString text = textR.toString();
- if (m_seeAlsoContext.isNull()) {
- const QString type = text.endsWith(QLatin1String("()"))
- ? functionLinkType() : classLinkType();
- m_seeAlsoContext.reset(handleLinkStart(type, text));
- }
- handleLinkText(m_seeAlsoContext.data(), text);
- }
- }
- break;
- case QXmlStreamReader::EndElement:
- if (!m_seeAlsoContext.isNull()) { // direct, no nested </link> seen
- handleLinkEnd(m_seeAlsoContext.data());
- m_seeAlsoContext.reset();
- }
- m_output << Qt::endl << Qt::endl;
- break;
- default:
- break;
- }
-}
-
-static inline QString fallbackPathAttribute() { return QStringLiteral("path"); }
-
-static inline bool snippetComparison()
-{
- return ReportHandler::debugLevel() >= ReportHandler::FullDebug;
-}
-
-template <class Indent> // const char*/class Indentor
-void formatSnippet(QTextStream &str, Indent indent, const QString &snippet)
-{
- const QVector<QStringRef> lines = snippet.splitRef(QLatin1Char('\n'));
- for (const QStringRef &line : lines) {
- if (!line.trimmed().isEmpty())
- str << indent << line;
- str << Qt::endl;
- }
-}
-
-static QString msgSnippetComparison(const QString &location, const QString &identifier,
- const QString &pythonCode, const QString &fallbackCode)
-{
- QString result;
- QTextStream str(&result);
- str << "Python snippet " << location;
- if (!identifier.isEmpty())
- str << " [" << identifier << ']';
- str << ":\n";
- formatSnippet(str, " ", pythonCode);
- str << "Corresponding fallback snippet:\n";
- formatSnippet(str, " ", fallbackCode);
- str << "-- end --\n";
- return result;
-}
-
-void QtXmlToSphinx::handleSnippetTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- const bool consecutiveSnippet = m_lastTagName == QLatin1String("snippet")
- || m_lastTagName == QLatin1String("dots") || m_lastTagName == QLatin1String("codeline");
- if (consecutiveSnippet) {
- m_output.flush();
- m_output.string()->chop(2);
- }
- QString location = reader.attributes().value(QLatin1String("location")).toString();
- QString identifier = reader.attributes().value(QLatin1String("identifier")).toString();
- QString errorMessage;
- const QString pythonCode =
- readFromLocations(m_generator->codeSnippetDirs(), location, identifier, &errorMessage);
- if (!errorMessage.isEmpty())
- qCWarning(lcShibokenDoc, "%s", qPrintable(msgTagWarning(reader, m_context, m_lastTagName, errorMessage)));
- // Fall back to C++ snippet when "path" attribute is present.
- // Also read fallback snippet when comparison is desired.
- QString fallbackCode;
- if ((pythonCode.isEmpty() || snippetComparison())
- && reader.attributes().hasAttribute(fallbackPathAttribute())) {
- const QString fallback = reader.attributes().value(fallbackPathAttribute()).toString();
- if (QFileInfo::exists(fallback)) {
- if (pythonCode.isEmpty())
- qCWarning(lcShibokenDoc, "%s", qPrintable(msgFallbackWarning(reader, m_context, m_lastTagName, location, identifier, fallback)));
- fallbackCode = readFromLocation(fallback, identifier, &errorMessage);
- if (!errorMessage.isEmpty())
- qCWarning(lcShibokenDoc, "%s", qPrintable(msgTagWarning(reader, m_context, m_lastTagName, errorMessage)));
- }
- }
-
- if (!pythonCode.isEmpty() && !fallbackCode.isEmpty() && snippetComparison())
- qCDebug(lcShibokenDoc, "%s", qPrintable(msgSnippetComparison(location, identifier, pythonCode, fallbackCode)));
-
- if (!consecutiveSnippet)
- m_output << INDENT << "::\n\n";
-
- Indentation indentation(INDENT);
- const QString code = pythonCode.isEmpty() ? fallbackCode : pythonCode;
- if (code.isEmpty())
- m_output << INDENT << "<Code snippet \"" << location << ':' << identifier << "\" not found>\n";
- else
- formatSnippet(m_output, INDENT, code);
- m_output << Qt::endl;
- }
-}
-void QtXmlToSphinx::handleDotsTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- const bool consecutiveSnippet = m_lastTagName == QLatin1String("snippet")
- || m_lastTagName == QLatin1String("dots") || m_lastTagName == QLatin1String("codeline");
- if (consecutiveSnippet) {
- m_output.flush();
- m_output.string()->chop(2);
- } else {
- m_output << INDENT << "::\n\n";
- }
- Indentation indentation(INDENT);
- pushOutputBuffer();
- m_output << INDENT;
- int indent = reader.attributes().value(QLatin1String("indent")).toInt();
- for (int i = 0; i < indent; ++i)
- m_output << ' ';
- } else if (token == QXmlStreamReader::Characters) {
- m_output << reader.text().toString();
- } else if (token == QXmlStreamReader::EndElement) {
- m_output << popOutputBuffer() << "\n\n\n";
- }
-}
-
-void QtXmlToSphinx::handleTableTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- m_currentTable.clear();
- m_tableHasHeader = false;
- } else if (token == QXmlStreamReader::EndElement) {
- // write the table on m_output
- m_currentTable.setHeaderEnabled(m_tableHasHeader);
- m_currentTable.normalize();
- m_output << ensureEndl << m_currentTable;
- m_currentTable.clear();
- }
-}
-
-void QtXmlToSphinx::handleTermTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- pushOutputBuffer();
- } else if (token == QXmlStreamReader::Characters) {
- m_output << reader.text().toString().replace(QLatin1String("::"), QLatin1String("."));
- } else if (token == QXmlStreamReader::EndElement) {
- TableCell cell;
- cell.data = popOutputBuffer().trimmed();
- m_currentTable.appendRow(TableRow(1, cell));
- }
-}
-
-
-void QtXmlToSphinx::handleItemTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- if (m_currentTable.isEmpty())
- m_currentTable.appendRow({});
- TableRow& row = m_currentTable.last();
- TableCell cell;
- cell.colSpan = reader.attributes().value(QLatin1String("colspan")).toShort();
- cell.rowSpan = reader.attributes().value(QLatin1String("rowspan")).toShort();
- row << cell;
- pushOutputBuffer();
- } else if (token == QXmlStreamReader::EndElement) {
- QString data = popOutputBuffer().trimmed();
- if (!m_currentTable.isEmpty()) {
- TableRow& row = m_currentTable.last();
- if (!row.isEmpty())
- row.last().data = data;
- }
- }
-}
-
-void QtXmlToSphinx::handleRowTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- m_tableHasHeader = reader.name() == QLatin1String("header");
- m_currentTable.appendRow({});
- }
-}
-
-enum ListType { BulletList, OrderedList, EnumeratedList };
-
-static inline ListType webXmlListType(const QStringRef &t)
-{
- if (t == QLatin1String("enum"))
- return EnumeratedList;
- if (t == QLatin1String("ordered"))
- return OrderedList;
- return BulletList;
-}
-
-void QtXmlToSphinx::handleListTag(QXmlStreamReader& reader)
-{
- // BUG We do not support a list inside a table cell
- static ListType listType = BulletList;
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- listType = webXmlListType(reader.attributes().value(QLatin1String("type")));
- if (listType == EnumeratedList) {
- m_currentTable.appendRow(TableRow{TableCell(QLatin1String("Constant")),
- TableCell(QLatin1String("Description"))});
- m_tableHasHeader = true;
- }
- INDENT.indent--;
- } else if (token == QXmlStreamReader::EndElement) {
- INDENT.indent++;
- if (!m_currentTable.isEmpty()) {
- switch (listType) {
- case BulletList:
- case OrderedList: {
- m_output << Qt::endl;
- const char *separator = listType == BulletList ? "* " : "#. ";
- const char *indent = listType == BulletList ? " " : " ";
- for (const TableCell &cell : m_currentTable.constFirst()) {
- const QVector<QStringRef> itemLines = cell.data.splitRef(QLatin1Char('\n'));
- m_output << INDENT << separator << itemLines.constFirst() << Qt::endl;
- for (int i = 1, max = itemLines.count(); i < max; ++i)
- m_output << INDENT << indent << itemLines[i] << Qt::endl;
- }
- m_output << Qt::endl;
- }
- break;
- case EnumeratedList:
- m_currentTable.setHeaderEnabled(m_tableHasHeader);
- m_currentTable.normalize();
- m_output << ensureEndl << m_currentTable;
- break;
- }
- }
- m_currentTable.clear();
- }
-}
-
-void QtXmlToSphinx::handleLinkTag(QXmlStreamReader& reader)
-{
- switch (reader.tokenType()) {
- case QXmlStreamReader::StartElement: {
- // <link> embedded in <see-also> means the characters of <see-also> are no link.
- m_seeAlsoContext.reset();
- const QString type = fixLinkType(reader.attributes().value(QLatin1String("type")));
- const QString ref = reader.attributes().value(linkSourceAttribute(type)).toString();
- m_linkContext.reset(handleLinkStart(type, ref));
- }
- break;
- case QXmlStreamReader::Characters:
- Q_ASSERT(!m_linkContext.isNull());
- handleLinkText(m_linkContext.data(), reader.text().toString());
- break;
- case QXmlStreamReader::EndElement:
- Q_ASSERT(!m_linkContext.isNull());
- handleLinkEnd(m_linkContext.data());
- m_linkContext.reset();
- break;
- default:
- break;
- }
-}
-
-QtXmlToSphinx::LinkContext *QtXmlToSphinx::handleLinkStart(const QString &type, QString ref) const
-{
- ref.replace(QLatin1String("::"), QLatin1String("."));
- ref.remove(QLatin1String("()"));
- auto *result = new LinkContext(ref);
-
- if (m_insideBold)
- result->flags |= LinkContext::InsideBold;
- else if (m_insideItalic)
- result->flags |= LinkContext::InsideItalic;
-
- if (type == functionLinkType() && !m_context.isEmpty()) {
- result->type = LinkContext::Method;
- const QVector<QStringRef> rawlinklist = result->linkRef.splitRef(QLatin1Char('.'));
- if (rawlinklist.size() == 1 || rawlinklist.constFirst() == m_context) {
- QString context = resolveContextForMethod(rawlinklist.constLast().toString());
- if (!result->linkRef.startsWith(context))
- result->linkRef.prepend(context + QLatin1Char('.'));
- } else {
- result->linkRef = expandFunction(result->linkRef);
- }
- } else if (type == functionLinkType() && m_context.isEmpty()) {
- result->type = LinkContext::Function;
- } else if (type == classLinkType()) {
- result->type = LinkContext::Class;
- if (const TypeEntry *type = TypeDatabase::instance()->findType(result->linkRef)) {
- result->linkRef = type->qualifiedTargetLangName();
- } else { // fall back to the old heuristic if the type wasn't found.
- const QVector<QStringRef> rawlinklist = result->linkRef.splitRef(QLatin1Char('.'));
- QStringList splittedContext = m_context.split(QLatin1Char('.'));
- if (rawlinklist.size() == 1 || rawlinklist.constFirst() == splittedContext.constLast()) {
- splittedContext.removeLast();
- result->linkRef.prepend(QLatin1Char('~') + splittedContext.join(QLatin1Char('.'))
- + QLatin1Char('.'));
- }
- }
- } else if (type == QLatin1String("enum")) {
- result->type = LinkContext::Attribute;
- } else if (type == QLatin1String("page")) {
- // Module, external web page or reference
- if (result->linkRef == m_generator->moduleName())
- result->type = LinkContext::Module;
- else if (result->linkRef.startsWith(QLatin1String("http")))
- result->type = LinkContext::External;
- else
- result->type = LinkContext::Reference;
- } else if (type == QLatin1String("external")) {
- result->type = LinkContext::External;
- } else {
- result->type = LinkContext::Reference;
- }
- return result;
-}
-
-// <link raw="Model/View Classes" href="model-view-programming.html#model-view-classes"
-// type="page" page="Model/View Programming">Model/View Classes</link>
-// <link type="page" page="http://doc.qt.io/qt-5/class.html">QML types</link>
-// <link raw="Qt Quick" href="qtquick-index.html" type="page" page="Qt Quick">Qt Quick</link>
-// <link raw="QObject" href="qobject.html" type="class">QObject</link>
-// <link raw="Qt::Window" href="qt.html#WindowType-enum" type="enum" enum="Qt::WindowType">Qt::Window</link>
-// <link raw="QNetworkSession::reject()" href="qnetworksession.html#reject" type="function">QNetworkSession::reject()</link>
-
-static QString fixLinkText(const QtXmlToSphinx::LinkContext *linkContext,
- QString linktext)
-{
- if (linkContext->type == QtXmlToSphinx::LinkContext::External
- || linkContext->type == QtXmlToSphinx::LinkContext::Reference) {
- return linktext;
- }
- // For the language reference documentation, strip the module name.
- // Clear the link text if that matches the function/class/enumeration name.
- const int lastSep = linktext.lastIndexOf(QLatin1String("::"));
- if (lastSep != -1)
- linktext.remove(0, lastSep + 2);
- else
- stripPythonQualifiers(&linktext);
- if (linkContext->linkRef == linktext)
- return QString();
- if ((linkContext->type & QtXmlToSphinx::LinkContext::FunctionMask) != 0
- && (linkContext->linkRef + QLatin1String("()")) == linktext) {
- return QString();
- }
- return linktext;
-}
-
-void QtXmlToSphinx::handleLinkText(LinkContext *linkContext, const QString &linktext) const
-{
- linkContext->linkText = fixLinkText(linkContext, linktext);
-}
-
-void QtXmlToSphinx::handleLinkEnd(LinkContext *linkContext)
-{
- m_output << *linkContext;
-}
-
-// Copy images that are placed in a subdirectory "images" under the webxml files
-// by qdoc to a matching subdirectory under the "rst/PySide2/<module>" directory
-static bool copyImage(const QString &href, const QString &docDataDir,
- const QString &context, const QString &outputDir,
- QString *errorMessage)
-{
- const QChar slash = QLatin1Char('/');
- const int lastSlash = href.lastIndexOf(slash);
- const QString imagePath = lastSlash != -1 ? href.left(lastSlash) : QString();
- const QString imageFileName = lastSlash != -1 ? href.right(href.size() - lastSlash - 1) : href;
- QFileInfo imageSource(docDataDir + slash + href);
- if (!imageSource.exists()) {
- QTextStream(errorMessage) << "Image " << href << " does not exist in "
- << QDir::toNativeSeparators(docDataDir);
- return false;
- }
- // Determine directory from context, "Pyside2.QtGui.QPainter" ->"Pyside2/QtGui".
- // FIXME: Not perfect yet, should have knowledge about namespaces (DataVis3D) or
- // nested classes "Pyside2.QtGui.QTouchEvent.QTouchPoint".
- QString relativeTargetDir = context;
- const int lastDot = relativeTargetDir.lastIndexOf(QLatin1Char('.'));
- if (lastDot != -1)
- relativeTargetDir.truncate(lastDot);
- relativeTargetDir.replace(QLatin1Char('.'), slash);
- if (!imagePath.isEmpty())
- relativeTargetDir += slash + imagePath;
-
- const QString targetDir = outputDir + slash + relativeTargetDir;
- const QString targetFileName = targetDir + slash + imageFileName;
- if (QFileInfo::exists(targetFileName))
- return true;
- if (!QFileInfo::exists(targetDir)) {
- const QDir outDir(outputDir);
- if (!outDir.mkpath(relativeTargetDir)) {
- QTextStream(errorMessage) << "Cannot create " << QDir::toNativeSeparators(relativeTargetDir)
- << " under " << QDir::toNativeSeparators(outputDir);
- return false;
- }
- }
-
- QFile source(imageSource.absoluteFilePath());
- if (!source.copy(targetFileName)) {
- QTextStream(errorMessage) << "Cannot copy " << QDir::toNativeSeparators(source.fileName())
- << " to " << QDir::toNativeSeparators(targetFileName) << ": "
- << source.errorString();
- return false;
- }
- qCDebug(lcShibokenDoc()).noquote().nospace() << __FUNCTION__ << " href=\""
- << href << "\", context=\"" << context << "\", docDataDir=\""
- << docDataDir << "\", outputDir=\"" << outputDir << "\", copied \""
- << source.fileName() << "\"->\"" << targetFileName << '"';
- return true;
-}
-
-bool QtXmlToSphinx::copyImage(const QString &href) const
-{
- QString errorMessage;
- const bool result =
- ::copyImage(href, m_generator->docDataDir(), m_context,
- m_generator->outputDirectory(), &errorMessage);
- if (!result)
- qCWarning(lcShibokenDoc, "%s", qPrintable(errorMessage));
- return result;
-}
-
-void QtXmlToSphinx::handleImageTag(QXmlStreamReader& reader)
-{
- if (reader.tokenType() != QXmlStreamReader::StartElement)
- return;
- const QString href = reader.attributes().value(QLatin1String("href")).toString();
- if (copyImage(href))
- m_output << INDENT << ".. image:: " << href << Qt::endl << Qt::endl;
-}
-
-void QtXmlToSphinx::handleInlineImageTag(QXmlStreamReader& reader)
-{
- if (reader.tokenType() != QXmlStreamReader::StartElement)
- return;
- const QString href = reader.attributes().value(QLatin1String("href")).toString();
- if (!copyImage(href))
- return;
- // Handle inline images by substitution references. Insert a unique tag
- // enclosed by '|' and define it further down. Determine tag from the base
- //file name with number.
- QString tag = href;
- int pos = tag.lastIndexOf(QLatin1Char('/'));
- if (pos != -1)
- tag.remove(0, pos + 1);
- pos = tag.indexOf(QLatin1Char('.'));
- if (pos != -1)
- tag.truncate(pos);
- tag += QString::number(m_inlineImages.size() + 1);
- m_inlineImages.append(InlineImage{tag, href});
- m_output << '|' << tag << '|' << ' ';
-}
-
-void QtXmlToSphinx::handleRawTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- QString format = reader.attributes().value(QLatin1String("format")).toString();
- m_output << INDENT << ".. raw:: " << format.toLower() << Qt::endl << Qt::endl;
- } else if (token == QXmlStreamReader::Characters) {
- const QVector<QStringRef> lst(reader.text().split(QLatin1Char('\n')));
- for (const QStringRef &row : lst)
- m_output << INDENT << INDENT << row << Qt::endl;
- } else if (token == QXmlStreamReader::EndElement) {
- m_output << Qt::endl << Qt::endl;
- }
-}
-
-void QtXmlToSphinx::handleCodeTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- m_output << INDENT << "::\n\n";
- INDENT.indent++;
- } else if (token == QXmlStreamReader::Characters) {
- const QVector<QStringRef> lst(reader.text().split(QLatin1Char('\n')));
- for (const QStringRef &row : lst)
- m_output << INDENT << INDENT << row << Qt::endl;
- } else if (token == QXmlStreamReader::EndElement) {
- m_output << Qt::endl << Qt::endl;
- INDENT.indent--;
- }
-}
-
-void QtXmlToSphinx::handleUnknownTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement)
- qCDebug(lcShibokenDoc).noquote().nospace() << "Unknown QtDoc tag: \"" << reader.name().toString() << "\".";
-}
-
-void QtXmlToSphinx::handleSuperScriptTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- m_output << " :sup:`";
- pushOutputBuffer();
- } else if (token == QXmlStreamReader::Characters) {
- m_output << reader.text().toString();
- } else if (token == QXmlStreamReader::EndElement) {
- m_output << popOutputBuffer();
- m_output << '`';
- }
-}
-
-void QtXmlToSphinx::handlePageTag(QXmlStreamReader &reader)
-{
- if (reader.tokenType() != QXmlStreamReader::StartElement)
- return;
-
- const QStringRef title = reader.attributes().value(titleAttribute());
- if (!title.isEmpty())
- m_output << rstLabel(title.toString());
-
- const QStringRef fullTitle = reader.attributes().value(fullTitleAttribute());
- const int size = fullTitle.isEmpty()
- ? writeEscapedRstText(m_output, title)
- : writeEscapedRstText(m_output, fullTitle);
-
- m_output << Qt::endl << Pad('*', size) << Qt::endl << Qt::endl;
-}
-
-void QtXmlToSphinx::handleTargetTag(QXmlStreamReader &reader)
-{
- if (reader.tokenType() != QXmlStreamReader::StartElement)
- return;
- const QStringRef name = reader.attributes().value(nameAttribute());
- if (!name.isEmpty())
- m_output << INDENT << rstLabel(name.toString());
-}
-
-void QtXmlToSphinx::handleIgnoredTag(QXmlStreamReader&)
-{
-}
-
-void QtXmlToSphinx::handleUselessTag(QXmlStreamReader&)
-{
- // Tag "description" just marks the init of "Detailed description" title.
- // Tag "definition" just marks enums. We have a different way to process them.
-}
-
-void QtXmlToSphinx::handleAnchorTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::StartElement) {
- QString anchor;
- if (reader.attributes().hasAttribute(QLatin1String("id")))
- anchor = reader.attributes().value(QLatin1String("id")).toString();
- else if (reader.attributes().hasAttribute(QLatin1String("name")))
- anchor = reader.attributes().value(QLatin1String("name")).toString();
- if (!anchor.isEmpty() && m_opened_anchor != anchor) {
- m_opened_anchor = anchor;
- if (!m_context.isEmpty())
- anchor.prepend(m_context + QLatin1Char('_'));
- m_output << INDENT << rstLabel(anchor);
- }
- } else if (token == QXmlStreamReader::EndElement) {
- m_opened_anchor.clear();
- }
-}
-
-void QtXmlToSphinx::handleRstPassTroughTag(QXmlStreamReader& reader)
-{
- if (reader.tokenType() == QXmlStreamReader::Characters)
- m_output << reader.text();
-}
-
-void QtXmlToSphinx::handleQuoteFileTag(QXmlStreamReader& reader)
-{
- QXmlStreamReader::TokenType token = reader.tokenType();
- if (token == QXmlStreamReader::Characters) {
- QString location = reader.text().toString();
- location.prepend(m_generator->libSourceDir() + QLatin1Char('/'));
- QString errorMessage;
- QString code = readFromLocation(location, QString(), &errorMessage);
- if (!errorMessage.isEmpty())
- qCWarning(lcShibokenDoc, "%s", qPrintable(msgTagWarning(reader, m_context, m_lastTagName, errorMessage)));
- m_output << INDENT << "::\n\n";
- Indentation indentation(INDENT);
- if (code.isEmpty())
- m_output << INDENT << "<Code snippet \"" << location << "\" not found>\n";
- else
- formatCode(m_output, code, INDENT);
- m_output << Qt::endl;
- }
-}
-
-bool QtXmlToSphinx::convertToRst(QtDocGenerator *generator,
- const QString &sourceFileName,
- const QString &targetFileName,
- const QString &context, QString *errorMessage)
-{
- QFile sourceFile(sourceFileName);
- if (!sourceFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
- if (errorMessage)
- *errorMessage = msgCannotOpenForReading(sourceFile);
- return false;
- }
- const QString doc = QString::fromUtf8(sourceFile.readAll());
- sourceFile.close();
-
- FileOut targetFile(targetFileName);
- QtXmlToSphinx x(generator, doc, context);
- targetFile.stream << x;
- return targetFile.done(errorMessage) != FileOut::Failure;
-}
-
-void QtXmlToSphinx::Table::normalize()
-{
- if (m_normalized || isEmpty())
- return;
-
- //QDoc3 generates tables with wrong number of columns. We have to
- //check and if necessary, merge the last columns.
- int maxCols = -1;
- for (const auto &row : qAsConst(m_rows)) {
- if (row.count() > maxCols)
- maxCols = row.count();
- }
- if (maxCols <= 0)
- return;
- // add col spans
- for (int row = 0; row < m_rows.count(); ++row) {
- for (int col = 0; col < m_rows.at(row).count(); ++col) {
- QtXmlToSphinx::TableCell& cell = m_rows[row][col];
- bool mergeCols = (col >= maxCols);
- if (cell.colSpan > 0) {
- QtXmlToSphinx::TableCell newCell;
- newCell.colSpan = -1;
- for (int i = 0, max = cell.colSpan-1; i < max; ++i) {
- m_rows[row].insert(col + 1, newCell);
- }
- cell.colSpan = 0;
- col++;
- } else if (mergeCols) {
- m_rows[row][maxCols - 1].data += QLatin1Char(' ') + cell.data;
- }
- }
- }
-
- // row spans
- const int numCols = m_rows.constFirst().count();
- for (int col = 0; col < numCols; ++col) {
- for (int row = 0; row < m_rows.count(); ++row) {
- if (col < m_rows[row].count()) {
- QtXmlToSphinx::TableCell& cell = m_rows[row][col];
- if (cell.rowSpan > 0) {
- QtXmlToSphinx::TableCell newCell;
- newCell.rowSpan = -1;
- int targetRow = row + 1;
- const int targetEndRow =
- std::min(targetRow + cell.rowSpan - 1, m_rows.count());
- cell.rowSpan = 0;
- for ( ; targetRow < targetEndRow; ++targetRow)
- m_rows[targetRow].insert(col, newCell);
- row++;
- }
- }
- }
- }
- m_normalized = true;
-}
-
-QTextStream& operator<<(QTextStream& s, const QtXmlToSphinx::Table &table)
-{
- table.format(s);
- return s;
-}
-
-void QtXmlToSphinx::Table::format (QTextStream& s) const
-{
- if (isEmpty())
- return;
-
- if (!isNormalized()) {
- qCDebug(lcShibokenDoc) << "Attempt to print an unnormalized table!";
- return;
- }
-
- // calc width and height of each column and row
- const int headerColumnCount = m_rows.constFirst().count();
- QVector<int> colWidths(headerColumnCount);
- QVector<int> rowHeights(m_rows.count());
- for (int i = 0, maxI = m_rows.count(); i < maxI; ++i) {
- const QtXmlToSphinx::TableRow& row = m_rows.at(i);
- for (int j = 0, maxJ = std::min(row.count(), colWidths.size()); j < maxJ; ++j) {
- const QVector<QStringRef> rowLines = row[j].data.splitRef(QLatin1Char('\n')); // cache this would be a good idea
- for (const QStringRef &str : rowLines)
- colWidths[j] = std::max(colWidths[j], str.count());
- rowHeights[i] = std::max(rowHeights[i], row[j].data.count(QLatin1Char('\n')) + 1);
- }
- }
-
- if (!*std::max_element(colWidths.begin(), colWidths.end()))
- return; // empty table (table with empty cells)
-
- // create a horizontal line to be used later.
- QString horizontalLine = QLatin1String("+");
- for (int i = 0, max = colWidths.count(); i < max; ++i) {
- horizontalLine += QString(colWidths.at(i), QLatin1Char('-'));
- horizontalLine += QLatin1Char('+');
- }
-
- // write table rows
- for (int i = 0, maxI = m_rows.count(); i < maxI; ++i) { // for each row
- const QtXmlToSphinx::TableRow& row = m_rows.at(i);
-
- // print line
- s << INDENT << '+';
- for (int col = 0; col < headerColumnCount; ++col) {
- char c;
- if (col >= row.length() || row[col].rowSpan == -1)
- c = ' ';
- else if (i == 1 && hasHeader())
- c = '=';
- else
- c = '-';
- s << Pad(c, colWidths.at(col)) << '+';
- }
- s << Qt::endl;
-
-
- // Print the table cells
- for (int rowLine = 0; rowLine < rowHeights[i]; ++rowLine) { // for each line in a row
- int j = 0;
- for (int maxJ = std::min(row.count(), headerColumnCount); j < maxJ; ++j) { // for each column
- const QtXmlToSphinx::TableCell& cell = row[j];
- const QVector<QStringRef> rowLines = cell.data.splitRef(QLatin1Char('\n')); // FIXME: Cache this!!!
- if (!j) // First column, so we need print the identation
- s << INDENT;
-
- if (!j || !cell.colSpan)
- s << '|';
- else
- s << ' ';
- if (rowLine < rowLines.count())
- s << qSetFieldWidth(colWidths[j]) << Qt::left << rowLines.at(rowLine) << qSetFieldWidth(0);
- else
- s << Pad(' ', colWidths.at(j));
- }
- for ( ; j < headerColumnCount; ++j) // pad
- s << '|' << Pad(' ', colWidths.at(j));
- s << "|\n";
- }
- }
- s << INDENT << horizontalLine << Qt::endl << Qt::endl;
-}
-
-static QString getFuncName(const AbstractMetaFunction* cppFunc) {
- static bool hashInitialized = false;
- static QHash<QString, QString> operatorsHash;
- if (!hashInitialized) {
- operatorsHash.insert(QLatin1String("operator+"), QLatin1String("__add__"));
- operatorsHash.insert(QLatin1String("operator+="), QLatin1String("__iadd__"));
- operatorsHash.insert(QLatin1String("operator-"), QLatin1String("__sub__"));
- operatorsHash.insert(QLatin1String("operator-="), QLatin1String("__isub__"));
- operatorsHash.insert(QLatin1String("operator*"), QLatin1String("__mul__"));
- operatorsHash.insert(QLatin1String("operator*="), QLatin1String("__imul__"));
- operatorsHash.insert(QLatin1String("operator/"), QLatin1String("__div__"));
- operatorsHash.insert(QLatin1String("operator/="), QLatin1String("__idiv__"));
- operatorsHash.insert(QLatin1String("operator%"), QLatin1String("__mod__"));
- operatorsHash.insert(QLatin1String("operator%="), QLatin1String("__imod__"));
- operatorsHash.insert(QLatin1String("operator<<"), QLatin1String("__lshift__"));
- operatorsHash.insert(QLatin1String("operator<<="), QLatin1String("__ilshift__"));
- operatorsHash.insert(QLatin1String("operator>>"), QLatin1String("__rshift__"));
- operatorsHash.insert(QLatin1String("operator>>="), QLatin1String("__irshift__"));
- operatorsHash.insert(QLatin1String("operator&"), QLatin1String("__and__"));
- operatorsHash.insert(QLatin1String("operator&="), QLatin1String("__iand__"));
- operatorsHash.insert(QLatin1String("operator|"), QLatin1String("__or__"));
- operatorsHash.insert(QLatin1String("operator|="), QLatin1String("__ior__"));
- operatorsHash.insert(QLatin1String("operator^"), QLatin1String("__xor__"));
- operatorsHash.insert(QLatin1String("operator^="), QLatin1String("__ixor__"));
- operatorsHash.insert(QLatin1String("operator=="), QLatin1String("__eq__"));
- operatorsHash.insert(QLatin1String("operator!="), QLatin1String("__ne__"));
- operatorsHash.insert(QLatin1String("operator<"), QLatin1String("__lt__"));
- operatorsHash.insert(QLatin1String("operator<="), QLatin1String("__le__"));
- operatorsHash.insert(QLatin1String("operator>"), QLatin1String("__gt__"));
- operatorsHash.insert(QLatin1String("operator>="), QLatin1String("__ge__"));
- hashInitialized = true;
- }
-
- QHash<QString, QString>::const_iterator it = operatorsHash.constFind(cppFunc->name());
- QString result = it != operatorsHash.cend() ? it.value() : cppFunc->name();
- result.replace(QLatin1String("::"), QLatin1String("."));
- return result;
-}
-
-QtDocGenerator::QtDocGenerator() : m_docParser(nullptr)
-{
-}
-
-QtDocGenerator::~QtDocGenerator()
-{
- delete m_docParser;
-}
-
-QString QtDocGenerator::fileNameSuffix() const
-{
- return QLatin1String(".rst");
-}
-
-bool QtDocGenerator::shouldGenerate(const AbstractMetaClass *cls) const
-{
- return Generator::shouldGenerate(cls)
- && cls->typeEntry()->type() != TypeEntry::SmartPointerType;
-}
-
-QString QtDocGenerator::fileNameForContext(const GeneratorContext &context) const
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- if (!context.forSmartPointer()) {
- return getClassTargetFullName(metaClass, false) + fileNameSuffix();
- }
- const AbstractMetaType *smartPointerType = context.preciseType();
- QString fileNameBase = getFileNameBaseForSmartPointer(smartPointerType, metaClass);
- return fileNameBase + fileNameSuffix();
-}
-
-void QtDocGenerator::writeFormattedText(QTextStream &s, const Documentation &doc,
- const AbstractMetaClass *metaClass)
-{
- QString metaClassName;
-
- if (metaClass)
- metaClassName = getClassTargetFullName(metaClass);
-
- if (doc.format() == Documentation::Native) {
- QtXmlToSphinx x(this, doc.value(), metaClassName);
- s << x;
- } else {
- const QString &value = doc.value();
- const QVector<QStringRef> lines = value.splitRef(QLatin1Char('\n'));
- int typesystemIndentation = std::numeric_limits<int>::max();
- // check how many spaces must be removed from the beginning of each line
- for (const QStringRef &line : lines) {
- const auto it = std::find_if(line.cbegin(), line.cend(),
- [] (QChar c) { return !c.isSpace(); });
- if (it != line.cend())
- typesystemIndentation = qMin(typesystemIndentation, int(it - line.cbegin()));
- }
- if (typesystemIndentation == std::numeric_limits<int>::max())
- typesystemIndentation = 0;
- for (const QStringRef &line : lines) {
- s << INDENT
- << (typesystemIndentation > 0 && typesystemIndentation < line.size()
- ? line.right(line.size() - typesystemIndentation) : line)
- << Qt::endl;
- }
- }
-
- s << Qt::endl;
-}
-
-static void writeInheritedByList(QTextStream& s, const AbstractMetaClass* metaClass, const AbstractMetaClassList& allClasses)
-{
- AbstractMetaClassList res;
- for (AbstractMetaClass *c : allClasses) {
- if (c != metaClass && c->inheritsFrom(metaClass))
- res << c;
- }
-
- if (res.isEmpty())
- return;
-
- s << "**Inherited by:** ";
- QStringList classes;
- for (AbstractMetaClass *c : qAsConst(res))
- classes << QLatin1String(":ref:`") + getClassTargetFullName(c, false) + QLatin1Char('`');
- s << classes.join(QLatin1String(", ")) << Qt::endl << Qt::endl;
-}
-
-// Extract the <brief> section from a WebXML (class) documentation and remove it
-// from the source.
-static bool extractBrief(Documentation *sourceDoc, Documentation *brief)
-{
- if (sourceDoc->format() != Documentation::Native)
- return false;
- QString value = sourceDoc->value();
- const int briefStart = value.indexOf(briefStartElement());
- if (briefStart < 0)
- return false;
- const int briefEnd = value.indexOf(briefEndElement(), briefStart + briefStartElement().size());
- if (briefEnd < briefStart)
- return false;
- const int briefLength = briefEnd + briefEndElement().size() - briefStart;
- brief->setFormat(Documentation::Native);
- QString briefValue = value.mid(briefStart, briefLength);
- briefValue.insert(briefValue.size() - briefEndElement().size(),
- QLatin1String("<rst> More_...</rst>"));
- brief->setValue(briefValue);
- value.remove(briefStart, briefLength);
- sourceDoc->setValue(value);
- return true;
-}
-
-void QtDocGenerator::generateClass(QTextStream &s, const GeneratorContext &classContext)
-{
- const AbstractMetaClass *metaClass = classContext.metaClass();
- qCDebug(lcShibokenDoc).noquote().nospace() << "Generating Documentation for " << metaClass->fullName();
-
- m_packages[metaClass->package()] << fileNameForContext(classContext);
-
- m_docParser->setPackageName(metaClass->package());
- m_docParser->fillDocumentation(const_cast<AbstractMetaClass*>(metaClass));
-
- QString className = getClassTargetFullName(metaClass, false);
- s << ".. _" << className << ":" << "\n\n";
- s << ".. currentmodule:: " << metaClass->package() << "\n\n\n";
-
- s << className << Qt::endl;
- s << Pad('*', className.count()) << Qt::endl << Qt::endl;
-
- auto documentation = metaClass->documentation();
- Documentation brief;
- if (extractBrief(&documentation, &brief))
- writeFormattedText(s, brief, metaClass);
-
- s << ".. inheritance-diagram:: " << getClassTargetFullName(metaClass, true) << Qt::endl
- << " :parts: 2\n\n"; // TODO: This would be a parameter in the future...
-
-
- writeInheritedByList(s, metaClass, classes());
-
- const auto version = versionOf(metaClass->typeEntry());
- if (!version.isNull())
- s << rstVersionAdded(version);
- if (metaClass->attributes().testFlag(AbstractMetaAttributes::Deprecated))
- s << rstDeprecationNote("class");
-
- writeFunctionList(s, metaClass);
-
- //Function list
- AbstractMetaFunctionList functionList = metaClass->functions();
- std::sort(functionList.begin(), functionList.end(), functionSort);
-
- s << "\nDetailed Description\n"
- "--------------------\n\n"
- << ".. _More:\n";
-
- writeInjectDocumentation(s, TypeSystem::DocModificationPrepend, metaClass, nullptr);
- if (!writeInjectDocumentation(s, TypeSystem::DocModificationReplace, metaClass, nullptr))
- writeFormattedText(s, documentation, metaClass);
-
- if (!metaClass->isNamespace())
- writeConstructors(s, metaClass);
- writeEnums(s, metaClass);
- if (!metaClass->isNamespace())
- writeFields(s, metaClass);
-
-
- for (AbstractMetaFunction *func : qAsConst(functionList)) {
- if (shouldSkip(func))
- continue;
-
- if (func->isStatic())
- s << ".. staticmethod:: ";
- else
- s << ".. method:: ";
-
- writeFunction(s, metaClass, func);
- }
-
- writeInjectDocumentation(s, TypeSystem::DocModificationAppend, metaClass, nullptr);
-}
-
-void QtDocGenerator::writeFunctionList(QTextStream& s, const AbstractMetaClass* cppClass)
-{
- QStringList functionList;
- QStringList virtualList;
- QStringList signalList;
- QStringList slotList;
- QStringList staticFunctionList;
-
- const AbstractMetaFunctionList &classFunctions = cppClass->functions();
- for (AbstractMetaFunction *func : classFunctions) {
- if (shouldSkip(func))
- continue;
-
- QString className;
- if (!func->isConstructor())
- className = getClassTargetFullName(cppClass) + QLatin1Char('.');
- else if (func->implementingClass() && func->implementingClass()->enclosingClass())
- className = getClassTargetFullName(func->implementingClass()->enclosingClass()) + QLatin1Char('.');
- QString funcName = getFuncName(func);
-
- QString str = QLatin1String("def :meth:`");
-
- str += funcName;
- str += QLatin1Char('<');
- if (!funcName.startsWith(className))
- str += className;
- str += funcName;
- str += QLatin1String(">` (");
- str += parseArgDocStyle(cppClass, func);
- str += QLatin1Char(')');
-
- if (func->isStatic())
- staticFunctionList << str;
- else if (func->isVirtual())
- virtualList << str;
- else if (func->isSignal())
- signalList << str;
- else if (func->isSlot())
- slotList << str;
- else
- functionList << str;
- }
-
- if (!functionList.isEmpty() || !staticFunctionList.isEmpty()) {
- QtXmlToSphinx::Table functionTable;
-
- s << "\nSynopsis\n--------\n\n";
-
- writeFunctionBlock(s, QLatin1String("Functions"), functionList);
- writeFunctionBlock(s, QLatin1String("Virtual functions"), virtualList);
- writeFunctionBlock(s, QLatin1String("Slots"), slotList);
- writeFunctionBlock(s, QLatin1String("Signals"), signalList);
- writeFunctionBlock(s, QLatin1String("Static functions"), staticFunctionList);
- }
-}
-
-void QtDocGenerator::writeFunctionBlock(QTextStream& s, const QString& title, QStringList& functions)
-{
- if (!functions.isEmpty()) {
- s << title << Qt::endl
- << QString(title.size(), QLatin1Char('^')) << Qt::endl;
-
- std::sort(functions.begin(), functions.end());
-
- s << ".. container:: function_list\n\n";
- Indentation indentation(INDENT);
- for (const QString &func : qAsConst(functions))
- s << INDENT << '*' << ' ' << func << Qt::endl;
-
- s << Qt::endl << Qt::endl;
- }
-}
-
-void QtDocGenerator::writeEnums(QTextStream& s, const AbstractMetaClass* cppClass)
-{
- static const QString section_title = QLatin1String(".. attribute:: ");
-
- const AbstractMetaEnumList &enums = cppClass->enums();
- for (AbstractMetaEnum *en : enums) {
- s << section_title << getClassTargetFullName(cppClass) << '.' << en->name() << Qt::endl << Qt::endl;
- writeFormattedText(s, en->documentation(), cppClass);
- const auto version = versionOf(en->typeEntry());
- if (!version.isNull())
- s << rstVersionAdded(version);
- }
-
-}
-
-void QtDocGenerator::writeFields(QTextStream& s, const AbstractMetaClass* cppClass)
-{
- static const QString section_title = QLatin1String(".. attribute:: ");
-
- const AbstractMetaFieldList &fields = cppClass->fields();
- for (AbstractMetaField *field : fields) {
- s << section_title << getClassTargetFullName(cppClass) << "." << field->name() << Qt::endl << Qt::endl;
- //TODO: request for member ‘documentation’ is ambiguous
- writeFormattedText(s, field->AbstractMetaAttributes::documentation(), cppClass);
- }
-}
-
-void QtDocGenerator::writeConstructors(QTextStream& s, const AbstractMetaClass* cppClass)
-{
- static const QString sectionTitle = QLatin1String(".. class:: ");
-
- AbstractMetaFunctionList lst = cppClass->queryFunctions(AbstractMetaClass::Constructors | AbstractMetaClass::Visible);
- for (int i = lst.size() - 1; i >= 0; --i) {
- if (lst.at(i)->isModifiedRemoved() || lst.at(i)->functionType() == AbstractMetaFunction::MoveConstructorFunction)
- lst.removeAt(i);
- }
-
- bool first = true;
- QHash<QString, AbstractMetaArgument*> arg_map;
-
- IndentorBase<1> indent1;
- indent1.indent = INDENT.total();
- for (AbstractMetaFunction *func : qAsConst(lst)) {
- s << indent1;
- if (first) {
- first = false;
- s << sectionTitle;
- indent1.indent += sectionTitle.size();
- }
- s << functionSignature(cppClass, func) << "\n\n";
-
- const auto version = versionOf(func->typeEntry());
- if (!version.isNull())
- s << indent1 << rstVersionAdded(version);
- if (func->attributes().testFlag(AbstractMetaAttributes::Deprecated))
- s << indent1 << rstDeprecationNote("constructor");
-
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (AbstractMetaArgument *arg : arguments) {
- if (!arg_map.contains(arg->name())) {
- arg_map.insert(arg->name(), arg);
- }
- }
- }
-
- s << Qt::endl;
-
- for (QHash<QString, AbstractMetaArgument*>::const_iterator it = arg_map.cbegin(), end = arg_map.cend(); it != end; ++it) {
- Indentation indentation(INDENT, 2);
- writeParameterType(s, cppClass, it.value());
- }
-
- s << Qt::endl;
-
- for (AbstractMetaFunction *func : qAsConst(lst))
- writeFormattedText(s, func->documentation(), cppClass);
-}
-
-QString QtDocGenerator::parseArgDocStyle(const AbstractMetaClass* /* cppClass */,
- const AbstractMetaFunction* func)
-{
- QString ret;
- int optArgs = 0;
-
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (AbstractMetaArgument *arg : arguments) {
-
- if (func->argumentRemoved(arg->argumentIndex() + 1))
- continue;
-
- bool thisIsoptional = !arg->defaultValueExpression().isEmpty();
- if (optArgs || thisIsoptional) {
- ret += QLatin1Char('[');
- optArgs++;
- }
-
- if (arg->argumentIndex() > 0)
- ret += QLatin1String(", ");
-
- ret += arg->name();
-
- if (thisIsoptional) {
- QString defValue = arg->defaultValueExpression();
- if (defValue == QLatin1String("QString()")) {
- defValue = QLatin1String("\"\"");
- } else if (defValue == QLatin1String("QStringList()")
- || defValue.startsWith(QLatin1String("QVector"))
- || defValue.startsWith(QLatin1String("QList"))) {
- defValue = QLatin1String("list()");
- } else if (defValue == QLatin1String("QVariant()")) {
- defValue = none();
- } else {
- defValue.replace(QLatin1String("::"), QLatin1String("."));
- if (defValue == QLatin1String("nullptr"))
- defValue = none();
- else if (defValue == QLatin1String("0") && arg->type()->isObject())
- defValue = none();
- }
- ret += QLatin1Char('=') + defValue;
- }
- }
-
- ret += QString(optArgs, QLatin1Char(']'));
- return ret;
-}
-
-void QtDocGenerator::writeDocSnips(QTextStream &s,
- const CodeSnipList &codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language)
-{
- Indentation indentation(INDENT);
- QStringList invalidStrings;
- const static QString startMarkup = QLatin1String("[sphinx-begin]");
- const static QString endMarkup = QLatin1String("[sphinx-end]");
-
- invalidStrings << QLatin1String("*") << QLatin1String("//") << QLatin1String("/*") << QLatin1String("*/");
-
- for (const CodeSnip &snip : codeSnips) {
- if ((snip.position != position) ||
- !(snip.language & language))
- continue;
-
- QString code = snip.code();
- while (code.contains(startMarkup) && code.contains(endMarkup)) {
- int startBlock = code.indexOf(startMarkup) + startMarkup.size();
- int endBlock = code.indexOf(endMarkup);
-
- if ((startBlock == -1) || (endBlock == -1))
- break;
-
- QString codeBlock = code.mid(startBlock, endBlock - startBlock);
- const QStringList rows = codeBlock.split(QLatin1Char('\n'));
- int currentRow = 0;
- int offset = 0;
-
- for (QString row : rows) {
- for (const QString &invalidString : qAsConst(invalidStrings))
- row.remove(invalidString);
-
- if (row.trimmed().size() == 0) {
- if (currentRow == 0)
- continue;
- s << Qt::endl;
- }
-
- if (currentRow == 0) {
- //find offset
- for (auto c : row) {
- if (c == QLatin1Char(' '))
- offset++;
- else if (c == QLatin1Char('\n'))
- offset = 0;
- else
- break;
- }
- }
- s << row.midRef(offset) << Qt::endl;
- currentRow++;
- }
-
- code = code.mid(endBlock+endMarkup.size());
- }
- }
-}
-
-bool QtDocGenerator::writeInjectDocumentation(QTextStream& s,
- TypeSystem::DocModificationMode mode,
- const AbstractMetaClass* cppClass,
- const AbstractMetaFunction* func)
-{
- Indentation indentation(INDENT);
- bool didSomething = false;
-
- const DocModificationList &mods = cppClass->typeEntry()->docModifications();
- for (const DocModification &mod : mods) {
- if (mod.mode() == mode) {
- bool modOk = func ? mod.signature() == func->minimalSignature() : mod.signature().isEmpty();
-
- if (modOk) {
- Documentation doc;
- Documentation::Format fmt;
-
- if (mod.format() == TypeSystem::NativeCode)
- fmt = Documentation::Native;
- else if (mod.format() == TypeSystem::TargetLangCode)
- fmt = Documentation::Target;
- else
- continue;
-
- doc.setValue(mod.code() , fmt);
- writeFormattedText(s, doc, cppClass);
- didSomething = true;
- }
- }
- }
-
- s << Qt::endl;
-
- // TODO: Deprecate the use of doc string on glue code.
- // This is pre "add-function" and "inject-documentation" tags.
- const TypeSystem::CodeSnipPosition pos = mode == TypeSystem::DocModificationPrepend
- ? TypeSystem::CodeSnipPositionBeginning : TypeSystem::CodeSnipPositionEnd;
- if (func)
- writeDocSnips(s, func->injectedCodeSnips(), pos, TypeSystem::TargetLangCode);
- else
- writeDocSnips(s, cppClass->typeEntry()->codeSnips(), pos, TypeSystem::TargetLangCode);
- return didSomething;
-}
-
-QString QtDocGenerator::functionSignature(const AbstractMetaClass* cppClass, const AbstractMetaFunction* func)
-{
- QString className;
- if (!func->isConstructor())
- className = getClassTargetFullName(cppClass) + QLatin1Char('.');
- else if (func->implementingClass() && func->implementingClass()->enclosingClass())
- className = getClassTargetFullName(func->implementingClass()->enclosingClass()) + QLatin1Char('.');
-
- QString funcName = getFuncName(func);
- if (!funcName.startsWith(className))
- funcName = className + funcName;
-
- return funcName + QLatin1Char('(') + parseArgDocStyle(cppClass, func)
- + QLatin1Char(')');
-}
-
-QString QtDocGenerator::translateToPythonType(const AbstractMetaType* type, const AbstractMetaClass* cppClass)
-{
- QString strType;
- const QString name = type->name();
- if (name == QLatin1String("QString")) {
- strType = QLatin1String("unicode");
- } else if (name == QLatin1String("QVariant")) {
- strType = QLatin1String("object");
- } else if (name == QLatin1String("QStringList")) {
- strType = QLatin1String("list of strings");
- } else if (type->isConstant() && name == QLatin1String("char") && type->indirections() == 1) {
- strType = QLatin1String("str");
- } else if (name.startsWith(QLatin1String("unsigned short"))) {
- strType = QLatin1String("int");
- } else if (name.startsWith(QLatin1String("unsigned "))) { // uint and ulong
- strType = QLatin1String("long");
- } else if (type->isContainer()) {
- QString strType = translateType(type, cppClass, Options(ExcludeConst) | ExcludeReference);
- strType.remove(QLatin1Char('*'));
- strType.remove(QLatin1Char('>'));
- strType.remove(QLatin1Char('<'));
- strType.replace(QLatin1String("::"), QLatin1String("."));
- if (strType.contains(QLatin1String("QList")) || strType.contains(QLatin1String("QVector"))) {
- strType.replace(QLatin1String("QList"), QLatin1String("list of "));
- strType.replace(QLatin1String("QVector"), QLatin1String("list of "));
- } else if (strType.contains(QLatin1String("QHash")) || strType.contains(QLatin1String("QMap"))) {
- strType.remove(QLatin1String("QHash"));
- strType.remove(QLatin1String("QMap"));
- QStringList types = strType.split(QLatin1Char(','));
- strType = QString::fromLatin1("Dictionary with keys of type %1 and values of type %2.")
- .arg(types[0], types[1]);
- }
- } else {
- QString refTag;
- if (type->isEnum())
- refTag = QLatin1String("attr");
- else
- refTag = QLatin1String("class");
- strType = QLatin1Char(':') + refTag + QLatin1String(":`") + name + QLatin1Char('`');
- }
- return strType;
-}
-
-void QtDocGenerator::writeParameterType(QTextStream& s, const AbstractMetaClass* cppClass, const AbstractMetaArgument* arg)
-{
- s << INDENT << ":param " << arg->name() << ": "
- << translateToPythonType(arg->type(), cppClass) << Qt::endl;
-}
-
-void QtDocGenerator::writeFunctionParametersType(QTextStream &s, const AbstractMetaClass *cppClass,
- const AbstractMetaFunction *func)
-{
- s << Qt::endl;
- const AbstractMetaArgumentList &funcArgs = func->arguments();
- for (AbstractMetaArgument *arg : funcArgs) {
-
- if (func->argumentRemoved(arg->argumentIndex() + 1))
- continue;
-
- writeParameterType(s, cppClass, arg);
- }
-
- if (!func->isConstructor() && func->type()) {
-
- QString retType;
- // check if the return type was modified
- const FunctionModificationList &mods = func->modifications();
- for (const FunctionModification &mod : mods) {
- for (const ArgumentModification &argMod : mod.argument_mods) {
- if (argMod.index == 0) {
- retType = argMod.modified_type;
- break;
- }
- }
- }
-
- if (retType.isEmpty())
- retType = translateToPythonType(func->type(), cppClass);
- s << INDENT << ":rtype: " << retType << Qt::endl;
- }
- s << Qt::endl;
-}
-
-void QtDocGenerator::writeFunction(QTextStream& s, const AbstractMetaClass* cppClass,
- const AbstractMetaFunction* func)
-{
- s << functionSignature(cppClass, func) << "\n\n";
-
- {
- Indentation indentation(INDENT);
- writeFunctionParametersType(s, cppClass, func);
- const auto version = versionOf(func->typeEntry());
- if (!version.isNull())
- s << INDENT << rstVersionAdded(version);
- if (func->attributes().testFlag(AbstractMetaAttributes::Deprecated))
- s << INDENT << rstDeprecationNote("function");
- }
-
- writeInjectDocumentation(s, TypeSystem::DocModificationPrepend, cppClass, func);
- if (!writeInjectDocumentation(s, TypeSystem::DocModificationReplace, cppClass, func))
- writeFormattedText(s, func->documentation(), cppClass);
- writeInjectDocumentation(s, TypeSystem::DocModificationAppend, cppClass, func);
-}
-
-static void writeFancyToc(QTextStream& s, const QStringList& items, int cols = 4)
-{
- using TocMap = QMap<QChar, QStringList>;
- TocMap tocMap;
- QChar Q = QLatin1Char('Q');
- QChar idx;
- for (QString item : items) {
- if (item.isEmpty())
- continue;
- if (item.startsWith(Q) && item.length() > 1)
- idx = item[1];
- else
- idx = item[0]; // To group classes without the 'Q' prefix
-
- item.chop(4); // Remove the .rst extension
- tocMap[idx] << item;
- }
- QtXmlToSphinx::Table table;
- QtXmlToSphinx::TableRow row;
-
- int itemsPerCol = (items.size() + tocMap.size()*2) / cols;
- QString currentColData;
- int i = 0;
- QTextStream ss(&currentColData);
- QMutableMapIterator<QChar, QStringList> it(tocMap);
- while (it.hasNext()) {
- it.next();
- std::sort(it.value().begin(), it.value().end());
-
- if (i)
- ss << Qt::endl;
-
- ss << "**" << it.key() << "**\n\n";
- i += 2; // a letter title is equivalent to two entries in space
- for (const QString &item : qAsConst(it.value())) {
- ss << "* :doc:`" << item << "`\n";
- ++i;
-
- // end of column detected!
- if (i > itemsPerCol) {
- ss.flush();
- QtXmlToSphinx::TableCell cell(currentColData);
- row << cell;
- currentColData.clear();
- i = 0;
- }
- }
- }
- if (i) {
- ss.flush();
- QtXmlToSphinx::TableCell cell(currentColData);
- row << cell;
- currentColData.clear();
- i = 0;
- }
- table.appendRow(row);
- table.normalize();
- s << ".. container:: pysidetoc\n\n";
- s << table;
-}
-
-bool QtDocGenerator::finishGeneration()
-{
- if (!classes().isEmpty())
- writeModuleDocumentation();
- if (!m_additionalDocumentationList.isEmpty())
- writeAdditionalDocumentation();
- return true;
-}
-
-void QtDocGenerator::writeModuleDocumentation()
-{
- QMap<QString, QStringList>::iterator it = m_packages.begin();
- for (; it != m_packages.end(); ++it) {
- QString key = it.key();
- key.replace(QLatin1Char('.'), QLatin1Char('/'));
- QString outputDir = outputDirectory() + QLatin1Char('/') + key;
- FileOut output(outputDir + QLatin1String("/index.rst"));
- QTextStream& s = output.stream;
-
- s << ".. module:: " << it.key() << Qt::endl << Qt::endl;
-
- const QString &title = it.key();
- s << title << Qt::endl;
- s << Pad('*', title.length()) << Qt::endl << Qt::endl;
-
- /* Avoid showing "Detailed Description for *every* class in toc tree */
- Indentation indentation(INDENT);
- // Store the it.key() in a QString so that it can be stripped off unwanted
- // information when neeeded. For example, the RST files in the extras directory
- // doesn't include the PySide# prefix in their names.
- const QString moduleName = it.key();
- const int lastIndex = moduleName.lastIndexOf(QLatin1Char('.'));
-
- // Search for extra-sections
- if (!m_extraSectionDir.isEmpty()) {
- QDir extraSectionDir(m_extraSectionDir);
- if (!extraSectionDir.exists())
- qCWarning(lcShibokenDoc) << m_extraSectionDir << "doesn't exist";
-
- QStringList fileList = extraSectionDir.entryList(QStringList() << (moduleName.mid(lastIndex + 1) + QLatin1String("?*.rst")), QDir::Files);
- QStringList::iterator it2 = fileList.begin();
- for (; it2 != fileList.end(); ++it2) {
- QString origFileName(*it2);
- it2->remove(0, moduleName.indexOf(QLatin1Char('.')));
- QString newFilePath = outputDir + QLatin1Char('/') + *it2;
- if (QFile::exists(newFilePath))
- QFile::remove(newFilePath);
- if (!QFile::copy(m_extraSectionDir + QLatin1Char('/') + origFileName, newFilePath)) {
- qCDebug(lcShibokenDoc).noquote().nospace() << "Error copying extra doc "
- << QDir::toNativeSeparators(m_extraSectionDir + QLatin1Char('/') + origFileName)
- << " to " << QDir::toNativeSeparators(newFilePath);
- }
- }
- it.value().append(fileList);
- }
-
- writeFancyToc(s, it.value());
-
- s << INDENT << ".. container:: hide\n\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << ".. toctree::\n";
- Indentation deeperIndentation(INDENT);
- s << INDENT << ":maxdepth: 1\n\n";
- for (const QString &className : qAsConst(it.value()))
- s << INDENT << className << Qt::endl;
- s << Qt::endl << Qt::endl;
- }
-
- s << "Detailed Description\n--------------------\n\n";
-
- // module doc is always wrong and C++istic, so go straight to the extra directory!
- QFile moduleDoc(m_extraSectionDir + QLatin1Char('/') + moduleName.mid(lastIndex + 1) + QLatin1String(".rst"));
- if (moduleDoc.open(QIODevice::ReadOnly | QIODevice::Text)) {
- s << moduleDoc.readAll();
- moduleDoc.close();
- } else {
- // try the normal way
- Documentation moduleDoc = m_docParser->retrieveModuleDocumentation(it.key());
- if (moduleDoc.format() == Documentation::Native) {
- QString context = it.key();
- stripPythonQualifiers(&context);
- QtXmlToSphinx x(this, moduleDoc.value(), context);
- s << x;
- } else {
- s << moduleDoc.value();
- }
- }
- }
-}
-
-static inline QString msgNonExistentAdditionalDocFile(const QString &dir,
- const QString &fileName)
-{
- const QString result = QLatin1Char('"') + fileName
- + QLatin1String("\" does not exist in ")
- + QDir::toNativeSeparators(dir) + QLatin1Char('.');
- return result;
-}
-
-void QtDocGenerator::writeAdditionalDocumentation()
-{
- QFile additionalDocumentationFile(m_additionalDocumentationList);
- if (!additionalDocumentationFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
- qCWarning(lcShibokenDoc, "%s",
- qPrintable(msgCannotOpenForReading(additionalDocumentationFile)));
- return;
- }
-
- 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(lcShibokenDoc, "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()) {
- const QString rstFileName = fi.baseName() + rstSuffix;
- const QString rstFile = targetDir + QLatin1Char('/') + rstFileName;
- const QString context = targetDir.mid(targetDir.lastIndexOf(QLatin1Char('/')) + 1);
- if (QtXmlToSphinx::convertToRst(this, fi.absoluteFilePath(),
- rstFile, context, &errorMessage)) {
- ++successCount;
- qCDebug(lcShibokenDoc).nospace().noquote() << __FUNCTION__
- << " converted " << fi.fileName()
- << ' ' << rstFileName;
- } else {
- qCWarning(lcShibokenDoc, "%s", qPrintable(errorMessage));
- }
- } else {
- qCWarning(lcShibokenDoc, "%s",
- qPrintable(msgNonExistentAdditionalDocFile(m_docDataDir, line)));
- }
- ++count;
- }
- }
- additionalDocumentationFile.close();
-
- qCInfo(lcShibokenDoc, "Created %d/%d additional documentation files.",
- successCount, count);
-}
-
-#ifdef __WIN32__
-# define PATH_SEP ';'
-#else
-# define PATH_SEP ':'
-#endif
-
-bool QtDocGenerator::doSetup()
-{
- if (m_codeSnippetDirs.isEmpty())
- m_codeSnippetDirs = m_libSourceDir.split(QLatin1Char(PATH_SEP));
-
- if (!m_docParser)
- m_docParser = new QtDocParser;
-
- if (m_libSourceDir.isEmpty() || m_docDataDir.isEmpty()) {
- qCWarning(lcShibokenDoc) << "Documentation data dir and/or Qt source dir not informed, "
- "documentation will not be extracted from Qt sources.";
- return false;
- }
-
- m_docParser->setDocumentationDataDirectory(m_docDataDir);
- m_docParser->setLibrarySourceDirectory(m_libSourceDir);
- return true;
-}
-
-
-Generator::OptionDescriptions QtDocGenerator::options() const
-{
- return OptionDescriptions()
- << qMakePair(QLatin1String("doc-parser=<parser>"),
- QLatin1String("The documentation parser used to interpret the documentation\n"
- "input files (qdoc|doxygen)"))
- << qMakePair(QLatin1String("documentation-code-snippets-dir=<dir>"),
- QLatin1String("Directory used to search code snippets used by the documentation"))
- << qMakePair(QLatin1String("documentation-data-dir=<dir>"),
- QLatin1String("Directory with XML files generated by documentation tool"))
- << qMakePair(QLatin1String("documentation-extra-sections-dir=<dir>"),
- QLatin1String("Directory used to search for extra documentation sections"))
- << qMakePair(QLatin1String("library-source-dir=<dir>"),
- QLatin1String("Directory where library source code is located"))
- << qMakePair(additionalDocumentationOption() + QLatin1String("=<file>"),
- QLatin1String("List of additional XML files to be converted to .rst files\n"
- "(for example, tutorials)."));
-}
-
-bool QtDocGenerator::handleOption(const QString &key, const QString &value)
-{
- if (key == QLatin1String("library-source-dir")) {
- m_libSourceDir = value;
- return true;
- }
- if (key == QLatin1String("documentation-data-dir")) {
- m_docDataDir = value;
- return true;
- }
- if (key == QLatin1String("documentation-code-snippets-dir")) {
- m_codeSnippetDirs = value.split(QLatin1Char(PATH_SEP));
- return true;
- }
- if (key == QLatin1String("documentation-extra-sections-dir")) {
- m_extraSectionDir = value;
- return true;
- }
- if (key == QLatin1String("doc-parser")) {
- qCDebug(lcShibokenDoc).noquote().nospace() << "doc-parser: " << value;
- if (value == QLatin1String("doxygen"))
- m_docParser = new DoxygenParser;
- return true;
- }
- if (key == additionalDocumentationOption()) {
- m_additionalDocumentationList = value;
- return true;
- }
- return false;
-}
diff --git a/sources/shiboken2/generator/qtdoc/qtdocgenerator.h b/sources/shiboken2/generator/qtdoc/qtdocgenerator.h
deleted file mode 100644
index e4067cc6f..000000000
--- a/sources/shiboken2/generator/qtdoc/qtdocgenerator.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef DOCGENERATOR_H
-#define DOCGENERATOR_H
-
-#include <QtCore/QStack>
-#include <QtCore/QHash>
-#include <QtCore/QScopedPointer>
-#include <QtCore/QTextStream>
-#include <QXmlStreamReader>
-#include "generator.h"
-#include "docparser.h"
-#include "typesystem_enums.h"
-#include "typesystem_typedefs.h"
-
-class QtDocParser;
-class AbstractMetaFunction;
-class AbstractMetaClass;
-QT_BEGIN_NAMESPACE
-class QXmlStreamReader;
-QT_END_NAMESPACE
-class QtDocGenerator;
-
-class QtXmlToSphinx
-{
-public:
- struct LinkContext;
-
- struct InlineImage
- {
- QString tag;
- QString href;
- };
-
- struct TableCell
- {
- short rowSpan = 0;
- short colSpan = 0;
- QString data;
-
- TableCell(const QString& text = QString()) : data(text) {}
- TableCell(const char* text) : data(QLatin1String(text)) {}
- };
-
- using TableRow = QVector<TableCell>;
-
- class Table
- {
- public:
- Table() = default;
-
- bool isEmpty() const { return m_rows.isEmpty(); }
-
- void setHeaderEnabled(bool enable)
- {
- m_hasHeader = enable;
- }
-
- bool hasHeader() const
- {
- return m_hasHeader;
- }
-
- void normalize();
-
- bool isNormalized() const
- {
- return m_normalized;
- }
-
- void clear() {
- m_normalized = false;
- m_rows.clear();
- }
-
- void appendRow(const TableRow &row) { m_rows.append(row); }
-
- const TableRow &constFirst() { return m_rows.constFirst(); }
- TableRow &first() { return m_rows.first(); }
- TableRow &last() { return m_rows.last(); }
-
- void format (QTextStream& s) const;
-
- private:
- QVector<TableRow> m_rows;
- bool m_hasHeader = false;
- bool m_normalized = false;
- };
-
- QtXmlToSphinx(QtDocGenerator* generator, const QString& doc, const QString& context = QString());
-
- static bool convertToRst(QtDocGenerator *generator,
- const QString &sourceFileName,
- const QString &targetFileName,
- const QString &context = QString(),
- QString *errorMessage = nullptr);
-
- QString result() const
- {
- return m_result;
- }
-
-private:
- QString resolveContextForMethod(const QString& methodName) const;
- QString expandFunction(const QString& function) const;
- QString transform(const QString& doc);
-
- void handleHeadingTag(QXmlStreamReader& reader);
- void handleParaTag(QXmlStreamReader& reader);
- void handleItalicTag(QXmlStreamReader& reader);
- void handleBoldTag(QXmlStreamReader& reader);
- void handleArgumentTag(QXmlStreamReader& reader);
- void handleSeeAlsoTag(QXmlStreamReader& reader);
- void handleSnippetTag(QXmlStreamReader& reader);
- void handleDotsTag(QXmlStreamReader& reader);
- void handleLinkTag(QXmlStreamReader& reader);
- void handleImageTag(QXmlStreamReader& reader);
- void handleInlineImageTag(QXmlStreamReader& reader);
- void handleListTag(QXmlStreamReader& reader);
- void handleTermTag(QXmlStreamReader& reader);
- void handleSuperScriptTag(QXmlStreamReader& reader);
- void handleQuoteFileTag(QXmlStreamReader& reader);
-
- // table tagsvoid QtXmlToSphinx::handleValueTag(QXmlStreamReader& reader)
-
- void handleTableTag(QXmlStreamReader& reader);
- void handleRowTag(QXmlStreamReader& reader);
- void handleItemTag(QXmlStreamReader& reader);
- void handleRawTag(QXmlStreamReader& reader);
- void handleCodeTag(QXmlStreamReader& reader);
- void handlePageTag(QXmlStreamReader&);
- void handleTargetTag(QXmlStreamReader&);
-
- void handleIgnoredTag(QXmlStreamReader& reader);
- void handleUnknownTag(QXmlStreamReader& reader);
- void handleUselessTag(QXmlStreamReader& reader);
- void handleAnchorTag(QXmlStreamReader& reader);
- void handleRstPassTroughTag(QXmlStreamReader& reader);
-
- LinkContext *handleLinkStart(const QString &type, QString ref) const;
- void handleLinkText(LinkContext *linkContext, const QString &linktext) const;
- void handleLinkEnd(LinkContext *linkContext);
-
- typedef void (QtXmlToSphinx::*TagHandler)(QXmlStreamReader&);
- QHash<QString, TagHandler> m_handlerMap;
- QStack<TagHandler> m_handlers;
- QTextStream m_output;
- QString m_result;
-
- QStack<QString*> m_buffers;
-
-
- Table m_currentTable;
- QScopedPointer<LinkContext> m_linkContext; // for <link>
- QScopedPointer<LinkContext> m_seeAlsoContext; // for <see-also>foo()</see-also>
- bool m_tableHasHeader;
- QString m_context;
- QtDocGenerator* m_generator;
- bool m_insideBold;
- bool m_insideItalic;
- QString m_lastTagName;
- QString m_opened_anchor;
- QVector<InlineImage> m_inlineImages;
-
- QString readFromLocations(const QStringList &locations, const QString &path,
- const QString &identifier, QString *errorMessage);
- QString readFromLocation(const QString &location, const QString &identifier,
- QString *errorMessage);
- void pushOutputBuffer();
- QString popOutputBuffer();
- void writeTable(Table& table);
- bool copyImage(const QString &href) const;
-};
-
-inline QTextStream& operator<<(QTextStream& s, const QtXmlToSphinx& xmlToSphinx)
-{
- return s << xmlToSphinx.result();
-}
-
-QTextStream& operator<<(QTextStream& s, const QtXmlToSphinx::Table &table);
-
-/**
-* The DocGenerator generates documentation from library being binded.
-*/
-class QtDocGenerator : public Generator
-{
-public:
- QtDocGenerator();
- ~QtDocGenerator();
-
- QString libSourceDir() const
- {
- return m_libSourceDir;
- }
-
- QString docDataDir() const { return m_docDataDir; }
-
- bool doSetup() override;
-
- const char* name() const override
- {
- return "QtDocGenerator";
- }
-
- OptionDescriptions options() const override;
- bool handleOption(const QString &key, const QString &value) override;
-
- QStringList codeSnippetDirs() const
- {
- return m_codeSnippetDirs;
- }
-
-protected:
- bool shouldGenerate(const AbstractMetaClass *) const override;
- QString fileNameSuffix() const override;
- QString fileNameForContext(const GeneratorContext &context) const override;
- void generateClass(QTextStream &s, const GeneratorContext &classContext) override;
- bool finishGeneration() override;
-
- void writeFunctionArguments(QTextStream&, const AbstractMetaFunction*, Options) const override {}
- void writeArgumentNames(QTextStream&, const AbstractMetaFunction*, Options) const override {}
-
-private:
- void writeEnums(QTextStream& s, const AbstractMetaClass* cppClass);
-
- void writeFields(QTextStream &s, const AbstractMetaClass *cppClass);
- void writeArguments(QTextStream &s, const AbstractMetaClass *cppClass, const AbstractMetaFunction *func);
- QString functionSignature(const AbstractMetaClass* cppClass, const AbstractMetaFunction* func);
- void writeFunction(QTextStream& s, const AbstractMetaClass* cppClass,
- const AbstractMetaFunction* func);
- void writeFunctionParametersType(QTextStream &s, const AbstractMetaClass *cppClass,
- const AbstractMetaFunction* func);
- void writeFunctionList(QTextStream& s, const AbstractMetaClass* cppClass);
- void writeFunctionBlock(QTextStream& s, const QString& title, QStringList& functions);
- void writeParameterType(QTextStream &s, const AbstractMetaClass *cppClass, const AbstractMetaArgument *arg);
-
- void writeConstructors(QTextStream &s, const AbstractMetaClass *cppClass);
- void writeFormattedText(QTextStream &s, const Documentation &doc,
- const AbstractMetaClass *metaclass = nullptr);
- bool writeInjectDocumentation(QTextStream& s, TypeSystem::DocModificationMode mode, const AbstractMetaClass* cppClass, const AbstractMetaFunction* func);
- void writeDocSnips(QTextStream &s, const CodeSnipList &codeSnips, TypeSystem::CodeSnipPosition position, TypeSystem::Language language);
-
- void writeModuleDocumentation();
- void writeAdditionalDocumentation();
-
- QString parseArgDocStyle(const AbstractMetaClass *cppClass, const AbstractMetaFunction *func);
- QString translateToPythonType(const AbstractMetaType *type, const AbstractMetaClass *cppClass);
-
- QString m_docDataDir;
- QString m_libSourceDir;
- QStringList m_codeSnippetDirs;
- QString m_extraSectionDir;
- QStringList m_functionList;
- QMap<QString, QStringList> m_packages;
- DocParser* m_docParser;
- QString m_additionalDocumentationList;
-};
-
-#endif // DOCGENERATOR_H
diff --git a/sources/shiboken2/generator/shiboken2/cppgenerator.cpp b/sources/shiboken2/generator/shiboken2/cppgenerator.cpp
deleted file mode 100644
index 4c637e701..000000000
--- a/sources/shiboken2/generator/shiboken2/cppgenerator.cpp
+++ /dev/null
@@ -1,6181 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <memory>
-
-#include "cppgenerator.h"
-#include "fileout.h"
-#include "overloaddata.h"
-#include <abstractmetalang.h>
-#include <messages.h>
-#include <reporthandler.h>
-#include <typedatabase.h>
-
-#include <QtCore/QDir>
-#include <QtCore/QMetaObject>
-#include <QtCore/QRegularExpression>
-#include <QtCore/QTextStream>
-#include <QtCore/QDebug>
-#include <QMetaType>
-
-#include <algorithm>
-#include <cstring>
-
-static const char CPP_ARG0[] = "cppArg0";
-
-QHash<QString, QString> CppGenerator::m_nbFuncs = QHash<QString, QString>();
-QHash<QString, QString> CppGenerator::m_sqFuncs = QHash<QString, QString>();
-QHash<QString, QString> CppGenerator::m_mpFuncs = QHash<QString, QString>();
-QString CppGenerator::m_currentErrorCode(QLatin1String("{}"));
-
-static const char typeNameFunc[] = R"CPP(
-template <class T>
-static const char *typeNameOf(const T &t)
-{
- const char *typeName = typeid(t).name();
- auto size = std::strlen(typeName);
-#if defined(Q_CC_MSVC) // MSVC: "class QPaintDevice * __ptr64"
- if (auto lastStar = strchr(typeName, '*')) {
- // MSVC: "class QPaintDevice * __ptr64"
- while (*--lastStar == ' ') {
- }
- size = lastStar - typeName + 1;
- }
-#else // g++, Clang: "QPaintDevice *" -> "P12QPaintDevice"
- if (size > 2 && typeName[0] == 'P' && std::isdigit(typeName[1])) {
- ++typeName;
- --size;
- }
-#endif
- char *result = new char[size + 1];
- result[size] = '\0';
- memcpy(result, typeName, size);
- return result;
-}
-)CPP";
-
-// utility functions
-inline AbstractMetaType *getTypeWithoutContainer(AbstractMetaType *arg)
-{
- if (arg && arg->typeEntry()->isContainer()) {
- AbstractMetaTypeList lst = arg->instantiations();
- // only support containers with 1 type
- if (lst.size() == 1)
- return lst[0];
- }
- return arg;
-}
-
-// A helper for writing C++ return statements for either void ("return;")
-// or some return value ("return value;")
-class returnStatement
-{
-public:
- explicit returnStatement(QString s) : m_returnValue(std::move(s)) {}
-
- friend QTextStream &operator<<(QTextStream &s, const returnStatement &r);
-
-private:
- const QString m_returnValue;
-};
-
-QTextStream &operator<<(QTextStream &s, const returnStatement &r)
-{
- s << "return";
- if (!r.m_returnValue.isEmpty())
- s << ' ' << r.m_returnValue;
- s << ';';
- return s;
-}
-
-CppGenerator::CppGenerator()
-{
- // Number protocol structure members names
- m_nbFuncs.insert(QLatin1String("__add__"), QLatin1String("nb_add"));
- m_nbFuncs.insert(QLatin1String("__sub__"), QLatin1String("nb_subtract"));
- m_nbFuncs.insert(QLatin1String("__mul__"), QLatin1String("nb_multiply"));
- m_nbFuncs.insert(QLatin1String("__div__"), QLatin1String("nb_divide"));
- m_nbFuncs.insert(QLatin1String("__mod__"), QLatin1String("nb_remainder"));
- m_nbFuncs.insert(QLatin1String("__neg__"), QLatin1String("nb_negative"));
- m_nbFuncs.insert(QLatin1String("__pos__"), QLatin1String("nb_positive"));
- m_nbFuncs.insert(QLatin1String("__invert__"), QLatin1String("nb_invert"));
- m_nbFuncs.insert(QLatin1String("__lshift__"), QLatin1String("nb_lshift"));
- m_nbFuncs.insert(QLatin1String("__rshift__"), QLatin1String("nb_rshift"));
- m_nbFuncs.insert(QLatin1String("__and__"), QLatin1String("nb_and"));
- m_nbFuncs.insert(QLatin1String("__xor__"), QLatin1String("nb_xor"));
- m_nbFuncs.insert(QLatin1String("__or__"), QLatin1String("nb_or"));
- m_nbFuncs.insert(QLatin1String("__iadd__"), QLatin1String("nb_inplace_add"));
- m_nbFuncs.insert(QLatin1String("__isub__"), QLatin1String("nb_inplace_subtract"));
- m_nbFuncs.insert(QLatin1String("__imul__"), QLatin1String("nb_inplace_multiply"));
- m_nbFuncs.insert(QLatin1String("__idiv__"), QLatin1String("nb_inplace_divide"));
- m_nbFuncs.insert(QLatin1String("__imod__"), QLatin1String("nb_inplace_remainder"));
- m_nbFuncs.insert(QLatin1String("__ilshift__"), QLatin1String("nb_inplace_lshift"));
- m_nbFuncs.insert(QLatin1String("__irshift__"), QLatin1String("nb_inplace_rshift"));
- m_nbFuncs.insert(QLatin1String("__iand__"), QLatin1String("nb_inplace_and"));
- m_nbFuncs.insert(QLatin1String("__ixor__"), QLatin1String("nb_inplace_xor"));
- m_nbFuncs.insert(QLatin1String("__ior__"), QLatin1String("nb_inplace_or"));
- m_nbFuncs.insert(QLatin1String("bool"), QLatin1String("nb_nonzero"));
-
- // sequence protocol functions
- m_sequenceProtocol.insert(QLatin1String("__len__"),
- {QLatin1String("PyObject *self"),
- QLatin1String("Py_ssize_t")});
- m_sequenceProtocol.insert(QLatin1String("__getitem__"),
- {QLatin1String("PyObject *self, Py_ssize_t _i"),
- QLatin1String("PyObject*")});
- m_sequenceProtocol.insert(QLatin1String("__setitem__"),
- {QLatin1String("PyObject *self, Py_ssize_t _i, PyObject *_value"),
- QLatin1String("int")});
- m_sequenceProtocol.insert(QLatin1String("__getslice__"),
- {QLatin1String("PyObject *self, Py_ssize_t _i1, Py_ssize_t _i2"),
- QLatin1String("PyObject*")});
- m_sequenceProtocol.insert(QLatin1String("__setslice__"),
- {QLatin1String("PyObject *self, Py_ssize_t _i1, Py_ssize_t _i2, PyObject *_value"),
- QLatin1String("int")});
- m_sequenceProtocol.insert(QLatin1String("__contains__"),
- {QLatin1String("PyObject *self, PyObject *_value"),
- QLatin1String("int")});
- m_sequenceProtocol.insert(QLatin1String("__concat__"),
- {QLatin1String("PyObject *self, PyObject *_other"),
- QLatin1String("PyObject*")});
-
- // Sequence protocol structure members names
- m_sqFuncs.insert(QLatin1String("__concat__"), QLatin1String("sq_concat"));
- m_sqFuncs.insert(QLatin1String("__contains__"), QLatin1String("sq_contains"));
- m_sqFuncs.insert(QLatin1String("__getitem__"), QLatin1String("sq_item"));
- m_sqFuncs.insert(QLatin1String("__getslice__"), QLatin1String("sq_slice"));
- m_sqFuncs.insert(QLatin1String("__len__"), QLatin1String("sq_length"));
- m_sqFuncs.insert(QLatin1String("__setitem__"), QLatin1String("sq_ass_item"));
- m_sqFuncs.insert(QLatin1String("__setslice__"), QLatin1String("sq_ass_slice"));
-
- // mapping protocol function
- m_mappingProtocol.insert(QLatin1String("__mlen__"),
- {QLatin1String("PyObject *self"),
- QLatin1String("Py_ssize_t")});
- m_mappingProtocol.insert(QLatin1String("__mgetitem__"),
- {QLatin1String("PyObject *self, PyObject *_key"),
- QLatin1String("PyObject*")});
- m_mappingProtocol.insert(QLatin1String("__msetitem__"),
- {QLatin1String("PyObject *self, PyObject *_key, PyObject *_value"),
- QLatin1String("int")});
-
- // Sequence protocol structure members names
- m_mpFuncs.insert(QLatin1String("__mlen__"), QLatin1String("mp_length"));
- m_mpFuncs.insert(QLatin1String("__mgetitem__"), QLatin1String("mp_subscript"));
- m_mpFuncs.insert(QLatin1String("__msetitem__"), QLatin1String("mp_ass_subscript"));
-}
-
-QString CppGenerator::fileNameSuffix() const
-{
- return QLatin1String("_wrapper.cpp");
-}
-
-QString CppGenerator::fileNameForContext(const GeneratorContext &context) const
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- if (!context.forSmartPointer()) {
- QString fileNameBase = metaClass->qualifiedCppName().toLower();
- fileNameBase.replace(QLatin1String("::"), QLatin1String("_"));
- return fileNameBase + fileNameSuffix();
- }
- const AbstractMetaType *smartPointerType = context.preciseType();
- QString fileNameBase = getFileNameBaseForSmartPointer(smartPointerType, metaClass);
- return fileNameBase + fileNameSuffix();
-}
-
-QVector<AbstractMetaFunctionList> CppGenerator::filterGroupedOperatorFunctions(const AbstractMetaClass *metaClass,
- uint queryIn)
-{
- // ( func_name, num_args ) => func_list
- QMap<QPair<QString, int>, AbstractMetaFunctionList> results;
- const AbstractMetaClass::OperatorQueryOptions query(queryIn);
- const AbstractMetaFunctionList &funcs = metaClass->operatorOverloads(query);
- for (AbstractMetaFunction *func : funcs) {
- if (func->isModifiedRemoved()
- || func->usesRValueReferences()
- || func->name() == QLatin1String("operator[]")
- || func->name() == QLatin1String("operator->")
- || func->name() == QLatin1String("operator!")) {
- continue;
- }
- int args;
- if (func->isComparisonOperator()) {
- args = -1;
- } else {
- args = func->arguments().size();
- }
- QPair<QString, int > op(func->name(), args);
- results[op].append(func);
- }
- QVector<AbstractMetaFunctionList> result;
- result.reserve(results.size());
- for (auto it = results.cbegin(), end = results.cend(); it != end; ++it)
- result.append(it.value());
- return result;
-}
-
-const AbstractMetaFunction *CppGenerator::boolCast(const AbstractMetaClass *metaClass) const
-{
- if (!useIsNullAsNbNonZero())
- return nullptr;
- // TODO: This could be configurable someday
- const AbstractMetaFunction *func = metaClass->findFunction(QLatin1String("isNull"));
- if (!func || !func->type() || !func->type()->typeEntry()->isPrimitive() || !func->isPublic())
- return nullptr;
- auto pte = static_cast<const PrimitiveTypeEntry *>(func->type()->typeEntry());
- while (pte->referencedTypeEntry())
- pte = pte->referencedTypeEntry();
- return func && func->isConstant() && pte->name() == QLatin1String("bool")
- && func->arguments().isEmpty() ? func : nullptr;
-}
-
-using FunctionGroupMap = QMap<QString, AbstractMetaFunctionList>;
-
-// Prevent ELF symbol qt_version_tag from being generated into the source
-static const char includeQDebug[] =
-"#ifndef QT_NO_VERSION_TAGGING\n"
-"# define QT_NO_VERSION_TAGGING\n"
-"#endif\n"
-"#include <QDebug>\n";
-
-static QString chopType(QString s)
-{
- if (s.endsWith(QLatin1String("_Type")))
- s.chop(5);
- else if (s.endsWith(QLatin1String("_TypeF()")))
- s.chop(8);
- return s;
-}
-
-// Helper for field setters: Check for "const QWidget *" (settable field),
-// but not "int *const" (read-only field).
-static bool isPointerToConst(const AbstractMetaType *t)
-{
- const AbstractMetaType::Indirections &indirections = t->indirectionsV();
- return t->isConstant() && !indirections.isEmpty()
- && indirections.constLast() != Indirection::ConstPointer;
-}
-
-static inline bool canGenerateFieldSetter(const AbstractMetaField *field)
-{
- const AbstractMetaType *type = field->type();
- return !type->isConstant() || isPointerToConst(type);
-}
-
-/*!
- Function used to write the class generated binding code on the buffer
- \param s the output buffer
- \param metaClass the pointer to metaclass information
-*/
-void CppGenerator::generateClass(QTextStream &s, const GeneratorContext &classContext)
-{
- const AbstractMetaClass *metaClass = classContext.metaClass();
-
- // write license comment
- s << licenseComment() << Qt::endl;
-
- if (!avoidProtectedHack() && !metaClass->isNamespace() && !metaClass->hasPrivateDestructor()) {
- s << "//workaround to access protected functions\n";
- s << "#define protected public\n\n";
- }
-
- // headers
- s << "// default includes\n";
- s << "#include <shiboken.h>\n";
- if (usePySideExtensions()) {
- s << includeQDebug;
- s << "#include <pysidesignal.h>\n"
- << "#include <pysideproperty.h>\n"
- << "#include <pyside.h>\n"
- << "#include <qapp_macro.h>\n\n"
- << "QT_WARNING_DISABLE_DEPRECATED\n\n";
- }
-
- s << "#include <typeinfo>\n";
- if (usePySideExtensions() && metaClass->isQObject()) {
- s << "#include <signalmanager.h>\n";
- s << "#include <pysidemetafunction.h>\n";
- }
-
- // The multiple inheritance initialization function
- // needs the 'set' class from C++ STL.
- if (getMultipleInheritingClass(metaClass) != nullptr)
- s << "#include <algorithm>\n#include <set>\n";
- if (metaClass->generateExceptionHandling())
- s << "#include <exception>\n";
- s << "#include <iterator>\n"; // For containers
-
- if (wrapperDiagnostics())
- s << "#include <helper.h>\n#include <iostream>\n";
-
- s << "\n// module include\n" << "#include \"" << getModuleHeaderFileName() << "\"\n";
-
- QString headerfile = fileNameForContext(classContext);
- headerfile.replace(QLatin1String(".cpp"), QLatin1String(".h"));
- s << "\n// main header\n" << "#include \"" << headerfile << "\"\n";
-
- s << Qt::endl << "// inner classes\n";
- const AbstractMetaClassList &innerClasses = metaClass->innerClasses();
- for (AbstractMetaClass *innerClass : innerClasses) {
- GeneratorContext innerClassContext = contextForClass(innerClass);
- if (shouldGenerate(innerClass) && !innerClass->typeEntry()->isSmartPointer()) {
- QString headerfile = fileNameForContext(innerClassContext);
- headerfile.replace(QLatin1String(".cpp"), QLatin1String(".h"));
- s << "#include \"" << headerfile << "\"\n";
- }
- }
-
- AbstractMetaEnumList classEnums = metaClass->enums();
- for (AbstractMetaClass *innerClass : innerClasses)
- lookForEnumsInClassesNotToBeGenerated(classEnums, innerClass);
-
- //Extra includes
- s << "\n// Extra includes\n";
- QVector<Include> includes = metaClass->typeEntry()->extraIncludes();
- for (AbstractMetaEnum *cppEnum : qAsConst(classEnums))
- includes.append(cppEnum->typeEntry()->extraIncludes());
- std::sort(includes.begin(), includes.end());
- for (const Include &inc : qAsConst(includes))
- s << inc.toString() << Qt::endl;
- s << Qt::endl;
-
- s << "\n#include <cctype>\n#include <cstring>\n";
-
- if (metaClass->typeEntry()->typeFlags() & ComplexTypeEntry::Deprecated)
- s << "#Deprecated\n";
-
- // Use class base namespace
- {
- const AbstractMetaClass *context = metaClass->enclosingClass();
- while (context) {
- if (context->isNamespace() && !context->enclosingClass()) {
- s << "using namespace " << context->qualifiedCppName() << ";\n";
- break;
- }
- context = context->enclosingClass();
- }
- }
-
- s << Qt::endl << Qt::endl << typeNameFunc << Qt::endl;
-
- // Create string literal for smart pointer getter method.
- if (classContext.forSmartPointer()) {
- const auto *typeEntry =
- static_cast<const SmartPointerTypeEntry *>(classContext.preciseType()
- ->typeEntry());
- QString rawGetter = typeEntry->getter();
- s << "static const char * " << SMART_POINTER_GETTER << " = \"" << rawGetter << "\";";
- }
-
- // class inject-code native/beginning
- if (!metaClass->typeEntry()->codeSnips().isEmpty()) {
- writeClassCodeSnips(s, metaClass->typeEntry()->codeSnips(),
- TypeSystem::CodeSnipPositionBeginning, TypeSystem::NativeCode,
- classContext);
- s << Qt::endl;
- }
-
- // python conversion rules
- if (metaClass->typeEntry()->hasTargetConversionRule()) {
- s << "// Python Conversion\n";
- s << metaClass->typeEntry()->conversionRule() << Qt::endl;
- }
-
- if (classContext.useWrapper()) {
- s << "// Native ---------------------------------------------------------\n\n";
-
- if (avoidProtectedHack() && usePySideExtensions()) {
- s << "void " << classContext.wrapperName() << "::pysideInitQtMetaTypes()\n{\n";
- Indentation indent(INDENT);
- writeInitQtMetaTypeFunctionBody(s, classContext);
- s << "}\n\n";
- }
-
- const AbstractMetaFunctionList &funcs = filterFunctions(metaClass);
- int maxOverrides = 0;
- writeCacheResetNative(s, classContext);
- for (const AbstractMetaFunction *func : funcs) {
- const bool notAbstract = !func->isAbstract();
- if ((func->isPrivate() && notAbstract && !visibilityModifiedToPrivate(func))
- || (func->isModifiedRemoved() && notAbstract))
- continue;
- if (func->functionType() == AbstractMetaFunction::ConstructorFunction && !func->isUserAdded())
- writeConstructorNative(s, classContext, func);
- else if (shouldWriteVirtualMethodNative(func))
- writeVirtualMethodNative(s, func, maxOverrides++);
- }
-
- if (!avoidProtectedHack() || !metaClass->hasPrivateDestructor()) {
- if (usePySideExtensions() && metaClass->isQObject())
- writeMetaObjectMethod(s, classContext);
- writeDestructorNative(s, classContext);
- }
- }
-
- Indentation indentation(INDENT);
-
- QString methodsDefinitions;
- QTextStream md(&methodsDefinitions);
- QString singleMethodDefinitions;
- QTextStream smd(&singleMethodDefinitions);
- QString signaturesString;
- QTextStream signatureStream(&signaturesString);
-
- s << "\n// Target ---------------------------------------------------------\n\n"
- << "extern \"C\" {\n";
- const auto &functionGroups = getFunctionGroups(metaClass);
- for (auto it = functionGroups.cbegin(), end = functionGroups.cend(); it != end; ++it) {
- AbstractMetaFunctionList overloads;
- QSet<QString> seenSignatures;
- bool staticEncountered = false;
- for (AbstractMetaFunction *func : it.value()) {
- if (!func->isAssignmentOperator()
- && !func->usesRValueReferences()
- && !func->isCastOperator()
- && !func->isModifiedRemoved()
- && (!func->isPrivate() || func->functionType() == AbstractMetaFunction::EmptyFunction)
- && func->ownerClass() == func->implementingClass()
- && (func->name() != QLatin1String("qt_metacall"))) {
- // PYSIDE-331: Inheritance works correctly when there are disjoint functions.
- // But when a function is both in a class and inherited in a subclass,
- // then we need to search through all subclasses and collect the new signatures.
- overloads << getFunctionAndInheritedOverloads(func, &seenSignatures);
- if (func->isStatic())
- staticEncountered = true;
- }
- }
- // PYSIDE-886: If the method does not have any static overloads declared
- // in the class in question, remove all inherited static methods as setting
- // METH_STATIC in that case can cause crashes for the instance methods.
- // Manifested as crash when calling QPlainTextEdit::find() (clash with
- // static QWidget::find(WId)).
- if (!staticEncountered) {
- for (int i = overloads.size() - 1; i >= 0; --i) {
- if (overloads.at(i)->isStatic())
- delete overloads.takeAt(i);
- }
- }
-
- if (overloads.isEmpty())
- continue;
-
- const AbstractMetaFunction *rfunc = overloads.constFirst();
- if (m_sequenceProtocol.contains(rfunc->name()) || m_mappingProtocol.contains(rfunc->name()))
- continue;
-
- if (rfunc->isConstructor()) {
- // @TODO: Implement constructor support for smart pointers, so that they can be
- // instantiated in python code.
- if (classContext.forSmartPointer())
- continue;
- writeConstructorWrapper(s, overloads, classContext);
- writeSignatureInfo(signatureStream, overloads);
- }
- // call operators
- else if (rfunc->name() == QLatin1String("operator()")) {
- writeMethodWrapper(s, overloads, classContext);
- writeSignatureInfo(signatureStream, overloads);
- }
- else if (!rfunc->isOperatorOverload()) {
-
- if (classContext.forSmartPointer()) {
- const auto *smartPointerTypeEntry =
- static_cast<const SmartPointerTypeEntry *>(
- classContext.preciseType()->typeEntry());
-
- if (smartPointerTypeEntry->getter() == rfunc->name()) {
- // Replace the return type of the raw pointer getter method with the actual
- // return type.
- QString innerTypeName =
- classContext.preciseType()->getSmartPointerInnerType()->cppSignature();
- QString pointerToInnerTypeName = innerTypeName + QLatin1Char('*');
- // @TODO: This possibly leaks, but there are a bunch of other places where this
- // is done, so this will be fixed in bulk with all the other cases, because the
- // ownership of the pointers is not clear at the moment.
- AbstractMetaType *pointerToInnerType =
- buildAbstractMetaTypeFromString(pointerToInnerTypeName);
-
- AbstractMetaFunction *mutableRfunc = overloads.constFirst();
- mutableRfunc->replaceType(pointerToInnerType);
- } else if (smartPointerTypeEntry->refCountMethodName().isEmpty()
- || smartPointerTypeEntry->refCountMethodName() != rfunc->name()) {
- // Skip all public methods of the smart pointer except for the raw getter and
- // the ref count method.
- continue;
- }
- }
-
- writeMethodWrapper(s, overloads, classContext);
- writeSignatureInfo(signatureStream, overloads);
- if (OverloadData::hasStaticAndInstanceFunctions(overloads)) {
- QString methDefName = cpythonMethodDefinitionName(rfunc);
- smd << "static PyMethodDef " << methDefName << " = {\n";
- smd << INDENT;
- writeMethodDefinitionEntry(smd, overloads);
- smd << "\n};\n\n";
- }
- writeMethodDefinition(md, overloads);
- }
- }
-
- const QString className = chopType(cpythonTypeName(metaClass));
-
- if (metaClass->typeEntry()->isValue() || metaClass->typeEntry()->isSmartPointer()) {
- writeCopyFunction(s, classContext);
- signatureStream << fullPythonClassName(metaClass) << ".__copy__()\n";
- }
-
- // Write single method definitions
- s << singleMethodDefinitions;
-
- // Write methods definition
- s << "static PyMethodDef " << className << "_methods[] = {\n";
- s << methodsDefinitions << Qt::endl;
- if (metaClass->typeEntry()->isValue() || metaClass->typeEntry()->isSmartPointer()) {
- s << INDENT << "{\"__copy__\", reinterpret_cast<PyCFunction>(" << className << "___copy__)"
- << ", METH_NOARGS},\n";
- }
- s << INDENT << '{' << NULL_PTR << ", " << NULL_PTR << "} // Sentinel\n";
- s << "};\n\n";
-
- // Write tp_s/getattro function
- const AttroCheck attroCheck = checkAttroFunctionNeeds(metaClass);
- if (attroCheck.testFlag(AttroCheckFlag::GetattroSmartPointer)) {
- writeSmartPointerGetattroFunction(s, classContext);
- writeSmartPointerSetattroFunction(s, classContext);
- } else {
- if ((attroCheck & AttroCheckFlag::GetattroMask) != 0)
- writeGetattroFunction(s, attroCheck, classContext);
- if ((attroCheck & AttroCheckFlag::SetattroMask) != 0)
- writeSetattroFunction(s, attroCheck, classContext);
- }
-
- if (const AbstractMetaFunction *f = boolCast(metaClass)) {
- ErrorCode errorCode(-1);
- s << "static int " << cpythonBaseName(metaClass) << "___nb_bool(PyObject *self)\n"
- << "{\n";
- writeCppSelfDefinition(s, classContext);
- if (f->allowThread()) {
- s << INDENT << "int result;\n";
- s << INDENT << BEGIN_ALLOW_THREADS << Qt::endl;
- s << INDENT << "result = !" << CPP_SELF_VAR << "->isNull();\n";
- s << INDENT << END_ALLOW_THREADS << Qt::endl;
- s << INDENT << "return result;\n";
- } else {
- s << INDENT << "return !" << CPP_SELF_VAR << "->isNull();\n";
- }
- s << "}\n\n";
- }
-
- if (supportsNumberProtocol(metaClass) && !metaClass->typeEntry()->isSmartPointer()) {
- const QVector<AbstractMetaFunctionList> opOverloads = filterGroupedOperatorFunctions(
- metaClass,
- AbstractMetaClass::ArithmeticOp
- | AbstractMetaClass::LogicalOp
- | AbstractMetaClass::BitwiseOp);
-
- for (const AbstractMetaFunctionList &allOverloads : opOverloads) {
- AbstractMetaFunctionList overloads;
- for (AbstractMetaFunction *func : allOverloads) {
- if (!func->isModifiedRemoved()
- && !func->isPrivate()
- && (func->ownerClass() == func->implementingClass() || func->isAbstract()))
- overloads.append(func);
- }
-
- if (overloads.isEmpty())
- continue;
-
- writeMethodWrapper(s, overloads, classContext);
- writeSignatureInfo(signatureStream, overloads);
- }
- }
-
- if (supportsSequenceProtocol(metaClass)) {
- writeSequenceMethods(s, metaClass, classContext);
- }
-
- if (supportsMappingProtocol(metaClass)) {
- writeMappingMethods(s, metaClass, classContext);
- }
-
- if (!metaClass->isNamespace() && metaClass->hasComparisonOperatorOverload()) {
- s << "// Rich comparison\n";
- writeRichCompareFunction(s, classContext);
- }
-
- if (shouldGenerateGetSetList(metaClass) && !classContext.forSmartPointer()) {
- const AbstractMetaFieldList &fields = metaClass->fields();
- for (const AbstractMetaField *metaField : fields) {
- if (metaField->isStatic())
- continue;
- writeGetterFunction(s, metaField, classContext);
- if (canGenerateFieldSetter(metaField))
- writeSetterFunction(s, metaField, classContext);
- s << Qt::endl;
- }
-
- s << "// Getters and Setters for " << metaClass->name() << Qt::endl;
- s << "static PyGetSetDef " << cpythonGettersSettersDefinitionName(metaClass) << "[] = {\n";
- for (const AbstractMetaField *metaField : fields) {
- if (metaField->isStatic())
- continue;
-
- s << INDENT << "{const_cast<char *>(\"" << metaField->name() << "\"), ";
- s << cpythonGetterFunctionName(metaField) << ", ";
- if (canGenerateFieldSetter(metaField))
- s << cpythonSetterFunctionName(metaField);
- else
- s << NULL_PTR;
- s << "},\n";
- }
- s << INDENT << '{' << NULL_PTR << "} // Sentinel\n";
- s << "};\n\n";
- }
-
- s << "} // extern \"C\"\n\n";
-
- if (!metaClass->typeEntry()->hashFunction().isEmpty())
- writeHashFunction(s, classContext);
-
- // Write tp_traverse and tp_clear functions.
- writeTpTraverseFunction(s, metaClass);
- writeTpClearFunction(s, metaClass);
-
- writeClassDefinition(s, metaClass, classContext);
- s << Qt::endl;
-
- if (metaClass->isPolymorphic() && metaClass->baseClass())
- writeTypeDiscoveryFunction(s, metaClass);
-
-
- for (AbstractMetaEnum *cppEnum : qAsConst(classEnums)) {
- if (cppEnum->isAnonymous() || cppEnum->isPrivate())
- continue;
-
- bool hasFlags = cppEnum->typeEntry()->flags();
- if (hasFlags) {
- writeFlagsMethods(s, cppEnum);
- writeFlagsNumberMethodsDefinition(s, cppEnum);
- s << Qt::endl;
- }
- }
- s << Qt::endl;
-
- writeConverterFunctions(s, metaClass, classContext);
- writeClassRegister(s, metaClass, classContext, signatureStream);
-
- // class inject-code native/end
- if (!metaClass->typeEntry()->codeSnips().isEmpty()) {
- writeClassCodeSnips(s, metaClass->typeEntry()->codeSnips(),
- TypeSystem::CodeSnipPositionEnd, TypeSystem::NativeCode,
- classContext);
- s << Qt::endl;
- }
-}
-
-void CppGenerator::writeCacheResetNative(QTextStream &s, const GeneratorContext &classContext)
-{
- Indentation indentation(INDENT);
- s << "void " << classContext.wrapperName()
- << "::resetPyMethodCache()\n{\n";
- s << INDENT << "std::fill_n(m_PyMethodCache, sizeof(m_PyMethodCache) / sizeof(m_PyMethodCache[0]), false);\n";
- s << "}\n\n";
-}
-
-void CppGenerator::writeConstructorNative(QTextStream &s, const GeneratorContext &classContext,
- const AbstractMetaFunction *func)
-{
- Indentation indentation(INDENT);
- const QString qualifiedName = classContext.wrapperName() + QLatin1String("::");
- s << functionSignature(func, qualifiedName, QString(),
- OriginalTypeDescription | SkipDefaultValues);
- s << " : ";
- writeFunctionCall(s, func);
- s << "\n{\n";
- if (wrapperDiagnostics())
- s << INDENT << R"(std::cerr << __FUNCTION__ << ' ' << this << '\n';)" << '\n';
- const AbstractMetaArgument *lastArg = func->arguments().isEmpty() ? nullptr : func->arguments().constLast();
- s << INDENT << "resetPyMethodCache();\n";
- writeCodeSnips(s, func->injectedCodeSnips(), TypeSystem::CodeSnipPositionBeginning, TypeSystem::NativeCode, func, lastArg);
- s << INDENT << "// ... middle\n";
- writeCodeSnips(s, func->injectedCodeSnips(), TypeSystem::CodeSnipPositionEnd, TypeSystem::NativeCode, func, lastArg);
- s << "}\n\n";
-}
-
-void CppGenerator::writeDestructorNative(QTextStream &s, const GeneratorContext &classContext)
-{
- Indentation indentation(INDENT);
- s << classContext.wrapperName() << "::~"
- << classContext.wrapperName() << "()\n{\n";
- if (wrapperDiagnostics())
- s << INDENT << R"(std::cerr << __FUNCTION__ << ' ' << this << '\n';)" << '\n';
- // kill pyobject
- s << INDENT << "SbkObject *wrapper = Shiboken::BindingManager::instance().retrieveWrapper(this);\n";
- s << INDENT << "Shiboken::Object::destroy(wrapper, this);\n";
- s << "}\n";
-}
-
-static bool allArgumentsRemoved(const AbstractMetaFunction *func)
-{
- if (func->arguments().isEmpty())
- return false;
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- if (!func->argumentRemoved(arg->argumentIndex() + 1))
- return false;
- }
- return true;
-}
-
-QString CppGenerator::getVirtualFunctionReturnTypeName(const AbstractMetaFunction *func)
-{
- if (!func->type())
- return QLatin1String("\"\"");
-
- if (!func->typeReplaced(0).isEmpty())
- return QLatin1Char('"') + func->typeReplaced(0) + QLatin1Char('"');
-
- // SbkType would return null when the type is a container.
- auto typeEntry = func->type()->typeEntry();
- if (typeEntry->isContainer()) {
- return QLatin1Char('"')
- + reinterpret_cast<const ContainerTypeEntry *>(typeEntry)->typeName()
- + QLatin1Char('"');
- }
- if (typeEntry->isSmartPointer())
- return QLatin1Char('"') + typeEntry->qualifiedCppName() + QLatin1Char('"');
-
- if (avoidProtectedHack()) {
- const AbstractMetaEnum *metaEnum = findAbstractMetaEnum(func->type());
- if (metaEnum && metaEnum->isProtected())
- return QLatin1Char('"') + protectedEnumSurrogateName(metaEnum) + QLatin1Char('"');
- }
-
- if (func->type()->isPrimitive())
- return QLatin1Char('"') + func->type()->name() + QLatin1Char('"');
-
- return QLatin1String("reinterpret_cast<PyTypeObject *>(Shiboken::SbkType< ")
- + typeEntry->qualifiedCppName() + QLatin1String(" >())->tp_name");
-}
-
-void CppGenerator::writeVirtualMethodNative(QTextStream &s,
- const AbstractMetaFunction *func,
- int cacheIndex)
-{
- //skip metaObject function, this will be written manually ahead
- if (usePySideExtensions() && func->ownerClass() && func->ownerClass()->isQObject() &&
- ((func->name() == QLatin1String("metaObject")) || (func->name() == QLatin1String("qt_metacall"))))
- return;
-
- const TypeEntry *retType = func->type() ? func->type()->typeEntry() : nullptr;
- const QString funcName = func->isOperatorOverload() ? pythonOperatorFunctionName(func) : func->name();
-
- QString prefix = wrapperName(func->ownerClass()) + QLatin1String("::");
- s << functionSignature(func, prefix, QString(), Generator::SkipDefaultValues|Generator::OriginalTypeDescription)
- << "\n{\n";
-
- Indentation indentation(INDENT);
-
- DefaultValue defaultReturnExpr;
- if (retType) {
- const FunctionModificationList &mods = func->modifications();
- for (const FunctionModification &mod : mods) {
- for (const ArgumentModification &argMod : mod.argument_mods) {
- if (argMod.index == 0 && !argMod.replacedDefaultExpression.isEmpty()) {
- static const QRegularExpression regex(QStringLiteral("%(\\d+)"));
- Q_ASSERT(regex.isValid());
- QString expr = argMod.replacedDefaultExpression;
- for (int offset = 0; ; ) {
- const QRegularExpressionMatch match = regex.match(expr, offset);
- if (!match.hasMatch())
- break;
- const int argId = match.capturedRef(1).toInt() - 1;
- if (argId < 0 || argId > func->arguments().count()) {
- qCWarning(lcShiboken) << "The expression used in return value contains an invalid index.";
- break;
- }
- expr.replace(match.captured(0), func->arguments().at(argId)->name());
- offset = match.capturedStart(1);
- }
- defaultReturnExpr.setType(DefaultValue::Custom);
- defaultReturnExpr.setValue(expr);
- }
- }
- }
- if (!defaultReturnExpr.isValid())
- defaultReturnExpr = minimalConstructor(func->type());
- if (!defaultReturnExpr.isValid()) {
- QString errorMsg = QLatin1String(__FUNCTION__) + QLatin1String(": ");
- if (const AbstractMetaClass *c = func->implementingClass())
- errorMsg += c->qualifiedCppName() + QLatin1String("::");
- errorMsg += func->signature();
- errorMsg = msgCouldNotFindMinimalConstructor(errorMsg, func->type()->cppSignature());
- qCWarning(lcShiboken).noquote().nospace() << errorMsg;
- s << Qt::endl << INDENT << "#error " << errorMsg << Qt::endl;
- }
- } else {
- defaultReturnExpr.setType(DefaultValue::Void);
- }
-
- if (func->isAbstract() && func->isModifiedRemoved()) {
- qCWarning(lcShiboken).noquote().nospace()
- << QString::fromLatin1("Pure virtual method '%1::%2' must be implement but was "\
- "completely removed on type system.")
- .arg(func->ownerClass()->name(), func->minimalSignature());
- s << INDENT << returnStatement(defaultReturnExpr.returnValue()) << Qt::endl;
- s << "}\n\n";
- return;
- }
-
- //Write declaration/native injected code
- if (func->hasInjectedCode()) {
- CodeSnipList snips = func->injectedCodeSnips();
- const AbstractMetaArgument *lastArg = func->arguments().isEmpty() ? nullptr : func->arguments().constLast();
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionDeclaration, TypeSystem::NativeCode, func, lastArg);
- s << Qt::endl;
- }
-
- // PYSIDE-803: Build a boolean cache for unused overrides.
- bool multi_line = retType == nullptr; // set to true when using instrumentation
- if (wrapperDiagnostics()) {
- s << INDENT << "std::cerr << ";
-#ifndef Q_CC_MSVC // g++ outputs __FUNCTION__ unqualified
- s << '"' << prefix << R"(" << )";
-#endif
- s << R"(__FUNCTION__ << ' ' << this << " m_PyMethodCache[" << )"
- << cacheIndex << R"( << "]=" << m_PyMethodCache[)" << cacheIndex
- << R"(] << '\n';)" << '\n';
- }
- s << INDENT << "if (m_PyMethodCache[" << cacheIndex << "])" << (multi_line ? " {\n" : "\n");
- {
- Indentation indentation(INDENT);
- s << INDENT;
- if (retType)
- s << "return ";
- if (!func->isAbstract()) {
- s << "this->::" << func->implementingClass()->qualifiedCppName() << "::";
- writeFunctionCall(s, func, Generator::VirtualCall);
- } else {
- if (retType)
- s << ' ' << defaultReturnExpr.returnValue();
- }
- if (!retType)
- s << ";\n" << INDENT << "return";
- s << ";\n";
- }
- if (multi_line)
- s << INDENT << "}\n";
-
- s << INDENT << "Shiboken::GilState gil;\n";
-
- // Get out of virtual method call if someone already threw an error.
- s << INDENT << "if (PyErr_Occurred())\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << returnStatement(defaultReturnExpr.returnValue()) << Qt::endl;
- }
-
- s << INDENT << "Shiboken::AutoDecRef " << PYTHON_OVERRIDE_VAR << "(Shiboken::BindingManager::instance().getOverride(this, \"";
- s << funcName << "\"));\n";
-
- s << INDENT << "if (" << PYTHON_OVERRIDE_VAR << ".isNull()) {\n";
- {
- Indentation indentation(INDENT);
- CodeSnipList snips;
- if (func->hasInjectedCode()) {
- snips = func->injectedCodeSnips();
- const AbstractMetaArgument *lastArg = func->arguments().isEmpty() ? nullptr : func->arguments().constLast();
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionBeginning, TypeSystem::ShellCode, func, lastArg);
- s << Qt::endl;
- }
-
- if (func->isAbstract()) {
- s << INDENT << "PyErr_SetString(PyExc_NotImplementedError, \"pure virtual method '";
- s << func->ownerClass()->name() << '.' << funcName;
- s << "()' not implemented.\");\n";
- s << INDENT << "return";
- if (retType)
- s << ' ' << defaultReturnExpr.returnValue();
- } else {
- s << INDENT << "gil.release();\n";
- if (useOverrideCaching(func->ownerClass())) {
- s << INDENT << "m_PyMethodCache[" << cacheIndex << "] = true;\n";
- s << INDENT;
- }
- if (retType)
- s << "return ";
- s << "this->::" << func->implementingClass()->qualifiedCppName() << "::";
- writeFunctionCall(s, func, Generator::VirtualCall);
- if (!retType)
- s << ";\n" << INDENT << "return";
- }
- }
- s << ";\n";
- s << INDENT << "}\n\n"; //WS
-
- writeConversionRule(s, func, TypeSystem::TargetLangCode);
-
- s << INDENT << "Shiboken::AutoDecRef " << PYTHON_ARGS << "(";
-
- if (func->arguments().isEmpty() || allArgumentsRemoved(func)) {
- s << "PyTuple_New(0));\n";
- } else {
- QStringList argConversions;
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- if (func->argumentRemoved(arg->argumentIndex() + 1))
- continue;
-
- QString argConv;
- QTextStream ac(&argConv);
- auto argType = static_cast<const PrimitiveTypeEntry *>(arg->type()->typeEntry());
- bool convert = argType->isObject()
- || argType->isValue()
- || arg->type()->isValuePointer()
- || arg->type()->isNativePointer()
- || argType->isFlags()
- || argType->isEnum()
- || argType->isContainer()
- || arg->type()->referenceType() == LValueReference;
-
- if (!convert && argType->isPrimitive()) {
- if (argType->basicReferencedTypeEntry())
- argType = argType->basicReferencedTypeEntry();
- convert = !m_formatUnits.contains(argType->name());
- }
-
- Indentation indentation(INDENT);
- ac << INDENT;
- if (!func->conversionRule(TypeSystem::TargetLangCode, arg->argumentIndex() + 1).isEmpty()) {
- // Has conversion rule.
- ac << arg->name() + QLatin1String(CONV_RULE_OUT_VAR_SUFFIX);
- } else {
- QString argName = arg->name();
- if (convert)
- writeToPythonConversion(ac, arg->type(), func->ownerClass(), argName);
- else
- ac << argName;
- }
-
- argConversions << argConv;
- }
-
- s << "Py_BuildValue(\"(" << getFormatUnitString(func, false) << ")\",\n";
- s << argConversions.join(QLatin1String(",\n")) << Qt::endl;
- s << INDENT << "));\n";
- }
-
- bool invalidateReturn = false;
- QSet<int> invalidateArgs;
- const FunctionModificationList &mods = func->modifications();
- for (const FunctionModification &funcMod : mods) {
- for (const ArgumentModification &argMod : funcMod.argument_mods) {
- if (argMod.resetAfterUse && !invalidateArgs.contains(argMod.index)) {
- invalidateArgs.insert(argMod.index);
- s << INDENT << "bool invalidateArg" << argMod.index;
- s << " = PyTuple_GET_ITEM(" << PYTHON_ARGS << ", " << argMod.index - 1 << ")->ob_refcnt == 1;\n";
- } else if (argMod.index == 0 && argMod.ownerships[TypeSystem::TargetLangCode] == TypeSystem::CppOwnership) {
- invalidateReturn = true;
- }
- }
- }
- s << Qt::endl;
-
- CodeSnipList snips;
- if (func->hasInjectedCode()) {
- snips = func->injectedCodeSnips();
-
- if (injectedCodeUsesPySelf(func))
- s << INDENT << "PyObject *pySelf = BindingManager::instance().retrieveWrapper(this);\n";
-
- const AbstractMetaArgument *lastArg = func->arguments().isEmpty() ? nullptr : func->arguments().constLast();
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionBeginning, TypeSystem::NativeCode, func, lastArg);
- s << Qt::endl;
- }
-
- if (!injectedCodeCallsPythonOverride(func)) {
- s << INDENT;
- s << "Shiboken::AutoDecRef " << PYTHON_RETURN_VAR << "(PyObject_Call("
- << PYTHON_OVERRIDE_VAR << ", " << PYTHON_ARGS << ", nullptr));\n";
-
- s << INDENT << "// An error happened in python code!\n";
- s << INDENT << "if (" << PYTHON_RETURN_VAR << ".isNull()) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_Print();\n";
- s << INDENT << returnStatement(defaultReturnExpr.returnValue()) << Qt::endl;
- }
- s << INDENT << "}\n";
-
- if (retType) {
- if (invalidateReturn)
- s << INDENT << "bool invalidateArg0 = " << PYTHON_RETURN_VAR << "->ob_refcnt == 1;\n";
-
- if (func->typeReplaced(0) != QLatin1String("PyObject")) {
-
- s << INDENT << "// Check return type\n";
- s << INDENT;
- if (func->typeReplaced(0).isEmpty()) {
- s << "PythonToCppFunc " << PYTHON_TO_CPP_VAR << " = " << cpythonIsConvertibleFunction(func->type());
- s << PYTHON_RETURN_VAR << ");\n";
- s << INDENT << "if (!" << PYTHON_TO_CPP_VAR << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "Shiboken::warning(PyExc_RuntimeWarning, 2, "\
- "\"Invalid return value in function %s, expected %s, got %s.\", \"";
- s << func->ownerClass()->name() << '.' << funcName << "\", " << getVirtualFunctionReturnTypeName(func);
- s << ", Py_TYPE(" << PYTHON_RETURN_VAR << ")->tp_name);\n";
- s << INDENT << returnStatement(defaultReturnExpr.returnValue()) << Qt::endl;
- }
- s << INDENT << "}\n";
-
- } else {
-
- s << INDENT << "// Check return type\n";
- s << INDENT << "bool typeIsValid = ";
- writeTypeCheck(s, func->type(), QLatin1String(PYTHON_RETURN_VAR),
- isNumber(func->type()->typeEntry()), func->typeReplaced(0));
- s << ";\n";
- s << INDENT << "if (!typeIsValid";
- if (isPointerToWrapperType(func->type()))
- s << " && " << PYTHON_RETURN_VAR << " != Py_None";
- s << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "Shiboken::warning(PyExc_RuntimeWarning, 2, "\
- "\"Invalid return value in function %s, expected %s, got %s.\", \"";
- s << func->ownerClass()->name() << '.' << funcName << "\", " << getVirtualFunctionReturnTypeName(func);
- s << ", Py_TYPE(" << PYTHON_RETURN_VAR << ")->tp_name);\n";
- s << INDENT << returnStatement(defaultReturnExpr.returnValue()) << Qt::endl;
- }
- s << INDENT << "}\n";
-
- }
- }
-
- if (!func->conversionRule(TypeSystem::NativeCode, 0).isEmpty()) {
- // Has conversion rule.
- writeConversionRule(s, func, TypeSystem::NativeCode, QLatin1String(CPP_RETURN_VAR));
- } else if (!injectedCodeHasReturnValueAttribution(func, TypeSystem::NativeCode)) {
- writePythonToCppTypeConversion(s, func->type(), QLatin1String(PYTHON_RETURN_VAR),
- QLatin1String(CPP_RETURN_VAR), func->implementingClass());
- }
- }
- }
-
- if (invalidateReturn) {
- s << INDENT << "if (invalidateArg0)\n";
- Indentation indentation(INDENT);
- s << INDENT << "Shiboken::Object::releaseOwnership(" << PYTHON_RETURN_VAR << ".object());\n";
- }
- for (int argIndex : qAsConst(invalidateArgs)) {
- s << INDENT << "if (invalidateArg" << argIndex << ")\n";
- Indentation indentation(INDENT);
- s << INDENT << "Shiboken::Object::invalidate(PyTuple_GET_ITEM(" << PYTHON_ARGS << ", ";
- s << (argIndex - 1) << "));\n";
- }
-
-
- const FunctionModificationList &funcMods = func->modifications();
- for (const FunctionModification &funcMod : funcMods) {
- for (const ArgumentModification &argMod : funcMod.argument_mods) {
- if (argMod.ownerships.contains(TypeSystem::NativeCode)
- && argMod.index == 0 && argMod.ownerships[TypeSystem::NativeCode] == TypeSystem::CppOwnership) {
- s << INDENT << "if (Shiboken::Object::checkType(" << PYTHON_RETURN_VAR << "))\n";
- Indentation indent(INDENT);
- s << INDENT << "Shiboken::Object::releaseOwnership(" << PYTHON_RETURN_VAR << ");\n";
- }
- }
- }
-
- if (func->hasInjectedCode()) {
- s << Qt::endl;
- const AbstractMetaArgument *lastArg = func->arguments().isEmpty() ? nullptr : func->arguments().constLast();
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionEnd, TypeSystem::NativeCode, func, lastArg);
- }
-
- if (retType) {
- s << INDENT << "return ";
- if (avoidProtectedHack() && retType->isEnum()) {
- const AbstractMetaEnum *metaEnum = findAbstractMetaEnum(retType);
- bool isProtectedEnum = metaEnum && metaEnum->isProtected();
- if (isProtectedEnum) {
- QString typeCast;
- if (metaEnum->enclosingClass())
- typeCast += QLatin1String("::") + metaEnum->enclosingClass()->qualifiedCppName();
- typeCast += QLatin1String("::") + metaEnum->name();
- s << '(' << typeCast << ')';
- }
- }
- if (func->type()->referenceType() == LValueReference && !isPointer(func->type()))
- s << " *";
- s << CPP_RETURN_VAR << ";\n";
- }
-
- s<< "}\n\n";
-}
-
-void CppGenerator::writeMetaObjectMethod(QTextStream &s, const GeneratorContext &classContext)
-{
- Indentation indentation(INDENT);
- const QString wrapperClassName = classContext.wrapperName();
- const QString qualifiedCppName = classContext.metaClass()->qualifiedCppName();
- s << "const QMetaObject *" << wrapperClassName << "::metaObject() const\n{\n";
- s << INDENT << "if (QObject::d_ptr->metaObject)\n"
- << INDENT << INDENT << "return QObject::d_ptr->dynamicMetaObject();\n";
- s << INDENT << "SbkObject *pySelf = Shiboken::BindingManager::instance().retrieveWrapper(this);\n";
- s << INDENT << "if (pySelf == nullptr)\n";
- s << INDENT << INDENT << "return " << qualifiedCppName << "::metaObject();\n";
- s << INDENT << "return PySide::SignalManager::retrieveMetaObject(reinterpret_cast<PyObject *>(pySelf));\n";
- s<< "}\n\n";
-
- // qt_metacall function
- s << "int " << wrapperClassName << "::qt_metacall(QMetaObject::Call call, int id, void **args)\n";
- s << "{\n";
-
- AbstractMetaFunction *func = nullptr;
- AbstractMetaFunctionList list =
- classContext.metaClass()->queryFunctionsByName(QLatin1String("qt_metacall"));
- if (list.size() == 1)
- func = list[0];
-
- CodeSnipList snips;
- if (func) {
- snips = func->injectedCodeSnips();
- if (func->isUserAdded()) {
- CodeSnipList snips = func->injectedCodeSnips();
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionAny, TypeSystem::NativeCode, func);
- }
- }
-
- s << INDENT << "int result = " << qualifiedCppName << "::qt_metacall(call, id, args);\n";
- s << INDENT << "return result < 0 ? result : PySide::SignalManager::qt_metacall(this, call, id, args);\n";
- s << "}\n\n";
-
- // qt_metacast function
- writeMetaCast(s, classContext);
-}
-
-void CppGenerator::writeMetaCast(QTextStream &s, const GeneratorContext &classContext)
-{
- Indentation indentation(INDENT);
- const QString wrapperClassName = classContext.wrapperName();
- const QString qualifiedCppName = classContext.metaClass()->qualifiedCppName();
- s << "void *" << wrapperClassName << "::qt_metacast(const char *_clname)\n{\n";
- s << INDENT << "if (!_clname) return {};\n";
- s << INDENT << "SbkObject *pySelf = Shiboken::BindingManager::instance().retrieveWrapper(this);\n";
- s << INDENT << "if (pySelf && PySide::inherits(Py_TYPE(pySelf), _clname))\n";
- s << INDENT << INDENT << "return static_cast<void *>(const_cast< " << wrapperClassName << " *>(this));\n";
- s << INDENT << "return " << qualifiedCppName << "::qt_metacast(_clname);\n";
- s << "}\n\n";
-}
-
-void CppGenerator::writeEnumConverterFunctions(QTextStream &s, const AbstractMetaEnum *metaEnum)
-{
- if (metaEnum->isPrivate() || metaEnum->isAnonymous())
- return;
- writeEnumConverterFunctions(s, metaEnum->typeEntry());
-}
-
-void CppGenerator::writeEnumConverterFunctions(QTextStream &s, const TypeEntry *enumType)
-{
- if (!enumType)
- return;
- QString typeName = fixedCppTypeName(enumType);
- QString enumPythonType = cpythonTypeNameExt(enumType);
- QString cppTypeName = getFullTypeName(enumType).trimmed();
- if (avoidProtectedHack()) {
- const AbstractMetaEnum *metaEnum = findAbstractMetaEnum(enumType);
- if (metaEnum && metaEnum->isProtected())
- cppTypeName = protectedEnumSurrogateName(metaEnum);
- }
- QString code;
- QTextStream c(&code);
- c << INDENT << "*reinterpret_cast<" << cppTypeName << " *>(cppOut) =\n"
- << INDENT << " ";
- if (enumType->isFlags())
- c << cppTypeName << "(QFlag(int(PySide::QFlags::getValue(reinterpret_cast<PySideQFlagsObject *>(pyIn)))))";
- else
- c << "static_cast<" << cppTypeName << ">(Shiboken::Enum::getValue(pyIn))";
- c << ";\n";
- writePythonToCppFunction(s, code, typeName, typeName);
-
- QString pyTypeCheck = QStringLiteral("PyObject_TypeCheck(pyIn, %1)").arg(enumPythonType);
- writeIsPythonConvertibleToCppFunction(s, typeName, typeName, pyTypeCheck);
-
- code.clear();
-
- c << INDENT << "const int castCppIn = int(*reinterpret_cast<const "
- << cppTypeName << " *>(cppIn));\n";
- c << INDENT;
- c << "return ";
- if (enumType->isFlags()) {
- c << "reinterpret_cast<PyObject *>(PySide::QFlags::newObject(castCppIn, "
- << enumPythonType << "))";
- } else {
- c << "Shiboken::Enum::newItem(" << enumPythonType << ", castCppIn)";
- }
- c << ";\n";
- writeCppToPythonFunction(s, code, typeName, typeName);
- s << Qt::endl;
-
- if (enumType->isFlags())
- return;
-
- auto flags = reinterpret_cast<const EnumTypeEntry *>(enumType)->flags();
- if (!flags)
- return;
-
- // QFlags part.
-
- writeEnumConverterFunctions(s, flags);
-
- code.clear();
- cppTypeName = getFullTypeName(flags).trimmed();
- c << INDENT << "*reinterpret_cast<" << cppTypeName << " *>(cppOut) =\n"
- << INDENT << " " << cppTypeName
- << "(QFlag(int(Shiboken::Enum::getValue(pyIn))));\n";
-
- QString flagsTypeName = fixedCppTypeName(flags);
- writePythonToCppFunction(s, code, typeName, flagsTypeName);
- writeIsPythonConvertibleToCppFunction(s, typeName, flagsTypeName, pyTypeCheck);
-
- code.clear();
- c << INDENT << "Shiboken::AutoDecRef pyLong(PyNumber_Long(pyIn));\n";
- c << INDENT << "*reinterpret_cast<" << cppTypeName << " *>(cppOut) =\n"
- << INDENT << " " << cppTypeName
- << "(QFlag(int(PyLong_AsLong(pyLong.object()))));\n";
- // PYSIDE-898: Include an additional condition to detect if the type of the
- // enum corresponds to the object that is being evaluated.
- // Using only `PyNumber_Check(...)` is too permissive,
- // then we would have been unable to detect the difference between
- // a PolarOrientation and Qt::AlignmentFlag, which was the main
- // issue of the bug.
- const QString numberCondition = QStringLiteral("PyNumber_Check(pyIn) && ") + pyTypeCheck;
- writePythonToCppFunction(s, code, QLatin1String("number"), flagsTypeName);
- writeIsPythonConvertibleToCppFunction(s, QLatin1String("number"), flagsTypeName, numberCondition);
-
-
-}
-
-void CppGenerator::writeConverterFunctions(QTextStream &s, const AbstractMetaClass *metaClass,
- const GeneratorContext &classContext)
-{
- s << "// Type conversion functions.\n\n";
-
- AbstractMetaEnumList classEnums = metaClass->enums();
- const AbstractMetaClassList &innerClasses = metaClass->innerClasses();
- for (AbstractMetaClass *innerClass : innerClasses)
- lookForEnumsInClassesNotToBeGenerated(classEnums, innerClass);
- if (!classEnums.isEmpty())
- s << "// Python to C++ enum conversion.\n";
- for (const AbstractMetaEnum *metaEnum : qAsConst(classEnums))
- writeEnumConverterFunctions(s, metaEnum);
-
- if (metaClass->isNamespace())
- return;
-
- QString typeName;
- if (!classContext.forSmartPointer())
- typeName = getFullTypeName(metaClass);
- else
- typeName = getFullTypeName(classContext.preciseType());
-
- QString cpythonType = cpythonTypeName(metaClass);
-
- // Returns the C++ pointer of the Python wrapper.
- s << "// Python to C++ pointer conversion - returns the C++ object of the Python wrapper (keeps object identity).\n";
-
- QString sourceTypeName = metaClass->name();
- QString targetTypeName = metaClass->name() + QLatin1String("_PTR");
- QString code;
- QTextStream c(&code);
- c << INDENT << "Shiboken::Conversions::pythonToCppPointer(" << cpythonType << ", pyIn, cppOut);";
- writePythonToCppFunction(s, code, sourceTypeName, targetTypeName);
-
- // "Is convertible" function for the Python object to C++ pointer conversion.
- const QString pyTypeCheck = QLatin1String("PyObject_TypeCheck(pyIn, reinterpret_cast<PyTypeObject *>(")
- + cpythonType + QLatin1String("))");
- writeIsPythonConvertibleToCppFunction(s, sourceTypeName, targetTypeName, pyTypeCheck, QString(), true);
- s << Qt::endl;
-
- // C++ pointer to a Python wrapper, keeping identity.
- s << "// C++ to Python pointer conversion - tries to find the Python wrapper for the C++ object (keeps object identity).\n";
- code.clear();
- if (usePySideExtensions() && metaClass->isQObject())
- {
- c << INDENT << "return PySide::getWrapperForQObject(reinterpret_cast<"
- << typeName << " *>(const_cast<void *>(cppIn)), " << cpythonType << ");\n";
- } else {
- c << INDENT << "auto pyOut = reinterpret_cast<PyObject *>(Shiboken::BindingManager::instance().retrieveWrapper(cppIn));\n";
- c << INDENT << "if (pyOut) {\n";
- {
- Indentation indent(INDENT);
- c << INDENT << "Py_INCREF(pyOut);\n";
- c << INDENT << "return pyOut;\n";
- }
- c << INDENT << "}\n";
- c << INDENT << "bool changedTypeName = false;\n"
- << INDENT << "auto tCppIn = reinterpret_cast<const " << typeName << " *>(cppIn);\n"
- << INDENT << "const char *typeName = typeid(*tCppIn).name();\n"
- << INDENT << "auto sbkType = Shiboken::ObjectType::typeForTypeName(typeName);\n"
- << INDENT << "if (sbkType && Shiboken::ObjectType::hasSpecialCastFunction(sbkType)) {\n"
- << INDENT << " typeName = typeNameOf(tCppIn);\n"
- << INDENT << " changedTypeName = true;\n"
- << INDENT << " }\n"
- << INDENT << "PyObject *result = Shiboken::Object::newObject(" << cpythonType
- << ", const_cast<void *>(cppIn), false, /* exactType */ changedTypeName, typeName);\n"
- << INDENT << "if (changedTypeName)\n"
- << INDENT << " delete [] typeName;\n"
- << INDENT << "return result;";
- }
- std::swap(targetTypeName, sourceTypeName);
- writeCppToPythonFunction(s, code, sourceTypeName, targetTypeName);
-
- // The conversions for an Object Type end here.
- if (!metaClass->typeEntry()->isValue() && !metaClass->typeEntry()->isSmartPointer()) {
- s << Qt::endl;
- return;
- }
-
- // Always copies C++ value (not pointer, and not reference) to a new Python wrapper.
- s << Qt::endl << "// C++ to Python copy conversion.\n";
- if (!classContext.forSmartPointer())
- targetTypeName = metaClass->name();
- else
- targetTypeName = classContext.preciseType()->name();
-
- sourceTypeName = targetTypeName + QLatin1String("_COPY");
-
- code.clear();
-
- QString computedWrapperName;
- if (!classContext.forSmartPointer()) {
- computedWrapperName = classContext.useWrapper()
- ? classContext.wrapperName() : metaClass->qualifiedCppName();
- } else {
- computedWrapperName = classContext.smartPointerWrapperName();
- }
-
- c << INDENT << "return Shiboken::Object::newObject(" << cpythonType
- << ", new ::" << computedWrapperName << "(*reinterpret_cast<const "
- << typeName << " *>(cppIn)), true, true);";
- writeCppToPythonFunction(s, code, sourceTypeName, targetTypeName);
- s << Qt::endl;
-
- // Python to C++ copy conversion.
- s << "// Python to C++ copy conversion.\n";
- if (!classContext.forSmartPointer())
- sourceTypeName = metaClass->name();
- else
- sourceTypeName = classContext.preciseType()->name();
-
- targetTypeName = QStringLiteral("%1_COPY").arg(sourceTypeName);
- code.clear();
-
- QString pyInVariable = QLatin1String("pyIn");
- QString wrappedCPtrExpression;
- if (!classContext.forSmartPointer())
- wrappedCPtrExpression = cpythonWrapperCPtr(metaClass->typeEntry(), pyInVariable);
- else
- wrappedCPtrExpression = cpythonWrapperCPtr(classContext.preciseType(), pyInVariable);
-
- c << INDENT << "*reinterpret_cast<" << typeName << " *>(cppOut) = *"
- << wrappedCPtrExpression << ';';
- writePythonToCppFunction(s, code, sourceTypeName, targetTypeName);
-
- // "Is convertible" function for the Python object to C++ value copy conversion.
- writeIsPythonConvertibleToCppFunction(s, sourceTypeName, targetTypeName, pyTypeCheck);
- s << Qt::endl;
-
- // User provided implicit conversions.
- CustomConversion *customConversion = metaClass->typeEntry()->customConversion();
-
- // Implicit conversions.
- AbstractMetaFunctionList implicitConvs;
- if (!customConversion || !customConversion->replaceOriginalTargetToNativeConversions()) {
- const AbstractMetaFunctionList &allImplicitConvs = implicitConversions(metaClass->typeEntry());
- for (AbstractMetaFunction *func : allImplicitConvs) {
- if (!func->isUserAdded())
- implicitConvs << func;
- }
- }
-
- if (!implicitConvs.isEmpty())
- s << "// Implicit conversions.\n";
-
- AbstractMetaType *targetType = buildAbstractMetaTypeFromAbstractMetaClass(metaClass);
- for (const AbstractMetaFunction *conv : qAsConst(implicitConvs)) {
- if (conv->isModifiedRemoved())
- continue;
-
- QString typeCheck;
- QString toCppConv;
- QString toCppPreConv;
- if (conv->isConversionOperator()) {
- const AbstractMetaClass *sourceClass = conv->ownerClass();
- typeCheck = QStringLiteral("PyObject_TypeCheck(pyIn, %1)").arg(cpythonTypeNameExt(sourceClass->typeEntry()));
- toCppConv = QLatin1Char('*') + cpythonWrapperCPtr(sourceClass->typeEntry(), QLatin1String("pyIn"));
- } else {
- // Constructor that does implicit conversion.
- if (!conv->typeReplaced(1).isEmpty() || conv->isModifiedToArray(1))
- continue;
- const AbstractMetaType *sourceType = conv->arguments().constFirst()->type();
- typeCheck = cpythonCheckFunction(sourceType);
- bool isUserPrimitiveWithoutTargetLangName = isUserPrimitive(sourceType)
- && sourceType->typeEntry()->targetLangApiName() == sourceType->typeEntry()->name();
- if (!isWrapperType(sourceType)
- && !isUserPrimitiveWithoutTargetLangName
- && !sourceType->typeEntry()->isEnum()
- && !sourceType->typeEntry()->isFlags()
- && !sourceType->typeEntry()->isContainer()) {
- typeCheck += QLatin1Char('(');
- }
- if (isWrapperType(sourceType)) {
- typeCheck += QLatin1String("pyIn)");
- toCppConv = (sourceType->referenceType() == LValueReference || !isPointerToWrapperType(sourceType))
- ? QLatin1String(" *") : QString();
- toCppConv += cpythonWrapperCPtr(sourceType->typeEntry(), QLatin1String("pyIn"));
- } else if (typeCheck.contains(QLatin1String("%in"))) {
- typeCheck.replace(QLatin1String("%in"), QLatin1String("pyIn"));
- typeCheck.append(QLatin1Char(')'));
- } else {
- typeCheck += QLatin1String("pyIn)");
- }
-
- if (isUserPrimitive(sourceType)
- || isCppPrimitive(sourceType)
- || sourceType->typeEntry()->isContainer()
- || sourceType->typeEntry()->isEnum()
- || sourceType->typeEntry()->isFlags()) {
- QTextStream pc(&toCppPreConv);
- pc << INDENT << getFullTypeNameWithoutModifiers(sourceType) << " cppIn";
- writeMinimalConstructorExpression(pc, sourceType);
- pc << ";\n";
- writeToCppConversion(pc, sourceType, nullptr, QLatin1String("pyIn"), QLatin1String("cppIn"));
- pc << ';';
- toCppConv.append(QLatin1String("cppIn"));
- } else if (!isWrapperType(sourceType)) {
- QTextStream tcc(&toCppConv);
- writeToCppConversion(tcc, sourceType, metaClass, QLatin1String("pyIn"), QLatin1String("/*BOZO-1061*/"));
- }
-
-
- }
- const AbstractMetaType *sourceType = conv->isConversionOperator()
- ? buildAbstractMetaTypeFromAbstractMetaClass(conv->ownerClass())
- : conv->arguments().constFirst()->type();
- writePythonToCppConversionFunctions(s, sourceType, targetType, typeCheck, toCppConv, toCppPreConv);
- }
-
- writeCustomConverterFunctions(s, customConversion);
-}
-
-void CppGenerator::writeCustomConverterFunctions(QTextStream &s, const CustomConversion *customConversion)
-{
- if (!customConversion)
- return;
- const CustomConversion::TargetToNativeConversions &toCppConversions = customConversion->targetToNativeConversions();
- if (toCppConversions.isEmpty())
- return;
- s << "// Python to C++ conversions for type '" << customConversion->ownerType()->qualifiedCppName() << "'.\n";
- for (CustomConversion::TargetToNativeConversion *toNative : toCppConversions)
- writePythonToCppConversionFunctions(s, toNative, customConversion->ownerType());
- s << Qt::endl;
-}
-
-void CppGenerator::writeConverterRegister(QTextStream &s, const AbstractMetaClass *metaClass,
- const GeneratorContext &classContext)
-{
- if (metaClass->isNamespace())
- return;
- s << INDENT << "// Register Converter\n";
- s << INDENT << "SbkConverter *converter = Shiboken::Conversions::createConverter(";
- s << cpythonTypeName(metaClass) << ',' << Qt::endl;
- {
- Indentation indent(INDENT);
- QString sourceTypeName = metaClass->name();
- QString targetTypeName = sourceTypeName + QLatin1String("_PTR");
- s << INDENT << pythonToCppFunctionName(sourceTypeName, targetTypeName) << ',' << Qt::endl;
- s << INDENT << convertibleToCppFunctionName(sourceTypeName, targetTypeName) << ',' << Qt::endl;
- std::swap(targetTypeName, sourceTypeName);
- s << INDENT << cppToPythonFunctionName(sourceTypeName, targetTypeName);
- if (metaClass->typeEntry()->isValue() || metaClass->typeEntry()->isSmartPointer()) {
- s << ',' << Qt::endl;
- sourceTypeName = metaClass->name() + QLatin1String("_COPY");
- s << INDENT << cppToPythonFunctionName(sourceTypeName, targetTypeName);
- }
- }
- s << ");\n";
-
- s << Qt::endl;
-
- QStringList cppSignature;
- if (!classContext.forSmartPointer()) {
- cppSignature = metaClass->qualifiedCppName().split(QLatin1String("::"),
- Qt::SkipEmptyParts);
- } else {
- cppSignature = classContext.preciseType()->cppSignature().split(QLatin1String("::"),
- Qt::SkipEmptyParts);
- }
- while (!cppSignature.isEmpty()) {
- QString signature = cppSignature.join(QLatin1String("::"));
- s << INDENT << "Shiboken::Conversions::registerConverterName(converter, \"" << signature << "\");\n";
- s << INDENT << "Shiboken::Conversions::registerConverterName(converter, \"" << signature << "*\");\n";
- s << INDENT << "Shiboken::Conversions::registerConverterName(converter, \"" << signature << "&\");\n";
- cppSignature.removeFirst();
- }
-
- s << INDENT << "Shiboken::Conversions::registerConverterName(converter, typeid(::";
- QString qualifiedCppNameInvocation;
- if (!classContext.forSmartPointer())
- qualifiedCppNameInvocation = metaClass->qualifiedCppName();
- else
- qualifiedCppNameInvocation = classContext.preciseType()->cppSignature();
-
- s << qualifiedCppNameInvocation << ").name());\n";
-
- if (classContext.useWrapper()) {
- s << INDENT << "Shiboken::Conversions::registerConverterName(converter, typeid(::";
- s << classContext.wrapperName() << ").name());\n";
- }
-
- s << Qt::endl;
-
- if (!metaClass->typeEntry()->isValue() && !metaClass->typeEntry()->isSmartPointer())
- return;
-
- // Python to C++ copy (value, not pointer neither reference) conversion.
- s << INDENT << "// Add Python to C++ copy (value, not pointer neither reference) conversion to type converter.\n";
- QString sourceTypeName = metaClass->name();
- QString targetTypeName = sourceTypeName + QLatin1String("_COPY");
- QString toCpp = pythonToCppFunctionName(sourceTypeName, targetTypeName);
- QString isConv = convertibleToCppFunctionName(sourceTypeName, targetTypeName);
- writeAddPythonToCppConversion(s, QLatin1String("converter"), toCpp, isConv);
-
- // User provided implicit conversions.
- CustomConversion *customConversion = metaClass->typeEntry()->customConversion();
-
- // Add implicit conversions.
- AbstractMetaFunctionList implicitConvs;
- if (!customConversion || !customConversion->replaceOriginalTargetToNativeConversions()) {
- const AbstractMetaFunctionList &allImplicitConvs = implicitConversions(metaClass->typeEntry());
- for (AbstractMetaFunction *func : allImplicitConvs) {
- if (!func->isUserAdded())
- implicitConvs << func;
- }
- }
-
- if (!implicitConvs.isEmpty())
- s << INDENT << "// Add implicit conversions to type converter.\n";
-
- AbstractMetaType *targetType = buildAbstractMetaTypeFromAbstractMetaClass(metaClass);
- for (const AbstractMetaFunction *conv : qAsConst(implicitConvs)) {
- if (conv->isModifiedRemoved())
- continue;
- const AbstractMetaType *sourceType;
- if (conv->isConversionOperator()) {
- sourceType = buildAbstractMetaTypeFromAbstractMetaClass(conv->ownerClass());
- } else {
- // Constructor that does implicit conversion.
- if (!conv->typeReplaced(1).isEmpty() || conv->isModifiedToArray(1))
- continue;
- sourceType = conv->arguments().constFirst()->type();
- }
- QString toCpp = pythonToCppFunctionName(sourceType, targetType);
- QString isConv = convertibleToCppFunctionName(sourceType, targetType);
- writeAddPythonToCppConversion(s, QLatin1String("converter"), toCpp, isConv);
- }
-
- writeCustomConverterRegister(s, customConversion, QLatin1String("converter"));
-}
-
-void CppGenerator::writeCustomConverterRegister(QTextStream &s, const CustomConversion *customConversion, const QString &converterVar)
-{
- if (!customConversion)
- return;
- const CustomConversion::TargetToNativeConversions &toCppConversions = customConversion->targetToNativeConversions();
- if (toCppConversions.isEmpty())
- return;
- s << INDENT << "// Add user defined implicit conversions to type converter.\n";
- for (CustomConversion::TargetToNativeConversion *toNative : toCppConversions) {
- QString toCpp = pythonToCppFunctionName(toNative, customConversion->ownerType());
- QString isConv = convertibleToCppFunctionName(toNative, customConversion->ownerType());
- writeAddPythonToCppConversion(s, converterVar, toCpp, isConv);
- }
-}
-
-void CppGenerator::writeContainerConverterFunctions(QTextStream &s, const AbstractMetaType *containerType)
-{
- writeCppToPythonFunction(s, containerType);
- writePythonToCppConversionFunctions(s, containerType);
-}
-
-void CppGenerator::writeMethodWrapperPreamble(QTextStream &s, OverloadData &overloadData,
- const GeneratorContext &context)
-{
- const AbstractMetaFunction *rfunc = overloadData.referenceFunction();
- const AbstractMetaClass *ownerClass = rfunc->ownerClass();
- Q_ASSERT(ownerClass == context.metaClass());
- int minArgs = overloadData.minArgs();
- int maxArgs = overloadData.maxArgs();
- bool initPythonArguments;
- bool usesNamedArguments;
-
- // If method is a constructor...
- if (rfunc->isConstructor()) {
- // Check if the right constructor was called.
- if (!ownerClass->hasPrivateDestructor()) {
- s << INDENT;
- s << "if (Shiboken::Object::isUserType(self) && !Shiboken::ObjectType::canCallConstructor(self->ob_type, Shiboken::SbkType< ::";
- QString qualifiedCppName;
- if (!context.forSmartPointer())
- qualifiedCppName = ownerClass->qualifiedCppName();
- else
- qualifiedCppName = context.preciseType()->cppSignature();
-
- s << qualifiedCppName << " >()))\n";
- Indentation indent(INDENT);
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl << Qt::endl;
- }
- // Declare pointer for the underlying C++ object.
- s << INDENT << "::";
- if (!context.forSmartPointer()) {
- s << (context.useWrapper() ? context.wrapperName() : ownerClass->qualifiedCppName());
- } else {
- s << context.smartPointerWrapperName();
- }
- s << " *cptr{};\n";
-
- initPythonArguments = maxArgs > 0;
- usesNamedArguments = !ownerClass->isQObject() && overloadData.hasArgumentWithDefaultValue();
-
- } else {
- if (rfunc->implementingClass() &&
- (!rfunc->implementingClass()->isNamespace() && overloadData.hasInstanceFunction())) {
- writeCppSelfDefinition(s, rfunc, context, overloadData.hasStaticFunction());
- }
- if (!rfunc->isInplaceOperator() && overloadData.hasNonVoidReturnType())
- s << INDENT << "PyObject *" << PYTHON_RETURN_VAR << "{};\n";
-
- initPythonArguments = minArgs != maxArgs || maxArgs > 1;
- usesNamedArguments = rfunc->isCallOperator() || overloadData.hasArgumentWithDefaultValue();
- }
-
- if (maxArgs > 0) {
- s << INDENT << "int overloadId = -1;\n";
- s << INDENT << "PythonToCppFunc " << PYTHON_TO_CPP_VAR;
- if (pythonFunctionWrapperUsesListOfArguments(overloadData)) {
- s << "[] = { " << NULL_PTR;
- for (int i = 1; i < maxArgs; ++i)
- s << ", " << NULL_PTR;
- s << " };\n";
- } else {
- s << "{};\n";
- }
- writeUnusedVariableCast(s, QLatin1String(PYTHON_TO_CPP_VAR));
- }
-
- if (usesNamedArguments && !rfunc->isCallOperator())
- s << INDENT << "int numNamedArgs = (kwds ? PyDict_Size(kwds) : 0);\n";
-
- if (initPythonArguments) {
- s << INDENT << "int numArgs = ";
- if (minArgs == 0 && maxArgs == 1 && !rfunc->isConstructor() && !pythonFunctionWrapperUsesListOfArguments(overloadData))
- s << "(" << PYTHON_ARG << " == 0 ? 0 : 1);\n";
- else
- writeArgumentsInitializer(s, overloadData);
- }
-}
-
-void CppGenerator::writeConstructorWrapper(QTextStream &s, const AbstractMetaFunctionList &overloads,
- const GeneratorContext &classContext)
-{
- ErrorCode errorCode(-1);
- OverloadData overloadData(overloads, this);
-
- const AbstractMetaFunction *rfunc = overloadData.referenceFunction();
- const AbstractMetaClass *metaClass = rfunc->ownerClass();
-
- s << "static int\n";
- s << cpythonFunctionName(rfunc) << "(PyObject *self, PyObject *args, PyObject *kwds)\n{\n";
-
- QSet<QString> argNamesSet;
- if (usePySideExtensions() && metaClass->isQObject()) {
- // Write argNames variable with all known argument names.
- const OverloadData::MetaFunctionList &overloads = overloadData.overloads();
- for (const AbstractMetaFunction *func : overloads) {
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- if (arg->defaultValueExpression().isEmpty() || func->argumentRemoved(arg->argumentIndex() + 1))
- continue;
- argNamesSet << arg->name();
- }
- }
- QStringList argNamesList = argNamesSet.values();
- std::sort(argNamesList.begin(), argNamesList.end());
- if (argNamesList.isEmpty()) {
- s << INDENT << "const char **argNames{};\n";
- } else {
- s << INDENT << "const char *argNames[] = {\""
- << argNamesList.join(QLatin1String("\", \"")) << "\"};\n";
- }
- s << INDENT << "const QMetaObject *metaObject;\n";
- }
-
- s << INDENT << "SbkObject *sbkSelf = reinterpret_cast<SbkObject *>(self);\n";
-
- if (metaClass->isAbstract() || metaClass->baseClassNames().size() > 1) {
- s << INDENT << "SbkObjectType *type = reinterpret_cast<SbkObjectType *>(self->ob_type);\n";
- s << INDENT << "SbkObjectType *myType = reinterpret_cast<SbkObjectType *>(" << cpythonTypeNameExt(metaClass->typeEntry()) << ");\n";
- }
-
- if (metaClass->isAbstract()) {
- s << INDENT << "if (type == myType) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_NotImplementedError,\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << "\"'" << metaClass->qualifiedCppName();
- }
- s << "' represents a C++ abstract class and cannot be instantiated\");\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT<< "}\n\n";
- }
-
- if (metaClass->baseClassNames().size() > 1) {
- if (!metaClass->isAbstract()) {
- s << INDENT << "if (type != myType) {\n";
- }
- {
- Indentation indentation(INDENT);
- s << INDENT << "Shiboken::ObjectType::copyMultipleInheritance(type, myType);\n";
- }
- if (!metaClass->isAbstract())
- s << INDENT<< "}\n\n";
- }
-
- writeMethodWrapperPreamble(s, overloadData, classContext);
-
- s << Qt::endl;
-
- if (overloadData.maxArgs() > 0)
- writeOverloadedFunctionDecisor(s, overloadData);
-
- writeFunctionCalls(s, overloadData, classContext);
- s << Qt::endl;
-
- s << INDENT << "if (PyErr_Occurred() || !Shiboken::Object::setCppPointer(sbkSelf, Shiboken::SbkType< ::" << metaClass->qualifiedCppName() << " >(), cptr)) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "delete cptr;\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT << "}\n";
- if (overloadData.maxArgs() > 0) {
- s << INDENT << "if (!cptr) goto " << cpythonFunctionName(rfunc) << "_TypeError;\n";
- s << Qt::endl;
- }
-
- s << INDENT << "Shiboken::Object::setValidCpp(sbkSelf, true);\n";
- // If the created C++ object has a C++ wrapper the ownership is assigned to Python
- // (first "1") and the flag indicating that the Python wrapper holds an C++ wrapper
- // is marked as true (the second "1"). Otherwise the default values apply:
- // Python owns it and C++ wrapper is false.
- if (shouldGenerateCppWrapper(overloads.constFirst()->ownerClass()))
- s << INDENT << "Shiboken::Object::setHasCppWrapper(sbkSelf, true);\n";
- // Need to check if a wrapper for same pointer is already registered
- // Caused by bug PYSIDE-217, where deleted objects' wrappers are not released
- s << INDENT << "if (Shiboken::BindingManager::instance().hasWrapper(cptr)) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "Shiboken::BindingManager::instance().releaseWrapper(Shiboken::BindingManager::instance().retrieveWrapper(cptr));\n";
- }
- s << INDENT << "}\n";
- s << INDENT << "Shiboken::BindingManager::instance().registerWrapper(sbkSelf, cptr);\n";
-
- // Create metaObject and register signal/slot
- if (metaClass->isQObject() && usePySideExtensions()) {
- s << Qt::endl << INDENT << "// QObject setup\n";
- s << INDENT << "PySide::Signal::updateSourceObject(self);\n";
- s << INDENT << "metaObject = cptr->metaObject(); // <- init python qt properties\n";
- s << INDENT << "if (kwds && !PySide::fillQtProperties(self, metaObject, kwds, argNames, " << argNamesSet.count() << "))\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- }
-
- // Constructor code injections, position=end
- bool hasCodeInjectionsAtEnd = false;
- for (AbstractMetaFunction *func : overloads) {
- const CodeSnipList &injectedCodeSnips = func->injectedCodeSnips();
- for (const CodeSnip &cs : injectedCodeSnips) {
- if (cs.position == TypeSystem::CodeSnipPositionEnd) {
- hasCodeInjectionsAtEnd = true;
- break;
- }
- }
- }
- if (hasCodeInjectionsAtEnd) {
- // FIXME: C++ arguments are not available in code injection on constructor when position = end.
- s << INDENT << "switch (overloadId) {\n";
- for (AbstractMetaFunction *func : overloads) {
- Indentation indent(INDENT);
- const CodeSnipList &injectedCodeSnips = func->injectedCodeSnips();
- for (const CodeSnip &cs : injectedCodeSnips) {
- if (cs.position == TypeSystem::CodeSnipPositionEnd) {
- s << INDENT << "case " << metaClass->functions().indexOf(func) << ':' << Qt::endl;
- s << INDENT << "{\n";
- {
- Indentation indent(INDENT);
- writeCodeSnips(s, func->injectedCodeSnips(), TypeSystem::CodeSnipPositionEnd, TypeSystem::TargetLangCode, func);
- }
- s << INDENT << "}\n";
- break;
- }
- }
- }
- s << "}\n";
- }
-
- s << Qt::endl;
- s << Qt::endl << INDENT << "return 1;\n";
- if (overloadData.maxArgs() > 0)
- writeErrorSection(s, overloadData);
- s<< "}\n\n";
-}
-
-void CppGenerator::writeMethodWrapper(QTextStream &s, const AbstractMetaFunctionList &overloads,
- const GeneratorContext &classContext)
-{
- OverloadData overloadData(overloads, this);
- const AbstractMetaFunction *rfunc = overloadData.referenceFunction();
-
- int maxArgs = overloadData.maxArgs();
-
- s << "static PyObject *";
- s << cpythonFunctionName(rfunc) << "(PyObject *self";
- if (maxArgs > 0) {
- s << ", PyObject *" << (pythonFunctionWrapperUsesListOfArguments(overloadData) ? "args" : PYTHON_ARG);
- if (overloadData.hasArgumentWithDefaultValue() || rfunc->isCallOperator())
- s << ", PyObject *kwds";
- }
- s << ")\n{\n";
-
- writeMethodWrapperPreamble(s, overloadData, classContext);
-
- s << Qt::endl;
-
- /*
- * This code is intended for shift operations only:
- * Make sure reverse <</>> operators defined in other classes (specially from other modules)
- * are called. A proper and generic solution would require an reengineering in the operator
- * system like the extended converters.
- *
- * Solves #119 - QDataStream <</>> operators not working for QPixmap
- * http://bugs.openbossa.org/show_bug.cgi?id=119
- */
- bool hasReturnValue = overloadData.hasNonVoidReturnType();
- bool callExtendedReverseOperator = hasReturnValue
- && !rfunc->isInplaceOperator()
- && !rfunc->isCallOperator()
- && rfunc->isOperatorOverload();
- if (callExtendedReverseOperator) {
- QString revOpName = ShibokenGenerator::pythonOperatorFunctionName(rfunc).insert(2, QLatin1Char('r'));
- // For custom classes, operations like __radd__ and __rmul__
- // will enter an infinite loop.
- if (rfunc->isBinaryOperator() && revOpName.contains(QLatin1String("shift"))) {
- s << INDENT << "Shiboken::AutoDecRef attrName(Py_BuildValue(\"s\", \"" << revOpName << "\"));\n";
- s << INDENT << "if (!isReverse\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "&& Shiboken::Object::checkType(" << PYTHON_ARG << ")\n";
- s << INDENT << "&& !PyObject_TypeCheck(" << PYTHON_ARG << ", self->ob_type)\n";
- s << INDENT << "&& PyObject_HasAttr(" << PYTHON_ARG << ", attrName)) {\n";
-
- // This PyObject_CallMethod call will emit lots of warnings like
- // "deprecated conversion from string constant to char *" during compilation
- // due to the method name argument being declared as "char *" instead of "const char *"
- // issue 6952 http://bugs.python.org/issue6952
- s << INDENT << "PyObject *revOpMethod = PyObject_GetAttr(" << PYTHON_ARG << ", attrName);\n";
- s << INDENT << "if (revOpMethod && PyCallable_Check(revOpMethod)) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << PYTHON_RETURN_VAR << " = PyObject_CallFunction(revOpMethod, const_cast<char *>(\"O\"), self);\n";
- s << INDENT << "if (PyErr_Occurred() && (PyErr_ExceptionMatches(PyExc_NotImplementedError)";
- s << " || PyErr_ExceptionMatches(PyExc_AttributeError))) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_Clear();\n";
- s << INDENT << "Py_XDECREF(" << PYTHON_RETURN_VAR << ");\n";
- s << INDENT << PYTHON_RETURN_VAR << " = " << NULL_PTR << ";\n";
- }
- s << INDENT << "}\n";
- }
- s << INDENT << "}\n";
- s << INDENT << "Py_XDECREF(revOpMethod);\n\n";
- }
- s << INDENT << "}\n";
- }
- s << INDENT << "// Do not enter here if other object has implemented a reverse operator.\n";
- s << INDENT << "if (!" << PYTHON_RETURN_VAR << ") {\n\n";
- }
-
- if (maxArgs > 0)
- writeOverloadedFunctionDecisor(s, overloadData);
-
- writeFunctionCalls(s, overloadData, classContext);
-
- if (callExtendedReverseOperator)
- s << Qt::endl << INDENT << "} // End of \"if (!" << PYTHON_RETURN_VAR << ")\"\n";
-
- s << Qt::endl;
-
- writeFunctionReturnErrorCheckSection(s, hasReturnValue && !rfunc->isInplaceOperator());
-
- if (hasReturnValue) {
- if (rfunc->isInplaceOperator()) {
- s << INDENT << "Py_INCREF(self);\n";
- s << INDENT << "return self;\n";
- } else {
- s << INDENT << "return " << PYTHON_RETURN_VAR << ";\n";
- }
- } else {
- s << INDENT << "Py_RETURN_NONE;\n";
- }
-
- if (maxArgs > 0)
- writeErrorSection(s, overloadData);
-
- s<< "}\n\n";
-}
-
-void CppGenerator::writeArgumentsInitializer(QTextStream &s, OverloadData &overloadData)
-{
- const AbstractMetaFunction *rfunc = overloadData.referenceFunction();
- s << "PyTuple_GET_SIZE(args);\n";
- writeUnusedVariableCast(s, QLatin1String("numArgs"));
-
- int minArgs = overloadData.minArgs();
- int maxArgs = overloadData.maxArgs();
-
- s << INDENT << "PyObject *";
- s << PYTHON_ARGS << "[] = {"
- << QString(maxArgs, QLatin1Char('0')).split(QLatin1String(""), Qt::SkipEmptyParts).join(QLatin1String(", "))
- << "};\n";
- s << Qt::endl;
-
- if (overloadData.hasVarargs()) {
- maxArgs--;
- if (minArgs > maxArgs)
- minArgs = maxArgs;
-
- s << INDENT << "PyObject *nonvarargs = PyTuple_GetSlice(args, 0, " << maxArgs << ");\n";
- s << INDENT << "Shiboken::AutoDecRef auto_nonvarargs(nonvarargs);\n";
- s << INDENT << PYTHON_ARGS << '[' << maxArgs << "] = PyTuple_GetSlice(args, " << maxArgs << ", numArgs);\n";
- s << INDENT << "Shiboken::AutoDecRef auto_varargs(" << PYTHON_ARGS << "[" << maxArgs << "]);\n";
- s << Qt::endl;
- }
-
- bool usesNamedArguments = overloadData.hasArgumentWithDefaultValue();
-
- s << INDENT << "// invalid argument lengths\n";
- bool ownerClassIsQObject = rfunc->ownerClass() && rfunc->ownerClass()->isQObject() && rfunc->isConstructor();
- if (usesNamedArguments) {
- if (!ownerClassIsQObject) {
- s << INDENT << "if (numArgs" << (overloadData.hasArgumentWithDefaultValue() ? " + numNamedArgs" : "") << " > " << maxArgs << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_TypeError, \"" << fullPythonFunctionName(rfunc) << "(): too many arguments\");\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT << '}';
- }
- if (minArgs > 0) {
- if (ownerClassIsQObject)
- s << INDENT;
- else
- s << " else ";
- s << "if (numArgs < " << minArgs << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_TypeError, \"" << fullPythonFunctionName(rfunc) << "(): not enough arguments\");\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT << '}';
- }
- }
- const QVector<int> invalidArgsLength = overloadData.invalidArgumentLengths();
- if (!invalidArgsLength.isEmpty()) {
- QStringList invArgsLen;
- for (int i : qAsConst(invalidArgsLength))
- invArgsLen << QStringLiteral("numArgs == %1").arg(i);
- if (usesNamedArguments && (!ownerClassIsQObject || minArgs > 0))
- s << " else ";
- else
- s << INDENT;
- s << "if (" << invArgsLen.join(QLatin1String(" || ")) << ")\n";
- Indentation indent(INDENT);
- s << INDENT << "goto " << cpythonFunctionName(rfunc) << "_TypeError;";
- }
- s << Qt::endl << Qt::endl;
-
- QString funcName;
- if (rfunc->isOperatorOverload())
- funcName = ShibokenGenerator::pythonOperatorFunctionName(rfunc);
- else
- funcName = rfunc->name();
-
- QString argsVar = overloadData.hasVarargs() ? QLatin1String("nonvarargs") : QLatin1String("args");
- s << INDENT << "if (!";
- if (usesNamedArguments)
- s << "PyArg_ParseTuple(" << argsVar << ", \"|" << QByteArray(maxArgs, 'O') << ':' << funcName << '"';
- else
- s << "PyArg_UnpackTuple(" << argsVar << ", \"" << funcName << "\", " << minArgs << ", " << maxArgs;
- for (int i = 0; i < maxArgs; i++)
- s << ", &(" << PYTHON_ARGS << '[' << i << "])";
- s << "))\n";
- {
- Indentation indent(INDENT);
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << Qt::endl;
-}
-
-void CppGenerator::writeCppSelfConversion(QTextStream &s, const GeneratorContext &context,
- const QString &className, bool useWrapperClass)
-{
- static const QString pythonSelfVar = QLatin1String("self");
- if (useWrapperClass)
- s << "static_cast<" << className << " *>(";
- if (!context.forSmartPointer())
- s << cpythonWrapperCPtr(context.metaClass(), pythonSelfVar);
- else
- s << cpythonWrapperCPtr(context.preciseType(), pythonSelfVar);
- if (useWrapperClass)
- s << ')';
-}
-
-void CppGenerator::writeCppSelfDefinition(QTextStream &s,
- const GeneratorContext &context,
- bool hasStaticOverload,
- bool cppSelfAsReference)
-{
- Q_ASSERT(!(cppSelfAsReference && hasStaticOverload));
-
- const AbstractMetaClass *metaClass = context.metaClass();
- bool useWrapperClass = avoidProtectedHack() && metaClass->hasProtectedMembers();
- Q_ASSERT(!useWrapperClass || context.useWrapper());
- QString className;
- if (!context.forSmartPointer()) {
- className = useWrapperClass
- ? context.wrapperName()
- : (QLatin1String("::") + metaClass->qualifiedCppName());
- } else {
- className = context.smartPointerWrapperName();
- }
-
- writeInvalidPyObjectCheck(s, QLatin1String("self"));
-
- if (cppSelfAsReference) {
- s << INDENT << "auto &" << CPP_SELF_VAR << " = *";
- writeCppSelfConversion(s, context, className, useWrapperClass);
- s << ";\n";
- return;
- }
-
- if (!hasStaticOverload) {
- s << INDENT << "auto " << CPP_SELF_VAR << " = ";
- writeCppSelfConversion(s, context, className, useWrapperClass);
- s << ";\n";
- writeUnusedVariableCast(s, QLatin1String(CPP_SELF_VAR));
- return;
- }
-
- s << INDENT << className << " *" << CPP_SELF_VAR << " = nullptr;\n";
- writeUnusedVariableCast(s, QLatin1String(CPP_SELF_VAR));
-
- // Checks if the underlying C++ object is valid.
- s << INDENT << "if (self)\n";
- {
- Indentation indent(INDENT);
- s << INDENT << CPP_SELF_VAR << " = ";
- writeCppSelfConversion(s, context, className, useWrapperClass);
- s << ";\n";
- }
-}
-
-void CppGenerator::writeCppSelfDefinition(QTextStream &s,
- const AbstractMetaFunction *func,
- const GeneratorContext &context,
- bool hasStaticOverload)
-{
- if (!func->ownerClass() || func->isConstructor())
- return;
-
- if (func->isOperatorOverload() && func->isBinaryOperator()) {
- QString checkFunc = cpythonCheckFunction(func->ownerClass()->typeEntry());
- s << INDENT << "bool isReverse = " << checkFunc << PYTHON_ARG << ")\n";
- {
- Indentation indent1(INDENT, 4);
- s << INDENT << "&& !" << checkFunc << "self);\n";
- }
- s << INDENT << "if (isReverse)\n";
- Indentation indent(INDENT);
- s << INDENT << "std::swap(self, " << PYTHON_ARG << ");\n";
- }
-
- writeCppSelfDefinition(s, context, hasStaticOverload);
-}
-
-void CppGenerator::writeErrorSection(QTextStream &s, OverloadData &overloadData)
-{
- const AbstractMetaFunction *rfunc = overloadData.referenceFunction();
- s << Qt::endl << INDENT << cpythonFunctionName(rfunc) << "_TypeError:\n";
- Indentation indentation(INDENT);
- QString funcName = fullPythonFunctionName(rfunc);
-
- QString argsVar = pythonFunctionWrapperUsesListOfArguments(overloadData)
- ? QLatin1String("args") : QLatin1String(PYTHON_ARG);
- s << INDENT << "Shiboken::setErrorAboutWrongArguments(" << argsVar << ", \"" << funcName << "\");\n";
- s << INDENT << "return " << m_currentErrorCode << ";\n";
-}
-
-void CppGenerator::writeFunctionReturnErrorCheckSection(QTextStream &s, bool hasReturnValue)
-{
- s << INDENT << "if (PyErr_Occurred()";
- if (hasReturnValue)
- s << " || !" << PYTHON_RETURN_VAR;
- s << ") {\n";
- {
- Indentation indent(INDENT);
- if (hasReturnValue)
- s << INDENT << "Py_XDECREF(" << PYTHON_RETURN_VAR << ");\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT << "}\n";
-}
-
-void CppGenerator::writeInvalidPyObjectCheck(QTextStream &s, const QString &pyObj)
-{
- s << INDENT << "if (!Shiboken::Object::isValid(" << pyObj << "))\n";
- Indentation indent(INDENT);
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
-}
-
-static QString pythonToCppConverterForArgumentName(const QString &argumentName)
-{
- static const QRegularExpression pyArgsRegex(QLatin1String(PYTHON_ARGS)
- + QLatin1String(R"((\[\d+[-]?\d*\]))"));
- Q_ASSERT(pyArgsRegex.isValid());
- const QRegularExpressionMatch match = pyArgsRegex.match(argumentName);
- QString result = QLatin1String(PYTHON_TO_CPP_VAR);
- if (match.hasMatch())
- result += match.captured(1);
- return result;
-}
-
-void CppGenerator::writeTypeCheck(QTextStream &s, const AbstractMetaType *argType,
- const QString &argumentName, bool isNumber,
- const QString &customType, bool rejectNull)
-{
- QString customCheck;
- if (!customType.isEmpty()) {
- AbstractMetaType *metaType;
- // PYSIDE-795: Note: XML-Overrides are handled in this shibokengenerator function!
- // This enables iterables for QMatrix4x4 for instance.
- customCheck = guessCPythonCheckFunction(customType, &metaType);
- if (metaType)
- argType = metaType;
- }
-
- // TODO-CONVERTER: merge this with the code below.
- QString typeCheck;
- if (customCheck.isEmpty())
- typeCheck = cpythonIsConvertibleFunction(argType, argType->isEnum() ? false : isNumber);
- else
- typeCheck = customCheck;
- typeCheck.append(QString::fromLatin1("(%1)").arg(argumentName));
-
- // TODO-CONVERTER -----------------------------------------------------------------------
- if (customCheck.isEmpty() && !argType->typeEntry()->isCustom()) {
- typeCheck = QString::fromLatin1("(%1 = %2))").arg(pythonToCppConverterForArgumentName(argumentName), typeCheck);
- if (!isNumber && argType->typeEntry()->isCppPrimitive())
- typeCheck.prepend(QString::fromLatin1("%1(%2) && ").arg(cpythonCheckFunction(argType), argumentName));
- }
- // TODO-CONVERTER -----------------------------------------------------------------------
-
- if (rejectNull)
- typeCheck = QString::fromLatin1("(%1 != Py_None && %2)").arg(argumentName, typeCheck);
-
- s << typeCheck;
-}
-
-static void checkTypeViability(const AbstractMetaFunction *func, const AbstractMetaType *type, int argIdx)
-{
- if (!type
- || !type->typeEntry()->isPrimitive()
- || type->indirections() == 0
- || (type->indirections() == 1 && type->typeUsagePattern() == AbstractMetaType::NativePointerAsArrayPattern)
- || ShibokenGenerator::isCString(type)
- || func->argumentRemoved(argIdx)
- || !func->typeReplaced(argIdx).isEmpty()
- || !func->conversionRule(TypeSystem::All, argIdx).isEmpty()
- || func->hasInjectedCode())
- return;
- QString message;
- QTextStream str(&message);
- str << "There's no user provided way (conversion rule, argument"
- " removal, custom code, etc) to handle the primitive ";
- if (argIdx == 0)
- str << "return type '" << type->cppSignature() << '\'';
- else
- str << "type '" << type->cppSignature() << "' of argument " << argIdx;
- str << " in function '";
- if (func->ownerClass())
- str << func->ownerClass()->qualifiedCppName() << "::";
- str << func->signature() << "'.";
- qCWarning(lcShiboken).noquote().nospace() << message;
-}
-
-static void checkTypeViability(const AbstractMetaFunction *func)
-{
- if (func->isUserAdded())
- return;
- const AbstractMetaType *type = func->type();
- checkTypeViability(func, type, 0);
- for (int i = 0; i < func->arguments().count(); ++i)
- checkTypeViability(func, func->arguments().at(i)->type(), i + 1);
-}
-
-void CppGenerator::writeTypeCheck(QTextStream &s, const OverloadData *overloadData, QString argumentName)
-{
- QSet<const TypeEntry *> numericTypes;
- const OverloadDataList &overloads = overloadData->previousOverloadData()->nextOverloadData();
- for (OverloadData *od : overloads) {
- const OverloadData::MetaFunctionList &odOverloads = od->overloads();
- for (const AbstractMetaFunction *func : odOverloads) {
- checkTypeViability(func);
- const AbstractMetaType *argType = od->argument(func)->type();
- if (!argType->isPrimitive())
- continue;
- if (ShibokenGenerator::isNumber(argType->typeEntry()))
- numericTypes << argType->typeEntry();
- }
- }
-
- // This condition trusts that the OverloadData object will arrange for
- // PyInt type to come after the more precise numeric types (e.g. float and bool)
- const AbstractMetaType *argType = overloadData->argType();
- bool numberType = numericTypes.count() == 1 || ShibokenGenerator::isPyInt(argType);
- QString customType = (overloadData->hasArgumentTypeReplace() ? overloadData->argumentTypeReplaced() : QString());
- bool rejectNull = shouldRejectNullPointerArgument(overloadData->referenceFunction(), overloadData->argPos());
- writeTypeCheck(s, argType, argumentName, numberType, customType, rejectNull);
-}
-
-void CppGenerator::writeArgumentConversion(QTextStream &s,
- const AbstractMetaType *argType,
- const QString &argName, const QString &pyArgName,
- const AbstractMetaClass *context,
- const QString &defaultValue,
- bool castArgumentAsUnused)
-{
- if (argType->typeEntry()->isCustom() || argType->typeEntry()->isVarargs())
- return;
- if (isWrapperType(argType))
- writeInvalidPyObjectCheck(s, pyArgName);
- writePythonToCppTypeConversion(s, argType, pyArgName, argName, context, defaultValue);
- if (castArgumentAsUnused)
- writeUnusedVariableCast(s, argName);
-}
-
-const AbstractMetaType *CppGenerator::getArgumentType(const AbstractMetaFunction *func, int argPos)
-{
- if (argPos < 0 || argPos > func->arguments().size()) {
- qCWarning(lcShiboken).noquote().nospace()
- << QStringLiteral("Argument index for function '%1' out of range.").arg(func->signature());
- return nullptr;
- }
-
- const AbstractMetaType *argType = nullptr;
- QString typeReplaced = func->typeReplaced(argPos);
- if (typeReplaced.isEmpty())
- argType = (argPos == 0) ? func->type() : func->arguments().at(argPos-1)->type();
- else
- argType = buildAbstractMetaTypeFromString(typeReplaced);
- if (!argType && !m_knownPythonTypes.contains(typeReplaced)) {
- qCWarning(lcShiboken).noquote().nospace()
- << QString::fromLatin1("Unknown type '%1' used as argument type replacement "\
- "in function '%2', the generated code may be broken.")
- .arg(typeReplaced, func->signature());
- }
- return argType;
-}
-
-static inline QString arrayHandleType(const AbstractMetaTypeCList &nestedArrayTypes)
-{
- switch (nestedArrayTypes.size()) {
- case 1:
- return QStringLiteral("Shiboken::Conversions::ArrayHandle<")
- + nestedArrayTypes.constLast()->minimalSignature()
- + QLatin1Char('>');
- case 2:
- return QStringLiteral("Shiboken::Conversions::Array2Handle<")
- + nestedArrayTypes.constLast()->minimalSignature()
- + QStringLiteral(", ")
- + QString::number(nestedArrayTypes.constFirst()->arrayElementCount())
- + QLatin1Char('>');
- }
- return QString();
-}
-
-void CppGenerator::writePythonToCppTypeConversion(QTextStream &s,
- const AbstractMetaType *type,
- const QString &pyIn,
- const QString &cppOut,
- const AbstractMetaClass * /* context */,
- const QString &defaultValue)
-{
- const TypeEntry *typeEntry = type->typeEntry();
- if (typeEntry->isCustom() || typeEntry->isVarargs())
- return;
-
- QString cppOutAux = cppOut + QLatin1String("_local");
-
- bool treatAsPointer = isValueTypeWithCopyConstructorOnly(type);
- bool isPointerOrObjectType = (isObjectType(type) || isPointer(type)) && !isUserPrimitive(type) && !isCppPrimitive(type);
- bool isNotContainerEnumOrFlags = !typeEntry->isContainer() && !typeEntry->isEnum() && !typeEntry->isFlags();
- bool mayHaveImplicitConversion = type->referenceType() == LValueReference
- && !isUserPrimitive(type)
- && !isCppPrimitive(type)
- && isNotContainerEnumOrFlags
- && !(treatAsPointer || isPointerOrObjectType);
-
- const AbstractMetaTypeCList nestedArrayTypes = type->nestedArrayTypes();
- const bool isCppPrimitiveArray = !nestedArrayTypes.isEmpty()
- && nestedArrayTypes.constLast()->isCppPrimitive();
- QString typeName = isCppPrimitiveArray
- ? arrayHandleType(nestedArrayTypes)
- : getFullTypeNameWithoutModifiers(type);
-
- bool isProtectedEnum = false;
-
- if (mayHaveImplicitConversion) {
- s << INDENT << typeName << ' ' << cppOutAux;
- writeMinimalConstructorExpression(s, type, defaultValue);
- s << ";\n";
- } else if (avoidProtectedHack() && type->typeEntry()->isEnum()) {
- const AbstractMetaEnum *metaEnum = findAbstractMetaEnum(type);
- if (metaEnum && metaEnum->isProtected()) {
- typeName = QLatin1String("long");
- isProtectedEnum = true;
- }
- }
-
- s << INDENT << typeName;
- if (isCppPrimitiveArray) {
- s << ' ' << cppOut;
- } else if (treatAsPointer || isPointerOrObjectType) {
- s << " *" << cppOut;
- if (!defaultValue.isEmpty())
- s << " = " << defaultValue;
- } else if (type->referenceType() == LValueReference && !typeEntry->isPrimitive() && isNotContainerEnumOrFlags) {
- s << " *" << cppOut << " = &" << cppOutAux;
- } else {
- s << ' ' << cppOut;
- if (isProtectedEnum && avoidProtectedHack()) {
- s << " = ";
- if (defaultValue.isEmpty())
- s << "0";
- else
- s << "(long)" << defaultValue;
- } else if (isUserPrimitive(type) || typeEntry->isEnum() || typeEntry->isFlags()) {
- writeMinimalConstructorExpression(s, typeEntry, defaultValue);
- } else if (!type->isContainer() && !type->isSmartPointer()) {
- writeMinimalConstructorExpression(s, type, defaultValue);
- }
- }
- s << ";\n";
-
- QString pythonToCppFunc = pythonToCppConverterForArgumentName(pyIn);
-
- s << INDENT;
- if (!defaultValue.isEmpty())
- s << "if (" << pythonToCppFunc << ") ";
-
- QString pythonToCppCall = QString::fromLatin1("%1(%2, &%3)").arg(pythonToCppFunc, pyIn, cppOut);
- if (!mayHaveImplicitConversion) {
- s << pythonToCppCall << ";\n";
- return;
- }
-
- if (!defaultValue.isEmpty())
- s << "{\n" << INDENT;
-
- s << "if (Shiboken::Conversions::isImplicitConversion(reinterpret_cast<SbkObjectType *>("
- << cpythonTypeNameExt(type) << "), " << pythonToCppFunc << "))\n";
- {
- Indentation indent(INDENT);
- s << INDENT << pythonToCppFunc << '(' << pyIn << ", &" << cppOutAux << ");\n";
- }
- s << INDENT << "else\n";
- {
- Indentation indent(INDENT);
- s << INDENT << pythonToCppCall << ";\n";
- }
-
- if (!defaultValue.isEmpty())
- s << INDENT << '}';
- s << Qt::endl;
-}
-
-static void addConversionRuleCodeSnippet(CodeSnipList &snippetList, QString &rule,
- TypeSystem::Language /* conversionLanguage */,
- TypeSystem::Language snippetLanguage,
- const QString &outputName = QString(),
- const QString &inputName = QString())
-{
- if (rule.isEmpty())
- return;
- if (snippetLanguage == TypeSystem::TargetLangCode) {
- rule.replace(QLatin1String("%in"), inputName);
- rule.replace(QLatin1String("%out"), outputName + QLatin1String("_out"));
- } else {
- rule.replace(QLatin1String("%out"), outputName);
- }
- CodeSnip snip(snippetLanguage);
- snip.position = (snippetLanguage == TypeSystem::NativeCode) ? TypeSystem::CodeSnipPositionAny : TypeSystem::CodeSnipPositionBeginning;
- snip.addCode(rule);
- snippetList << snip;
-}
-
-void CppGenerator::writeConversionRule(QTextStream &s, const AbstractMetaFunction *func, TypeSystem::Language language)
-{
- CodeSnipList snippets;
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (AbstractMetaArgument *arg : arguments) {
- QString rule = func->conversionRule(language, arg->argumentIndex() + 1);
- addConversionRuleCodeSnippet(snippets, rule, language, TypeSystem::TargetLangCode,
- arg->name(), arg->name());
- }
- writeCodeSnips(s, snippets, TypeSystem::CodeSnipPositionBeginning, TypeSystem::TargetLangCode, func);
-}
-
-void CppGenerator::writeConversionRule(QTextStream &s, const AbstractMetaFunction *func, TypeSystem::Language language, const QString &outputVar)
-{
- CodeSnipList snippets;
- QString rule = func->conversionRule(language, 0);
- addConversionRuleCodeSnippet(snippets, rule, language, language, outputVar);
- writeCodeSnips(s, snippets, TypeSystem::CodeSnipPositionAny, language, func);
-}
-
-void CppGenerator::writeNoneReturn(QTextStream &s, const AbstractMetaFunction *func, bool thereIsReturnValue)
-{
- if (thereIsReturnValue && (!func->type() || func->argumentRemoved(0)) && !injectedCodeHasReturnValueAttribution(func)) {
- s << INDENT << PYTHON_RETURN_VAR << " = Py_None;\n";
- s << INDENT << "Py_INCREF(Py_None);\n";
- }
-}
-
-void CppGenerator::writeOverloadedFunctionDecisor(QTextStream &s, const OverloadData &overloadData)
-{
- s << INDENT << "// Overloaded function decisor\n";
- const AbstractMetaFunction *rfunc = overloadData.referenceFunction();
- const OverloadData::MetaFunctionList &functionOverloads = overloadData.overloadsWithoutRepetition();
- for (int i = 0; i < functionOverloads.count(); i++) {
- const auto func = functionOverloads.at(i);
- s << INDENT << "// " << i << ": ";
- if (func->isStatic())
- s << "static ";
- if (const auto *decl = func->declaringClass())
- s << decl->name() << "::";
- s << func->minimalSignature() << Qt::endl;
- }
- writeOverloadedFunctionDecisorEngine(s, &overloadData);
- s << Qt::endl;
-
- // Ensure that the direct overload that called this reverse
- // is called.
- if (rfunc->isOperatorOverload() && !rfunc->isCallOperator()) {
- s << INDENT << "if (isReverse && overloadId == -1) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_NotImplementedError, \"reverse operator not implemented.\");\n";
- s << INDENT << "return {};\n";
- }
- s << INDENT << "}\n\n";
- }
-
- s << INDENT << "// Function signature not found.\n";
- s << INDENT << "if (overloadId == -1) goto " << cpythonFunctionName(overloadData.referenceFunction()) << "_TypeError;\n";
- s << Qt::endl;
-}
-
-void CppGenerator::writeOverloadedFunctionDecisorEngine(QTextStream &s, const OverloadData *parentOverloadData)
-{
- bool hasDefaultCall = parentOverloadData->nextArgumentHasDefaultValue();
- const AbstractMetaFunction *referenceFunction = parentOverloadData->referenceFunction();
-
- // If the next argument has not an argument with a default value, it is still possible
- // that one of the overloads for the current overload data has its final occurrence here.
- // If found, the final occurrence of a method is attributed to the referenceFunction
- // variable to be used further on this method on the conditional that identifies default
- // method calls.
- if (!hasDefaultCall) {
- const OverloadData::MetaFunctionList &overloads = parentOverloadData->overloads();
- for (const AbstractMetaFunction *func : overloads) {
- if (parentOverloadData->isFinalOccurrence(func)) {
- referenceFunction = func;
- hasDefaultCall = true;
- break;
- }
- }
- }
-
- int maxArgs = parentOverloadData->maxArgs();
- // Python constructors always receive multiple arguments.
- bool usePyArgs = pythonFunctionWrapperUsesListOfArguments(*parentOverloadData);
-
- // Functions without arguments are identified right away.
- if (maxArgs == 0) {
- s << INDENT << "overloadId = " << parentOverloadData->headOverloadData()->overloads().indexOf(referenceFunction);
- s << "; // " << referenceFunction->minimalSignature() << Qt::endl;
- return;
-
- }
- // To decide if a method call is possible at this point the current overload
- // data object cannot be the head, since it is just an entry point, or a root,
- // for the tree of arguments and it does not represent a valid method call.
- if (!parentOverloadData->isHeadOverloadData()) {
- bool isLastArgument = parentOverloadData->nextOverloadData().isEmpty();
- bool signatureFound = parentOverloadData->overloads().size() == 1;
-
- // The current overload data describes the last argument of a signature,
- // so the method can be identified right now.
- if (isLastArgument || (signatureFound && !hasDefaultCall)) {
- const AbstractMetaFunction *func = parentOverloadData->referenceFunction();
- s << INDENT << "overloadId = " << parentOverloadData->headOverloadData()->overloads().indexOf(func);
- s << "; // " << func->minimalSignature() << Qt::endl;
- return;
- }
- }
-
- bool isFirst = true;
-
- // If the next argument has a default value the decisor can perform a method call;
- // it just need to check if the number of arguments received from Python are equal
- // to the number of parameters preceding the argument with the default value.
- const OverloadDataList &overloads = parentOverloadData->nextOverloadData();
- if (hasDefaultCall) {
- isFirst = false;
- int numArgs = parentOverloadData->argPos() + 1;
- s << INDENT << "if (numArgs == " << numArgs << ") {\n";
- {
- Indentation indent(INDENT);
- const AbstractMetaFunction *func = referenceFunction;
- for (OverloadData *overloadData : overloads) {
- const AbstractMetaFunction *defValFunc = overloadData->getFunctionWithDefaultValue();
- if (defValFunc) {
- func = defValFunc;
- break;
- }
- }
- s << INDENT << "overloadId = " << parentOverloadData->headOverloadData()->overloads().indexOf(func);
- s << "; // " << func->minimalSignature() << Qt::endl;
- }
- s << INDENT << '}';
- }
-
- for (OverloadData *overloadData : overloads) {
- bool signatureFound = overloadData->overloads().size() == 1
- && !overloadData->getFunctionWithDefaultValue()
- && !overloadData->findNextArgWithDefault();
-
- const AbstractMetaFunction *refFunc = overloadData->referenceFunction();
-
- QStringList typeChecks;
-
- QString pyArgName = (usePyArgs && maxArgs > 1)
- ? pythonArgsAt(overloadData->argPos())
- : QLatin1String(PYTHON_ARG);
- OverloadData *od = overloadData;
- int startArg = od->argPos();
- int sequenceArgCount = 0;
- while (od && !od->argType()->isVarargs()) {
- bool typeReplacedByPyObject = od->argumentTypeReplaced() == QLatin1String("PyObject");
- if (!typeReplacedByPyObject) {
- if (usePyArgs)
- pyArgName = pythonArgsAt(od->argPos());
- QString typeCheck;
- QTextStream tck(&typeCheck);
- const AbstractMetaFunction *func = od->referenceFunction();
-
- if (func->isConstructor() && func->arguments().count() == 1) {
- const AbstractMetaClass *ownerClass = func->ownerClass();
- const ComplexTypeEntry *baseContainerType = ownerClass->typeEntry()->baseContainerType();
- if (baseContainerType && baseContainerType == func->arguments().constFirst()->type()->typeEntry() && isCopyable(ownerClass)) {
- tck << '!' << cpythonCheckFunction(ownerClass->typeEntry()) << pyArgName << ")\n";
- Indentation indent(INDENT);
- tck << INDENT << "&& ";
- }
- }
- writeTypeCheck(tck, od, pyArgName);
- typeChecks << typeCheck;
- }
-
- sequenceArgCount++;
-
- if (od->nextOverloadData().isEmpty()
- || od->nextArgumentHasDefaultValue()
- || od->nextOverloadData().size() != 1
- || od->overloads().size() != od->nextOverloadData().constFirst()->overloads().size()) {
- overloadData = od;
- od = nullptr;
- } else {
- od = od->nextOverloadData().constFirst();
- }
- }
-
- if (usePyArgs && signatureFound) {
- AbstractMetaArgumentList args = refFunc->arguments();
- const bool isVarargs = args.size() > 1 && args.constLast()->type()->isVarargs();
- int numArgs = args.size() - OverloadData::numberOfRemovedArguments(refFunc);
- if (isVarargs)
- --numArgs;
- typeChecks.prepend(QString::fromLatin1("numArgs %1 %2").arg(isVarargs ? QLatin1String(">=") : QLatin1String("==")).arg(numArgs));
- } else if (sequenceArgCount > 1) {
- typeChecks.prepend(QString::fromLatin1("numArgs >= %1").arg(startArg + sequenceArgCount));
- } else if (refFunc->isOperatorOverload() && !refFunc->isCallOperator()) {
- typeChecks.prepend(QString::fromLatin1("%1isReverse").arg(refFunc->isReverseOperator() ? QString() : QLatin1String("!")));
- }
-
- if (isFirst) {
- isFirst = false;
- s << INDENT;
- } else {
- s << " else ";
- }
- s << "if (";
- if (typeChecks.isEmpty()) {
- s << "true";
- } else {
- Indentation indent(INDENT);
- QString separator;
- QTextStream sep(&separator);
- sep << Qt::endl << INDENT << "&& ";
- s << typeChecks.join(separator);
- }
- s << ") {\n";
- {
- Indentation indent(INDENT);
- writeOverloadedFunctionDecisorEngine(s, overloadData);
- }
- s << INDENT << "}";
- }
- s << Qt::endl;
-}
-
-void CppGenerator::writeFunctionCalls(QTextStream &s, const OverloadData &overloadData,
- const GeneratorContext &context)
-{
- const OverloadData::MetaFunctionList &overloads = overloadData.overloadsWithoutRepetition();
- s << INDENT << "// Call function/method\n";
- s << INDENT << (overloads.count() > 1 ? "switch (overloadId) " : "") << "{\n";
- {
- Indentation indent(INDENT);
- if (overloads.count() == 1) {
- writeSingleFunctionCall(s, overloadData, overloads.constFirst(), context);
- } else {
- for (int i = 0; i < overloads.count(); i++) {
- const AbstractMetaFunction *func = overloads.at(i);
- s << INDENT << "case " << i << ": // " << func->signature() << Qt::endl;
- s << INDENT << "{\n";
- {
- Indentation indent(INDENT);
- writeSingleFunctionCall(s, overloadData, func, context);
- if (func->attributes().testFlag(AbstractMetaAttributes::Deprecated)) {
- s << INDENT << "PyErr_WarnEx(PyExc_DeprecationWarning, \"";
- if (auto cls = context.metaClass())
- s << cls->name() << '.';
- s << func->signature() << " is deprecated\", 1);\n";
- }
- s << INDENT << "break;\n";
- }
- s << INDENT << "}\n";
- }
- }
- }
- s << INDENT << "}\n";
-}
-
-void CppGenerator::writeSingleFunctionCall(QTextStream &s,
- const OverloadData &overloadData,
- const AbstractMetaFunction *func,
- const GeneratorContext &context)
-{
- if (func->isDeprecated()) {
- s << INDENT << "Shiboken::warning(PyExc_DeprecationWarning, 1, \"Function: '"
- << func->signature().replace(QLatin1String("::"), QLatin1String("."))
- << "' is marked as deprecated, please check the documentation for more information.\");\n";
- }
-
- if (func->functionType() == AbstractMetaFunction::EmptyFunction) {
- s << INDENT << "PyErr_Format(PyExc_TypeError, \"%s is a private method.\", \""
- << func->signature().replace(QLatin1String("::"), QLatin1String("."))
- << "\");\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- return;
- }
-
- bool usePyArgs = pythonFunctionWrapperUsesListOfArguments(overloadData);
-
- // Handle named arguments.
- writeNamedArgumentResolution(s, func, usePyArgs);
-
- bool injectCodeCallsFunc = injectedCodeCallsCppFunction(context, func);
- bool mayHaveUnunsedArguments = !func->isUserAdded() && func->hasInjectedCode() && injectCodeCallsFunc;
- int removedArgs = 0;
- for (int argIdx = 0; argIdx < func->arguments().count(); ++argIdx) {
- bool hasConversionRule = !func->conversionRule(TypeSystem::NativeCode, argIdx + 1).isEmpty();
- const AbstractMetaArgument *arg = func->arguments().at(argIdx);
- if (func->argumentRemoved(argIdx + 1)) {
- if (!arg->defaultValueExpression().isEmpty()) {
- const QString cppArgRemoved = QLatin1String(CPP_ARG_REMOVED)
- + QString::number(argIdx);
- s << INDENT << getFullTypeName(arg->type()) << ' ' << cppArgRemoved;
- s << " = " << guessScopeForDefaultValue(func, arg) << ";\n";
- writeUnusedVariableCast(s, cppArgRemoved);
- } else if (!injectCodeCallsFunc && !func->isUserAdded() && !hasConversionRule) {
- // When an argument is removed from a method signature and no other means of calling
- // the method are provided (as with code injection) the generator must abort.
- qFatal("No way to call '%s::%s' with the modifications described in the type system.",
- qPrintable(func->ownerClass()->name()), qPrintable(func->signature()));
- }
- removedArgs++;
- continue;
- }
- if (hasConversionRule)
- continue;
- const AbstractMetaType *argType = getArgumentType(func, argIdx + 1);
- if (!argType || (mayHaveUnunsedArguments && !injectedCodeUsesArgument(func, argIdx)))
- continue;
- int argPos = argIdx - removedArgs;
- QString argName = QLatin1String(CPP_ARG) + QString::number(argPos);
- QString pyArgName = usePyArgs ? pythonArgsAt(argPos) : QLatin1String(PYTHON_ARG);
- QString defaultValue = guessScopeForDefaultValue(func, arg);
- writeArgumentConversion(s, argType, argName, pyArgName, func->implementingClass(), defaultValue, func->isUserAdded());
- }
-
- s << Qt::endl;
-
- int numRemovedArgs = OverloadData::numberOfRemovedArguments(func);
-
- s << INDENT << "if (!PyErr_Occurred()) {\n";
- {
- Indentation indentation(INDENT);
- writeMethodCall(s, func, context, func->arguments().size() - numRemovedArgs);
- if (!func->isConstructor())
- writeNoneReturn(s, func, overloadData.hasNonVoidReturnType());
- }
- s << INDENT << "}\n";
-}
-
-QString CppGenerator::cppToPythonFunctionName(const QString &sourceTypeName, QString targetTypeName)
-{
- if (targetTypeName.isEmpty())
- targetTypeName = sourceTypeName;
- return QString::fromLatin1("%1_CppToPython_%2").arg(sourceTypeName, targetTypeName);
-}
-
-QString CppGenerator::pythonToCppFunctionName(const QString &sourceTypeName, const QString &targetTypeName)
-{
- return QString::fromLatin1("%1_PythonToCpp_%2").arg(sourceTypeName, targetTypeName);
-}
-QString CppGenerator::pythonToCppFunctionName(const AbstractMetaType *sourceType, const AbstractMetaType *targetType)
-{
- return pythonToCppFunctionName(fixedCppTypeName(sourceType), fixedCppTypeName(targetType));
-}
-QString CppGenerator::pythonToCppFunctionName(const CustomConversion::TargetToNativeConversion *toNative,
- const TypeEntry *targetType)
-{
- return pythonToCppFunctionName(fixedCppTypeName(toNative), fixedCppTypeName(targetType));
-}
-
-QString CppGenerator::convertibleToCppFunctionName(const QString &sourceTypeName, const QString &targetTypeName)
-{
- return QString::fromLatin1("is_%1_PythonToCpp_%2_Convertible").arg(sourceTypeName, targetTypeName);
-}
-QString CppGenerator::convertibleToCppFunctionName(const AbstractMetaType *sourceType, const AbstractMetaType *targetType)
-{
- return convertibleToCppFunctionName(fixedCppTypeName(sourceType), fixedCppTypeName(targetType));
-}
-QString CppGenerator::convertibleToCppFunctionName(const CustomConversion::TargetToNativeConversion *toNative,
- const TypeEntry *targetType)
-{
- return convertibleToCppFunctionName(fixedCppTypeName(toNative), fixedCppTypeName(targetType));
-}
-
-void CppGenerator::writeCppToPythonFunction(QTextStream &s, const QString &code, const QString &sourceTypeName, QString targetTypeName)
-{
- QString prettyCode;
- QTextStream c(&prettyCode);
- formatCode(c, code, INDENT);
- processCodeSnip(prettyCode);
-
- s << "static PyObject *" << cppToPythonFunctionName(sourceTypeName, targetTypeName);
- s << "(const void *cppIn) {\n";
- s << prettyCode;
- s << "}\n";
-}
-
-static void replaceCppToPythonVariables(QString &code, const QString &typeName)
-{
- code.prepend(QLatin1String("auto &cppInRef = *reinterpret_cast<")
- + typeName + QLatin1String(" *>(const_cast<void *>(cppIn));\n"));
- code.replace(QLatin1String("%INTYPE"), typeName);
- code.replace(QLatin1String("%OUTTYPE"), QLatin1String("PyObject *"));
- code.replace(QLatin1String("%in"), QLatin1String("cppInRef"));
- code.replace(QLatin1String("%out"), QLatin1String("pyOut"));
-}
-void CppGenerator::writeCppToPythonFunction(QTextStream &s, const CustomConversion *customConversion)
-{
- QString code = customConversion->nativeToTargetConversion();
- replaceCppToPythonVariables(code, getFullTypeName(customConversion->ownerType()));
- writeCppToPythonFunction(s, code, fixedCppTypeName(customConversion->ownerType()));
-}
-void CppGenerator::writeCppToPythonFunction(QTextStream &s, const AbstractMetaType *containerType)
-{
- const CustomConversion *customConversion = containerType->typeEntry()->customConversion();
- if (!customConversion) {
- qFatal("Can't write the C++ to Python conversion function for container type '%s' - "\
- "no conversion rule was defined for it in the type system.",
- qPrintable(containerType->typeEntry()->qualifiedCppName()));
- }
- if (!containerType->typeEntry()->isContainer()) {
- writeCppToPythonFunction(s, customConversion);
- return;
- }
- QString code = customConversion->nativeToTargetConversion();
- for (int i = 0; i < containerType->instantiations().count(); ++i) {
- AbstractMetaType *type = containerType->instantiations().at(i);
- QString typeName = getFullTypeName(type);
- if (type->isConstant())
- typeName = QLatin1String("const ") + typeName;
- code.replace(QString::fromLatin1("%INTYPE_%1").arg(i), typeName);
- }
- replaceCppToPythonVariables(code, getFullTypeNameWithoutModifiers(containerType));
- processCodeSnip(code);
- writeCppToPythonFunction(s, code, fixedCppTypeName(containerType));
-}
-
-void CppGenerator::writePythonToCppFunction(QTextStream &s, const QString &code, const QString &sourceTypeName, const QString &targetTypeName)
-{
- QString prettyCode;
- QTextStream c(&prettyCode);
- formatCode(c, code, INDENT);
- processCodeSnip(prettyCode);
- s << "static void " << pythonToCppFunctionName(sourceTypeName, targetTypeName);
- s << "(PyObject *pyIn, void *cppOut) {\n";
- s << prettyCode;
- s << "}\n";
-}
-
-void CppGenerator::writeIsPythonConvertibleToCppFunction(QTextStream &s,
- const QString &sourceTypeName,
- const QString &targetTypeName,
- const QString &condition,
- QString pythonToCppFuncName,
- bool acceptNoneAsCppNull)
-{
- if (pythonToCppFuncName.isEmpty())
- pythonToCppFuncName = pythonToCppFunctionName(sourceTypeName, targetTypeName);
-
- s << "static PythonToCppFunc " << convertibleToCppFunctionName(sourceTypeName, targetTypeName);
- s << "(PyObject *pyIn) {\n";
- if (acceptNoneAsCppNull) {
- s << INDENT << "if (pyIn == Py_None)\n";
- Indentation indent(INDENT);
- s << INDENT << "return Shiboken::Conversions::nonePythonToCppNullPtr;\n";
- }
- s << INDENT << "if (" << condition << ")\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return " << pythonToCppFuncName << ";\n";
- }
- s << INDENT << "return {};\n";
- s << "}\n";
-}
-
-void CppGenerator::writePythonToCppConversionFunctions(QTextStream &s,
- const AbstractMetaType *sourceType,
- const AbstractMetaType *targetType,
- QString typeCheck,
- QString conversion,
- const QString &preConversion)
-{
- QString sourcePyType = cpythonTypeNameExt(sourceType);
-
- // Python to C++ conversion function.
- QString code;
- QTextStream c(&code);
- if (conversion.isEmpty())
- conversion = QLatin1Char('*') + cpythonWrapperCPtr(sourceType->typeEntry(), QLatin1String("pyIn"));
- if (!preConversion.isEmpty())
- c << INDENT << preConversion << Qt::endl;
- const QString fullTypeName = getFullTypeName(targetType->typeEntry());
- c << INDENT << "*reinterpret_cast<" << fullTypeName << " *>(cppOut) = "
- << fullTypeName << '(' << conversion << ");";
- QString sourceTypeName = fixedCppTypeName(sourceType);
- QString targetTypeName = fixedCppTypeName(targetType);
- writePythonToCppFunction(s, code, sourceTypeName, targetTypeName);
-
- // Python to C++ convertible check function.
- if (typeCheck.isEmpty())
- typeCheck = QString::fromLatin1("PyObject_TypeCheck(pyIn, %1)").arg(sourcePyType);
- writeIsPythonConvertibleToCppFunction(s, sourceTypeName, targetTypeName, typeCheck);
- s << Qt::endl;
-}
-
-void CppGenerator::writePythonToCppConversionFunctions(QTextStream &s,
- const CustomConversion::TargetToNativeConversion *toNative,
- const TypeEntry *targetType)
-{
- // Python to C++ conversion function.
- QString code = toNative->conversion();
- QString inType;
- if (toNative->sourceType())
- inType = cpythonTypeNameExt(toNative->sourceType());
- else
- inType = QString::fromLatin1("(%1_TypeF())").arg(toNative->sourceTypeName());
- code.replace(QLatin1String("%INTYPE"), inType);
- code.replace(QLatin1String("%OUTTYPE"), targetType->qualifiedCppName());
- code.replace(QLatin1String("%in"), QLatin1String("pyIn"));
- code.replace(QLatin1String("%out"),
- QLatin1String("*reinterpret_cast<") + getFullTypeName(targetType) + QLatin1String(" *>(cppOut)"));
-
- QString sourceTypeName = fixedCppTypeName(toNative);
- QString targetTypeName = fixedCppTypeName(targetType);
- writePythonToCppFunction(s, code, sourceTypeName, targetTypeName);
-
- // Python to C++ convertible check function.
- QString typeCheck = toNative->sourceTypeCheck();
- if (typeCheck.isEmpty()) {
- QString pyTypeName = toNative->sourceTypeName();
- if (pyTypeName == QLatin1String("Py_None") || pyTypeName == QLatin1String("PyNone"))
- typeCheck = QLatin1String("%in == Py_None");
- else if (pyTypeName == QLatin1String("SbkEnumType"))
- typeCheck = QLatin1String("Shiboken::isShibokenEnum(%in)");
- else if (pyTypeName == QLatin1String("SbkObject"))
- typeCheck = QLatin1String("Shiboken::Object::checkType(%in)");
- else if (pyTypeName == QLatin1String("PyTypeObject"))
- typeCheck = QLatin1String("PyType_Check(%in)");
- else if (pyTypeName == QLatin1String("PyObject"))
- typeCheck = QLatin1String("PyObject_TypeCheck(%in, &PyBaseObject_Type)");
- // PYSIDE-795: We abuse PySequence for iterables
- else if (pyTypeName == QLatin1String("PySequence"))
- typeCheck = QLatin1String("Shiboken::String::checkIterable(%in)");
- else if (pyTypeName.startsWith(QLatin1String("Py")))
- typeCheck = pyTypeName + QLatin1String("_Check(%in)");
- }
- if (typeCheck.isEmpty()) {
- if (!toNative->sourceType() || toNative->sourceType()->isPrimitive()) {
- qFatal("User added implicit conversion for C++ type '%s' must provide either an input "\
- "type check function or a non primitive type entry.",
- qPrintable(targetType->qualifiedCppName()));
-
- }
- typeCheck = QString::fromLatin1("PyObject_TypeCheck(%in, %1)").arg(cpythonTypeNameExt(toNative->sourceType()));
- }
- typeCheck.replace(QLatin1String("%in"), QLatin1String("pyIn"));
- processCodeSnip(typeCheck);
- writeIsPythonConvertibleToCppFunction(s, sourceTypeName, targetTypeName, typeCheck);
-}
-
-void CppGenerator::writePythonToCppConversionFunctions(QTextStream &s, const AbstractMetaType *containerType)
-{
- const CustomConversion *customConversion = containerType->typeEntry()->customConversion();
- if (!customConversion) {
- //qFatal
- return;
- }
- const CustomConversion::TargetToNativeConversions &toCppConversions = customConversion->targetToNativeConversions();
- if (toCppConversions.isEmpty()) {
- //qFatal
- return;
- }
- // Python to C++ conversion function.
- QString cppTypeName = getFullTypeNameWithoutModifiers(containerType);
- QString code;
- QTextStream c(&code);
- c << INDENT << "auto &cppOutRef = *reinterpret_cast<"
- << cppTypeName << " *>(cppOut);\n";
- code.append(toCppConversions.constFirst()->conversion());
- for (int i = 0; i < containerType->instantiations().count(); ++i) {
- const AbstractMetaType *type = containerType->instantiations().at(i);
- QString typeName = getFullTypeName(type);
- if (type->isValue() && isValueTypeWithCopyConstructorOnly(type)) {
- for (int pos = 0; ; ) {
- const QRegularExpressionMatch match = convertToCppRegEx().match(code, pos);
- if (!match.hasMatch())
- break;
- pos = match.capturedEnd();
- const QString varName = match.captured(1);
- QString rightCode = code.mid(pos);
- rightCode.replace(varName, QLatin1Char('*') + varName);
- code.replace(pos, code.size() - pos, rightCode);
- }
- typeName.append(QLatin1String(" *"));
- }
- code.replace(QString::fromLatin1("%OUTTYPE_%1").arg(i), typeName);
- }
- code.replace(QLatin1String("%OUTTYPE"), cppTypeName);
- code.replace(QLatin1String("%in"), QLatin1String("pyIn"));
- code.replace(QLatin1String("%out"), QLatin1String("cppOutRef"));
- QString typeName = fixedCppTypeName(containerType);
- writePythonToCppFunction(s, code, typeName, typeName);
-
- // Python to C++ convertible check function.
- QString typeCheck = cpythonCheckFunction(containerType);
- if (typeCheck.isEmpty())
- typeCheck = QLatin1String("false");
- else
- typeCheck = QString::fromLatin1("%1pyIn)").arg(typeCheck);
- writeIsPythonConvertibleToCppFunction(s, typeName, typeName, typeCheck);
- s << Qt::endl;
-}
-
-void CppGenerator::writeAddPythonToCppConversion(QTextStream &s, const QString &converterVar, const QString &pythonToCppFunc, const QString &isConvertibleFunc)
-{
- s << INDENT << "Shiboken::Conversions::addPythonToCppValueConversion(" << converterVar << ',' << Qt::endl;
- {
- Indentation indent(INDENT);
- s << INDENT << pythonToCppFunc << ',' << Qt::endl;
- s << INDENT << isConvertibleFunc;
- }
- s << ");\n";
-}
-
-void CppGenerator::writeNamedArgumentResolution(QTextStream &s, const AbstractMetaFunction *func, bool usePyArgs)
-{
- const AbstractMetaArgumentList &args = OverloadData::getArgumentsWithDefaultValues(func);
- if (args.isEmpty())
- return;
-
- QString pyErrString(QLatin1String("PyErr_SetString(PyExc_TypeError, \"") + fullPythonFunctionName(func)
- + QLatin1String("(): got multiple values for keyword argument '%1'.\");"));
-
- s << INDENT << "if (kwds) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyObject *keyName = nullptr;\n";
- s << INDENT << "PyObject *value = nullptr;\n";
- for (const AbstractMetaArgument *arg : args) {
- int pyArgIndex = arg->argumentIndex() - OverloadData::numberOfRemovedArguments(func, arg->argumentIndex());
- QString pyArgName = usePyArgs ? pythonArgsAt(pyArgIndex) : QLatin1String(PYTHON_ARG);
- s << INDENT << "keyName = Py_BuildValue(\"s\",\"" << arg->name() << "\");\n";
- s << INDENT << "if (PyDict_Contains(kwds, keyName)) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "value = PyDict_GetItem(kwds, keyName);\n";
- s << INDENT << "if (value && " << pyArgName << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << pyErrString.arg(arg->name()) << Qt::endl;
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT << "}\n";
- s << INDENT << "if (value) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << pyArgName << " = value;\n";
- s << INDENT << "if (!";
- writeTypeCheck(s, arg->type(), pyArgName, isNumber(arg->type()->typeEntry()), func->typeReplaced(arg->argumentIndex() + 1));
- s << ")\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "goto " << cpythonFunctionName(func) << "_TypeError;\n";
- }
- }
- s << INDENT << "}\n";
- }
- s << INDENT << "}\n";
- }
- }
- s << INDENT << "}\n";
-}
-
-QString CppGenerator::argumentNameFromIndex(const AbstractMetaFunction *func, int argIndex, const AbstractMetaClass **wrappedClass)
-{
- *wrappedClass = nullptr;
- QString pyArgName;
- if (argIndex == -1) {
- pyArgName = QLatin1String("self");
- *wrappedClass = func->implementingClass();
- } else if (argIndex == 0) {
- AbstractMetaType *funcType = func->type();
- AbstractMetaType *returnType = getTypeWithoutContainer(funcType);
- if (returnType) {
- pyArgName = QLatin1String(PYTHON_RETURN_VAR);
- *wrappedClass = AbstractMetaClass::findClass(classes(), returnType->typeEntry());
- } else {
- QString message = QLatin1String("Invalid Argument index (0, return value) on function modification: ")
- + (funcType ? funcType->name() : QLatin1String("void")) + QLatin1Char(' ');
- if (const AbstractMetaClass *declaringClass = func->declaringClass())
- message += declaringClass->name() + QLatin1String("::");
- message += func->name() + QLatin1String("()");
- qCWarning(lcShiboken).noquote().nospace() << message;
- }
- } else {
- int realIndex = argIndex - 1 - OverloadData::numberOfRemovedArguments(func, argIndex - 1);
- AbstractMetaType *argType = getTypeWithoutContainer(func->arguments().at(realIndex)->type());
-
- if (argType) {
- *wrappedClass = AbstractMetaClass::findClass(classes(), argType->typeEntry());
- if (argIndex == 1
- && !func->isConstructor()
- && OverloadData::isSingleArgument(getFunctionGroups(func->implementingClass())[func->name()]))
- pyArgName = QLatin1String(PYTHON_ARG);
- else
- pyArgName = pythonArgsAt(argIndex - 1);
- }
- }
- return pyArgName;
-}
-
-static QStringList defaultExceptionHandling()
-{
- static const QStringList result{
- QLatin1String("} catch (const std::exception &e) {"),
- QLatin1String(" PyErr_SetString(PyExc_RuntimeError, e.what());"),
- QLatin1String("} catch (...) {"),
- QLatin1String(" PyErr_SetString(PyExc_RuntimeError, \"An unknown exception was caught\");"),
- QLatin1String("}")};
- return result;
-}
-
-void CppGenerator::writeMethodCall(QTextStream &s, const AbstractMetaFunction *func,
- const GeneratorContext &context, int maxArgs)
-{
- s << INDENT << "// " << func->minimalSignature() << (func->isReverseOperator() ? " [reverse operator]": "") << Qt::endl;
- if (func->isConstructor()) {
- const CodeSnipList &snips = func->injectedCodeSnips();
- for (const CodeSnip &cs : snips) {
- if (cs.position == TypeSystem::CodeSnipPositionEnd) {
- auto klass = func->ownerClass();
- s << INDENT << "overloadId = "
- << klass->functions().indexOf(const_cast<AbstractMetaFunction *>(func))
- << ";\n";
- break;
- }
- }
- }
-
- if (func->isAbstract()) {
- s << INDENT << "if (Shiboken::Object::hasCppWrapper(reinterpret_cast<SbkObject *>(self))) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_NotImplementedError, \"pure virtual method '";
- s << func->ownerClass()->name() << '.' << func->name() << "()' not implemented.\");\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT << "}\n";
- }
-
- // Used to provide contextual information to custom code writer function.
- const AbstractMetaArgument *lastArg = nullptr;
-
- CodeSnipList snips;
- if (func->hasInjectedCode()) {
- snips = func->injectedCodeSnips();
-
- // Find the last argument available in the method call to provide
- // the injected code writer with information to avoid invalid replacements
- // on the %# variable.
- if (maxArgs > 0 && maxArgs < func->arguments().size() - OverloadData::numberOfRemovedArguments(func)) {
- int removedArgs = 0;
- for (int i = 0; i < maxArgs + removedArgs; i++) {
- lastArg = func->arguments().at(i);
- if (func->argumentRemoved(i + 1))
- removedArgs++;
- }
- } else if (maxArgs != 0 && !func->arguments().isEmpty()) {
- lastArg = func->arguments().constLast();
- }
-
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionBeginning, TypeSystem::TargetLangCode, func, lastArg);
- s << Qt::endl;
- }
-
- writeConversionRule(s, func, TypeSystem::NativeCode);
-
- if (!func->isUserAdded()) {
- QStringList userArgs;
- if (func->functionType() != AbstractMetaFunction::CopyConstructorFunction) {
- int removedArgs = 0;
- for (int i = 0; i < maxArgs + removedArgs; i++) {
- const AbstractMetaArgument *arg = func->arguments().at(i);
- bool hasConversionRule = !func->conversionRule(TypeSystem::NativeCode, arg->argumentIndex() + 1).isEmpty();
- if (func->argumentRemoved(i + 1)) {
- // If some argument with default value is removed from a
- // method signature, the said value must be explicitly
- // added to the method call.
- removedArgs++;
-
- // If have conversion rules I will use this for removed args
- if (hasConversionRule)
- userArgs << arg->name() + QLatin1String(CONV_RULE_OUT_VAR_SUFFIX);
- else if (!arg->defaultValueExpression().isEmpty())
- userArgs.append(QLatin1String(CPP_ARG_REMOVED) + QString::number(i));
- } else {
- int idx = arg->argumentIndex() - removedArgs;
- bool deRef = isValueTypeWithCopyConstructorOnly(arg->type())
- || isObjectTypeUsedAsValueType(arg->type())
- || (arg->type()->referenceType() == LValueReference && isWrapperType(arg->type()) && !isPointer(arg->type()));
- if (hasConversionRule) {
- userArgs.append(arg->name() + QLatin1String(CONV_RULE_OUT_VAR_SUFFIX));
- } else {
- QString argName;
- if (deRef)
- argName += QLatin1Char('*');
- argName += QLatin1String(CPP_ARG) + QString::number(idx);
- userArgs.append(argName);
- }
- }
- }
-
- // If any argument's default value was modified the method must be called
- // with this new value whenever the user doesn't pass an explicit value to it.
- // Also, any unmodified default value coming after the last user specified
- // argument and before the modified argument must be explicitly stated.
- QStringList otherArgs;
- bool otherArgsModified = false;
- bool argsClear = true;
- for (int i = func->arguments().size() - 1; i >= maxArgs + removedArgs; i--) {
- const AbstractMetaArgument *arg = func->arguments().at(i);
- const bool defValModified = arg->hasModifiedDefaultValueExpression();
- bool hasConversionRule = !func->conversionRule(TypeSystem::NativeCode, arg->argumentIndex() + 1).isEmpty();
- if (argsClear && !defValModified && !hasConversionRule)
- continue;
- argsClear = false;
- otherArgsModified |= defValModified || hasConversionRule || func->argumentRemoved(i + 1);
- if (hasConversionRule)
- otherArgs.prepend(arg->name() + QLatin1String(CONV_RULE_OUT_VAR_SUFFIX));
- else
- otherArgs.prepend(QLatin1String(CPP_ARG_REMOVED) + QString::number(i));
- }
- if (otherArgsModified)
- userArgs << otherArgs;
- }
-
- bool isCtor = false;
- QString methodCall;
- QTextStream mc(&methodCall);
- QString useVAddr;
- QTextStream uva(&useVAddr);
- if (func->isOperatorOverload() && !func->isCallOperator()) {
- QString firstArg(QLatin1Char('('));
- if (!func->isPointerOperator()) // no de-reference operator
- firstArg += QLatin1Char('*');
- firstArg += QLatin1String(CPP_SELF_VAR);
- firstArg += QLatin1Char(')');
- QString secondArg = QLatin1String(CPP_ARG0);
- if (!func->isUnaryOperator() && shouldDereferenceArgumentPointer(func->arguments().constFirst())) {
- secondArg.prepend(QLatin1String("(*"));
- secondArg.append(QLatin1Char(')'));
- }
-
- if (func->isUnaryOperator())
- std::swap(firstArg, secondArg);
-
- QString op = func->originalName();
- op.remove(0, int(std::strlen("operator")));
-
- if (func->isBinaryOperator()) {
- if (func->isReverseOperator())
- std::swap(firstArg, secondArg);
-
- if (((op == QLatin1String("++")) || (op == QLatin1String("--"))) && !func->isReverseOperator()) {
- s << Qt::endl << INDENT << "for (int i=0; i < " << secondArg << "; i++, " << firstArg << op << ");\n";
- mc << firstArg;
- } else {
- mc << firstArg << ' ' << op << ' ' << secondArg;
- }
- } else {
- mc << op << ' ' << secondArg;
- }
- } else if (!injectedCodeCallsCppFunction(context, func)) {
- if (func->isConstructor()) {
- isCtor = true;
- const auto owner = func->ownerClass();
- Q_ASSERT(owner == context.metaClass());
- QString className = context.useWrapper()
- ? context.wrapperName() : owner->qualifiedCppName();
-
- if (func->functionType() == AbstractMetaFunction::CopyConstructorFunction && maxArgs == 1) {
- mc << "new ::" << className << "(*" << CPP_ARG0 << ')';
- } else {
- QString ctorCall = className + QLatin1Char('(') + userArgs.join(QLatin1String(", ")) + QLatin1Char(')');
- if (usePySideExtensions() && owner->isQObject()) {
- s << INDENT << "void *addr = PySide::nextQObjectMemoryAddr();\n";
- uva << "if (addr) {\n";
- {
- Indentation indent(INDENT);
-
- uva << INDENT << "cptr = " << "new (addr) ::"
- << ctorCall << ";\n"
- << INDENT
- << "PySide::setNextQObjectMemoryAddr(0);"
- << Qt::endl;
- }
- uva << INDENT << "} else {\n";
- {
- Indentation indent(INDENT);
-
- uva << INDENT << "cptr = " << "new ::"
- << ctorCall << ";\n";
- }
- uva << INDENT << "}\n";
- } else {
- mc << "new ::" << ctorCall;
- }
- }
- } else {
- QString methodCallClassName;
- if (context.forSmartPointer())
- methodCallClassName = context.preciseType()->cppSignature();
- else if (func->ownerClass())
- methodCallClassName = func->ownerClass()->qualifiedCppName();
-
- if (func->ownerClass()) {
- if (!avoidProtectedHack() || !func->isProtected()) {
- if (func->isStatic()) {
- mc << "::" << methodCallClassName << "::";
- } else {
- const QString selfVarCast = func->ownerClass() == func->implementingClass()
- ? QLatin1String(CPP_SELF_VAR)
- : QLatin1String("reinterpret_cast<") + methodCallClassName
- + QLatin1String(" *>(") + QLatin1String(CPP_SELF_VAR) + QLatin1Char(')');
- if (func->isConstant()) {
- if (avoidProtectedHack()) {
- mc << "const_cast<const ::";
- if (func->ownerClass()->hasProtectedMembers()) {
- // PYSIDE-500: Need a special wrapper cast when inherited
- const QString selfWrapCast = func->ownerClass() == func->implementingClass()
- ? QLatin1String(CPP_SELF_VAR)
- : QLatin1String("reinterpret_cast<") + wrapperName(func->ownerClass())
- + QLatin1String(" *>(") + QLatin1String(CPP_SELF_VAR) + QLatin1Char(')');
- mc << wrapperName(func->ownerClass());
- mc << " *>(" << selfWrapCast << ")->";
- }
- else {
- mc << methodCallClassName;
- mc << " *>(" << selfVarCast << ")->";
- }
- } else {
- mc << "const_cast<const ::" << methodCallClassName;
- mc << " *>(" << selfVarCast << ")->";
- }
- } else {
- mc << selfVarCast << "->";
- }
- }
-
- if (!func->isAbstract() && func->isVirtual())
- mc << "::%CLASS_NAME::";
-
- mc << func->originalName();
- } else {
- if (!func->isStatic()) {
- const auto *owner = func->ownerClass();
- const bool directInheritance = context.metaClass() == owner;
- mc << (directInheritance ? "static_cast" : "reinterpret_cast")
- << "<::" << wrapperName(owner) << " *>(" << CPP_SELF_VAR << ")->";
- }
-
- if (!func->isAbstract())
- mc << (func->isProtected() ? wrapperName(func->ownerClass()) :
- QLatin1String("::")
- + methodCallClassName) << "::";
- mc << func->originalName() << "_protected";
- }
- } else {
- mc << func->originalName();
- }
- mc << '(' << userArgs.join(QLatin1String(", ")) << ')';
- if (!func->isAbstract() && func->isVirtual()) {
- mc.flush();
- if (!avoidProtectedHack() || !func->isProtected()) {
- QString virtualCall(methodCall);
- QString normalCall(methodCall);
- virtualCall = virtualCall.replace(QLatin1String("%CLASS_NAME"),
- methodCallClassName);
- normalCall.remove(QLatin1String("::%CLASS_NAME::"));
- methodCall.clear();
- mc << "Shiboken::Object::hasCppWrapper(reinterpret_cast<SbkObject *>(self)) ? ";
- mc << virtualCall << " : " << normalCall;
- }
- }
- }
- }
-
- if (!injectedCodeCallsCppFunction(context, func)) {
- const bool allowThread = func->allowThread();
- const bool generateExceptionHandling = func->generateExceptionHandling();
- if (generateExceptionHandling) {
- s << INDENT << "try {\n";
- ++INDENT.indent;
- if (allowThread) {
- s << INDENT << "Shiboken::ThreadStateSaver threadSaver;\n"
- << INDENT << "threadSaver.save();\n";
- }
- } else if (allowThread) {
- s << INDENT << BEGIN_ALLOW_THREADS << Qt::endl;
- }
- s << INDENT;
- if (isCtor) {
- s << (useVAddr.isEmpty() ?
- QString::fromLatin1("cptr = %1;").arg(methodCall) : useVAddr) << Qt::endl;
- } else if (func->type() && !func->isInplaceOperator()) {
- bool writeReturnType = true;
- if (avoidProtectedHack()) {
- const AbstractMetaEnum *metaEnum = findAbstractMetaEnum(func->type());
- if (metaEnum) {
- QString enumName;
- if (metaEnum->isProtected())
- enumName = protectedEnumSurrogateName(metaEnum);
- else
- enumName = func->type()->cppSignature();
- methodCall.prepend(enumName + QLatin1Char('('));
- methodCall.append(QLatin1Char(')'));
- s << enumName;
- writeReturnType = false;
- }
- }
- if (writeReturnType) {
- s << func->type()->cppSignature();
- if (isObjectTypeUsedAsValueType(func->type())) {
- s << '*';
- methodCall.prepend(QString::fromLatin1("new %1(").arg(func->type()->typeEntry()->qualifiedCppName()));
- methodCall.append(QLatin1Char(')'));
- }
- }
- s << " " << CPP_RETURN_VAR << " = ";
- s << methodCall << ";\n";
- } else {
- s << methodCall << ";\n";
- }
-
- if (allowThread) {
- s << INDENT << (generateExceptionHandling
- ? "threadSaver.restore();" : END_ALLOW_THREADS) << '\n';
- }
-
- // Convert result
- if (!func->conversionRule(TypeSystem::TargetLangCode, 0).isEmpty()) {
- writeConversionRule(s, func, TypeSystem::TargetLangCode, QLatin1String(PYTHON_RETURN_VAR));
- } else if (!isCtor && !func->isInplaceOperator() && func->type()
- && !injectedCodeHasReturnValueAttribution(func, TypeSystem::TargetLangCode)) {
- s << INDENT << PYTHON_RETURN_VAR << " = ";
- if (isObjectTypeUsedAsValueType(func->type())) {
- s << "Shiboken::Object::newObject(reinterpret_cast<SbkObjectType *>(" << cpythonTypeNameExt(func->type()->typeEntry())
- << "), " << CPP_RETURN_VAR << ", true, true)";
- } else {
- writeToPythonConversion(s, func->type(), func->ownerClass(), QLatin1String(CPP_RETURN_VAR));
- }
- s << ";\n";
- }
-
- if (generateExceptionHandling) { // "catch" code
- --INDENT.indent;
- const QStringList handlingCode = defaultExceptionHandling();
- for (const auto &line : handlingCode)
- s << INDENT << line << '\n';
- }
- }
- }
-
- if (func->hasInjectedCode() && !func->isConstructor()) {
- s << Qt::endl;
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionEnd, TypeSystem::TargetLangCode, func, lastArg);
- }
-
- bool hasReturnPolicy = false;
-
- // Ownership transference between C++ and Python.
- QVector<ArgumentModification> ownership_mods;
- // Python object reference management.
- QVector<ArgumentModification> refcount_mods;
- const FunctionModificationList &funcMods = func->modifications();
- for (const FunctionModification &func_mod : funcMods) {
- for (const ArgumentModification &arg_mod : func_mod.argument_mods) {
- if (!arg_mod.ownerships.isEmpty() && arg_mod.ownerships.contains(TypeSystem::TargetLangCode))
- ownership_mods.append(arg_mod);
- else if (!arg_mod.referenceCounts.isEmpty())
- refcount_mods.append(arg_mod);
- }
- }
-
- // If there's already a setParent(return, me), don't use the return heuristic!
- if (func->argumentOwner(func->ownerClass(), -1).index == 0)
- hasReturnPolicy = true;
-
- if (!ownership_mods.isEmpty()) {
- s << Qt::endl << INDENT << "// Ownership transferences.\n";
- for (const ArgumentModification &arg_mod : qAsConst(ownership_mods)) {
- const AbstractMetaClass *wrappedClass = nullptr;
- QString pyArgName = argumentNameFromIndex(func, arg_mod.index, &wrappedClass);
- if (!wrappedClass) {
- s << "#error Invalid ownership modification for argument " << arg_mod.index << '(' << pyArgName << ")\n" << Qt::endl;
- break;
- }
-
- if (arg_mod.index == 0 || arg_mod.owner.index == 0)
- hasReturnPolicy = true;
-
- // The default ownership does nothing. This is useful to avoid automatic heuristically
- // based generation of code defining parenting.
- if (arg_mod.ownerships[TypeSystem::TargetLangCode] == TypeSystem::DefaultOwnership)
- continue;
-
- s << INDENT << "Shiboken::Object::";
- if (arg_mod.ownerships[TypeSystem::TargetLangCode] == TypeSystem::TargetLangOwnership) {
- s << "getOwnership(" << pyArgName << ");";
- } else if (wrappedClass->hasVirtualDestructor()) {
- if (arg_mod.index == 0)
- s << "releaseOwnership(" << PYTHON_RETURN_VAR << ");";
- else
- s << "releaseOwnership(" << pyArgName << ");";
- } else {
- s << "invalidate(" << pyArgName << ");";
- }
- s << Qt::endl;
- }
-
- } else if (!refcount_mods.isEmpty()) {
- for (const ArgumentModification &arg_mod : qAsConst(refcount_mods)) {
- ReferenceCount refCount = arg_mod.referenceCounts.constFirst();
- if (refCount.action != ReferenceCount::Set
- && refCount.action != ReferenceCount::Remove
- && refCount.action != ReferenceCount::Add) {
- qCWarning(lcShiboken) << "\"set\", \"add\" and \"remove\" are the only values supported by Shiboken for action attribute of reference-count tag.";
- continue;
- }
- const AbstractMetaClass *wrappedClass = nullptr;
-
- QString pyArgName;
- if (refCount.action == ReferenceCount::Remove) {
- pyArgName = QLatin1String("Py_None");
- } else {
- pyArgName = argumentNameFromIndex(func, arg_mod.index, &wrappedClass);
- if (pyArgName.isEmpty()) {
- s << "#error Invalid reference count modification for argument " << arg_mod.index << Qt::endl << Qt::endl;
- break;
- }
- }
-
- if (refCount.action == ReferenceCount::Add || refCount.action == ReferenceCount::Set)
- s << INDENT << "Shiboken::Object::keepReference(";
- else
- s << INDENT << "Shiboken::Object::removeReference(";
-
- s << "reinterpret_cast<SbkObject *>(self), \"";
- QString varName = arg_mod.referenceCounts.constFirst().varName;
- if (varName.isEmpty())
- varName = func->minimalSignature() + QString::number(arg_mod.index);
-
- s << varName << "\", " << pyArgName
- << (refCount.action == ReferenceCount::Add ? ", true" : "")
- << ");\n";
-
- if (arg_mod.index == 0)
- hasReturnPolicy = true;
- }
- }
- writeParentChildManagement(s, func, !hasReturnPolicy);
-}
-
-QStringList CppGenerator::getAncestorMultipleInheritance(const AbstractMetaClass *metaClass)
-{
- QStringList result;
- const AbstractMetaClassList &baseClases = getBaseClasses(metaClass);
- if (!baseClases.isEmpty()) {
- for (const AbstractMetaClass *baseClass : baseClases) {
- QString offset;
- QTextStream(&offset) << "reinterpret_cast<uintptr_t>(static_cast<const "
- << baseClass->qualifiedCppName() << " *>(class_ptr)) - base";
- result.append(offset);
- offset.clear();
- QTextStream(&offset) << "reinterpret_cast<uintptr_t>(static_cast<const "
- << baseClass->qualifiedCppName() << " *>(static_cast<const "
- << metaClass->qualifiedCppName()
- << " *>(static_cast<const void *>(class_ptr)))) - base";
- result.append(offset);
- }
-
- for (const AbstractMetaClass *baseClass : baseClases)
- result.append(getAncestorMultipleInheritance(baseClass));
- }
- return result;
-}
-
-void CppGenerator::writeMultipleInheritanceInitializerFunction(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- QString className = metaClass->qualifiedCppName();
- const QStringList ancestors = getAncestorMultipleInheritance(metaClass);
- s << "static int mi_offsets[] = { ";
- for (int i = 0; i < ancestors.size(); i++)
- s << "-1, ";
- s << "-1 };\n";
- s << "int *\n";
- s << multipleInheritanceInitializerFunctionName(metaClass) << "(const void *cptr)\n";
- s << "{\n";
- s << INDENT << "if (mi_offsets[0] == -1) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "std::set<int> offsets;\n";
- s << INDENT << "const auto *class_ptr = reinterpret_cast<const " << className << " *>(cptr);\n";
- s << INDENT << "const auto base = reinterpret_cast<uintptr_t>(class_ptr);\n";
-
- for (const QString &ancestor : ancestors)
- s << INDENT << "offsets.insert(int(" << ancestor << "));\n";
-
- s << Qt::endl;
- s << INDENT << "offsets.erase(0);\n";
- s << Qt::endl;
-
- s << INDENT << "std::copy(offsets.cbegin(), offsets.cend(), mi_offsets);\n";
- }
- s << INDENT << "}\n";
- s << INDENT << "return mi_offsets;\n";
- s << "}\n";
-}
-
-void CppGenerator::writeSpecialCastFunction(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- QString className = metaClass->qualifiedCppName();
- s << "static void * " << cpythonSpecialCastFunctionName(metaClass) << "(void *obj, SbkObjectType *desiredType)\n";
- s << "{\n";
- s << INDENT << "auto me = reinterpret_cast< ::" << className << " *>(obj);\n";
- bool firstClass = true;
- const AbstractMetaClassList &allAncestors = getAllAncestors(metaClass);
- for (const AbstractMetaClass *baseClass : allAncestors) {
- s << INDENT << (!firstClass ? "else " : "") << "if (desiredType == reinterpret_cast<SbkObjectType *>(" << cpythonTypeNameExt(baseClass->typeEntry()) << "))\n";
- Indentation indent(INDENT);
- s << INDENT << "return static_cast< ::" << baseClass->qualifiedCppName() << " *>(me);\n";
- firstClass = false;
- }
- s << INDENT << "return me;\n";
- s << "}\n\n";
-}
-
-void CppGenerator::writePrimitiveConverterInitialization(QTextStream &s, const CustomConversion *customConversion)
-{
- const TypeEntry *type = customConversion->ownerType();
- QString converter = converterObject(type);
- s << INDENT << "// Register converter for type '" << type->qualifiedTargetLangName() << "'.\n";
- s << INDENT << converter << " = Shiboken::Conversions::createConverter(";
- if (type->targetLangApiName() == type->name())
- s << '0';
- else if (type->targetLangApiName() == QLatin1String("PyObject"))
- s << "&PyBaseObject_Type";
- else
- s << '&' << type->targetLangApiName() << "_Type";
- QString typeName = fixedCppTypeName(type);
- s << ", " << cppToPythonFunctionName(typeName, typeName) << ");\n";
- s << INDENT << "Shiboken::Conversions::registerConverterName(" << converter << ", \"" << type->qualifiedCppName() << "\");\n";
- writeCustomConverterRegister(s, customConversion, converter);
-}
-
-void CppGenerator::writeEnumConverterInitialization(QTextStream &s, const AbstractMetaEnum *metaEnum)
-{
- if (metaEnum->isPrivate() || metaEnum->isAnonymous())
- return;
- writeEnumConverterInitialization(s, metaEnum->typeEntry());
-}
-
-void CppGenerator::writeEnumConverterInitialization(QTextStream &s, const TypeEntry *enumType)
-{
- if (!enumType)
- return;
- QString enumFlagName = enumType->isFlags() ? QLatin1String("flag") : QLatin1String("enum");
- QString enumPythonType = cpythonTypeNameExt(enumType);
-
- const FlagsTypeEntry *flags = nullptr;
- if (enumType->isFlags())
- flags = static_cast<const FlagsTypeEntry *>(enumType);
-
- s << INDENT << "// Register converter for " << enumFlagName << " '" << enumType->qualifiedCppName() << "'.\n";
- s << INDENT << "{\n";
- {
- Indentation indent(INDENT);
- QString typeName = fixedCppTypeName(enumType);
- s << INDENT << "SbkConverter *converter = Shiboken::Conversions::createConverter(" << enumPythonType << ',' << Qt::endl;
- {
- Indentation indent(INDENT);
- s << INDENT << cppToPythonFunctionName(typeName, typeName) << ");\n";
- }
-
- if (flags) {
- QString enumTypeName = fixedCppTypeName(flags->originator());
- QString toCpp = pythonToCppFunctionName(enumTypeName, typeName);
- QString isConv = convertibleToCppFunctionName(enumTypeName, typeName);
- writeAddPythonToCppConversion(s, QLatin1String("converter"), toCpp, isConv);
- }
-
- QString toCpp = pythonToCppFunctionName(typeName, typeName);
- QString isConv = convertibleToCppFunctionName(typeName, typeName);
- writeAddPythonToCppConversion(s, QLatin1String("converter"), toCpp, isConv);
-
- if (flags) {
- QString toCpp = pythonToCppFunctionName(QLatin1String("number"), typeName);
- QString isConv = convertibleToCppFunctionName(QLatin1String("number"), typeName);
- writeAddPythonToCppConversion(s, QLatin1String("converter"), toCpp, isConv);
- }
-
- s << INDENT << "Shiboken::Enum::setTypeConverter(" << enumPythonType << ", converter);\n";
-
- QString signature = enumType->qualifiedCppName();
- // Replace "QFlags<Class::Option>" by "Class::Options"
- if (flags && signature.startsWith(QLatin1String("QFlags<")) && signature.endsWith(QLatin1Char('>'))) {
- signature.chop(1);
- signature.remove(0, 7);
- const int lastQualifierPos = signature.lastIndexOf(QLatin1String("::"));
- if (lastQualifierPos != -1) {
- signature.replace(lastQualifierPos + 2, signature.size() - lastQualifierPos - 2,
- flags->flagsName());
- } else {
- signature = flags->flagsName();
- }
- }
-
- while (true) {
- s << INDENT << "Shiboken::Conversions::registerConverterName(converter, \""
- << signature << "\");\n";
- const int qualifierPos = signature.indexOf(QLatin1String("::"));
- if (qualifierPos != -1)
- signature.remove(0, qualifierPos + 2);
- else
- break;
- }
- }
- s << INDENT << "}\n";
-
- if (!flags)
- writeEnumConverterInitialization(s, static_cast<const EnumTypeEntry *>(enumType)->flags());
-}
-
-void CppGenerator::writeContainerConverterInitialization(QTextStream &s, const AbstractMetaType *type)
-{
- QByteArray cppSignature = QMetaObject::normalizedSignature(type->cppSignature().toUtf8());
- s << INDENT << "// Register converter for type '" << cppSignature << "'.\n";
- QString converter = converterObject(type);
- s << INDENT << converter << " = Shiboken::Conversions::createConverter(";
- if (type->typeEntry()->targetLangApiName() == QLatin1String("PyObject")) {
- s << "&PyBaseObject_Type";
- } else {
- QString baseName = cpythonBaseName(type->typeEntry());
- if (baseName == QLatin1String("PySequence"))
- baseName = QLatin1String("PyList");
- s << '&' << baseName << "_Type";
- }
- QString typeName = fixedCppTypeName(type);
- s << ", " << cppToPythonFunctionName(typeName, typeName) << ");\n";
- QString toCpp = pythonToCppFunctionName(typeName, typeName);
- QString isConv = convertibleToCppFunctionName(typeName, typeName);
- s << INDENT << "Shiboken::Conversions::registerConverterName(" << converter << ", \"" << cppSignature << "\");\n";
- if (usePySideExtensions() && cppSignature.startsWith("const ") && cppSignature.endsWith("&")) {
- cppSignature.chop(1);
- cppSignature.remove(0, sizeof("const ") / sizeof(char) - 1);
- s << INDENT << "Shiboken::Conversions::registerConverterName(" << converter << ", \"" << cppSignature << "\");\n";
- }
- writeAddPythonToCppConversion(s, converterObject(type), toCpp, isConv);
-}
-
-void CppGenerator::writeExtendedConverterInitialization(QTextStream &s, const TypeEntry *externalType,
- const QVector<const AbstractMetaClass *>& conversions)
-{
- s << INDENT << "// Extended implicit conversions for " << externalType->qualifiedTargetLangName() << '.' << Qt::endl;
- for (const AbstractMetaClass *sourceClass : conversions) {
- const QString converterVar = QLatin1String("reinterpret_cast<SbkObjectType *>(")
- + cppApiVariableName(externalType->targetLangPackage()) + QLatin1Char('[')
- + getTypeIndexVariableName(externalType) + QLatin1String("])");
- QString sourceTypeName = fixedCppTypeName(sourceClass->typeEntry());
- QString targetTypeName = fixedCppTypeName(externalType);
- QString toCpp = pythonToCppFunctionName(sourceTypeName, targetTypeName);
- QString isConv = convertibleToCppFunctionName(sourceTypeName, targetTypeName);
- writeAddPythonToCppConversion(s, converterVar, toCpp, isConv);
- }
-}
-
-QString CppGenerator::multipleInheritanceInitializerFunctionName(const AbstractMetaClass *metaClass)
-{
- return cpythonBaseName(metaClass->typeEntry()) + QLatin1String("_mi_init");
-}
-
-bool CppGenerator::supportsMappingProtocol(const AbstractMetaClass *metaClass)
-{
- for (auto it = m_mappingProtocol.cbegin(), end = m_mappingProtocol.cend(); it != end; ++it) {
- if (metaClass->hasFunction(it.key()))
- return true;
- }
-
- return false;
-}
-
-bool CppGenerator::supportsNumberProtocol(const AbstractMetaClass *metaClass)
-{
- return metaClass->hasArithmeticOperatorOverload()
- || metaClass->hasLogicalOperatorOverload()
- || metaClass->hasBitwiseOperatorOverload()
- || hasBoolCast(metaClass);
-}
-
-bool CppGenerator::supportsSequenceProtocol(const AbstractMetaClass *metaClass)
-{
- for (auto it = m_sequenceProtocol.cbegin(), end = m_sequenceProtocol.cend(); it != end; ++it) {
- if (metaClass->hasFunction(it.key()))
- return true;
- }
-
- const ComplexTypeEntry *baseType = metaClass->typeEntry()->baseContainerType();
- return baseType && baseType->isContainer();
-}
-
-bool CppGenerator::shouldGenerateGetSetList(const AbstractMetaClass *metaClass)
-{
- const AbstractMetaFieldList &fields = metaClass->fields();
- for (const AbstractMetaField *f : fields) {
- if (!f->isStatic())
- return true;
- }
- return false;
-}
-
-struct pyTypeSlotEntry
-{
- explicit pyTypeSlotEntry(const char *name, const QString &function) :
- m_name(name), m_function(function) {}
-
- const char *m_name;
- const QString &m_function;
-};
-
-QTextStream &operator<<(QTextStream &str, const pyTypeSlotEntry &e)
-{
- str << '{' << e.m_name << ',';
- const int padding = qMax(0, 18 - int(strlen(e.m_name)));
- for (int p = 0; p < padding; ++p)
- str << ' ';
- if (e.m_function.isEmpty())
- str << NULL_PTR;
- else
- str << "reinterpret_cast<void *>(" << e.m_function << ')';
- str << "},\n";
- return str;
-}
-
-void CppGenerator::writeClassDefinition(QTextStream &s,
- const AbstractMetaClass *metaClass,
- const GeneratorContext &classContext)
-{
- QString tp_flags;
- QString tp_init;
- QString tp_new;
- QString tp_dealloc;
- QString tp_hash;
- QString tp_call;
- QString cppClassName = metaClass->qualifiedCppName();
- const QString className = chopType(cpythonTypeName(metaClass));
- QString baseClassName;
- AbstractMetaFunctionList ctors;
- const AbstractMetaFunctionList &allCtors = metaClass->queryFunctions(AbstractMetaClass::Constructors);
- for (AbstractMetaFunction *f : allCtors) {
- if (!f->isPrivate() && !f->isModifiedRemoved() && !classContext.forSmartPointer())
- ctors.append(f);
- }
-
- if (!metaClass->baseClass())
- baseClassName = QLatin1String("reinterpret_cast<PyTypeObject *>(SbkObject_TypeF())");
-
- bool onlyPrivCtor = !metaClass->hasNonPrivateConstructor();
-
- const AbstractMetaClass *qCoreApp = AbstractMetaClass::findClass(classes(), QLatin1String("QCoreApplication"));
- const bool isQApp = qCoreApp != Q_NULLPTR && metaClass->inheritsFrom(qCoreApp);
-
- tp_flags = QLatin1String("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES");
- if (metaClass->isNamespace() || metaClass->hasPrivateDestructor()) {
- tp_dealloc = metaClass->hasPrivateDestructor() ?
- QLatin1String("SbkDeallocWrapperWithPrivateDtor") :
- QLatin1String("Sbk_object_dealloc /* PYSIDE-832: Prevent replacement of \"0\" with subtype_dealloc. */");
- tp_init.clear();
- } else {
- QString deallocClassName = classContext.useWrapper()
- ? classContext.wrapperName() : cppClassName;
- if (isQApp)
- tp_dealloc = QLatin1String("&SbkDeallocQAppWrapper");
- else
- tp_dealloc = QLatin1String("&SbkDeallocWrapper");
- if (!onlyPrivCtor && !ctors.isEmpty())
- tp_init = cpythonFunctionName(ctors.constFirst());
- }
-
- const AttroCheck attroCheck = checkAttroFunctionNeeds(metaClass);
- const QString tp_getattro = (attroCheck & AttroCheckFlag::GetattroMask) != 0
- ? cpythonGetattroFunctionName(metaClass) : QString();
- const QString tp_setattro = (attroCheck & AttroCheckFlag::SetattroMask) != 0
- ? cpythonSetattroFunctionName(metaClass) : QString();
-
- if (metaClass->hasPrivateDestructor() || onlyPrivCtor) {
- // tp_flags = QLatin1String("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES");
- // This is not generally possible, because PySide does not care about
- // privacy the same way. This worked before the heap types were used,
- // because inheritance is not really checked for static types.
- // Instead, we check this at runtime, see SbkObjectTypeTpNew.
- if (metaClass->fullName().startsWith(QLatin1String("PySide2.Qt"))) {
- // PYSIDE-595: No idea how to do non-inheritance correctly.
- // Since that is only relevant in shiboken, I used a shortcut for
- // PySide.
- tp_new = QLatin1String("SbkObjectTpNew");
- }
- else {
- tp_new = QLatin1String("SbkDummyNew /* PYSIDE-595: Prevent replacement "
- "of \"0\" with base->tp_new. */");
- }
- tp_flags.append(QLatin1String("|Py_TPFLAGS_HAVE_GC"));
- }
- else if (isQApp) {
- tp_new = QLatin1String("SbkQAppTpNew"); // PYSIDE-571: need singleton app
- }
- else {
- tp_new = QLatin1String("SbkObjectTpNew");
- tp_flags.append(QLatin1String("|Py_TPFLAGS_HAVE_GC"));
- }
-
- QString tp_richcompare;
- if (!metaClass->isNamespace() && metaClass->hasComparisonOperatorOverload())
- tp_richcompare = cpythonBaseName(metaClass) + QLatin1String("_richcompare");
-
- QString tp_getset;
- if (shouldGenerateGetSetList(metaClass) && !classContext.forSmartPointer())
- tp_getset = cpythonGettersSettersDefinitionName(metaClass);
-
- // search for special functions
- ShibokenGenerator::clearTpFuncs();
- const AbstractMetaFunctionList &funcs = metaClass->functions();
- for (AbstractMetaFunction *func : funcs) {
- if (m_tpFuncs.contains(func->name()))
- m_tpFuncs[func->name()] = cpythonFunctionName(func);
- }
- if (m_tpFuncs.value(QLatin1String("__repr__")).isEmpty()
- && metaClass->hasToStringCapability()) {
- m_tpFuncs[QLatin1String("__repr__")] = writeReprFunction(s,
- classContext,
- metaClass->toStringCapabilityIndirections());
- }
-
- // class or some ancestor has multiple inheritance
- const AbstractMetaClass *miClass = getMultipleInheritingClass(metaClass);
- if (miClass) {
- if (metaClass == miClass)
- writeMultipleInheritanceInitializerFunction(s, metaClass);
- writeSpecialCastFunction(s, metaClass);
- s << Qt::endl;
- }
-
- s << "// Class Definition -----------------------------------------------\n";
- s << "extern \"C\" {\n";
-
- if (!metaClass->typeEntry()->hashFunction().isEmpty())
- tp_hash = QLatin1Char('&') + cpythonBaseName(metaClass) + QLatin1String("_HashFunc");
-
- const AbstractMetaFunction *callOp = metaClass->findFunction(QLatin1String("operator()"));
- if (callOp && !callOp->isModifiedRemoved())
- tp_call = QLatin1Char('&') + cpythonFunctionName(callOp);
-
- QString computedClassTargetFullName;
- if (!classContext.forSmartPointer())
- computedClassTargetFullName = getClassTargetFullName(metaClass);
- else
- computedClassTargetFullName = getClassTargetFullName(classContext.preciseType());
-
- QString suffix;
- if (isObjectType(metaClass))
- suffix = QLatin1String(" *");
- const QString typePtr = QLatin1String("_") + className
- + QLatin1String("_Type");
- s << "static SbkObjectType *" << typePtr << " = nullptr;\n";
- s << "static SbkObjectType *" << className << "_TypeF(void)\n";
- s << "{\n";
- s << INDENT << "return " << typePtr << ";\n";
- s << "}\n";
- s << Qt::endl;
- s << "static PyType_Slot " << className << "_slots[] = {\n";
- s << INDENT << "{Py_tp_base, nullptr}, // inserted by introduceWrapperType\n";
- s << INDENT << pyTypeSlotEntry("Py_tp_dealloc", tp_dealloc)
- << INDENT << pyTypeSlotEntry("Py_tp_repr", m_tpFuncs.value(QLatin1String("__repr__")))
- << INDENT << pyTypeSlotEntry("Py_tp_hash", tp_hash)
- << INDENT << pyTypeSlotEntry("Py_tp_call", tp_call)
- << INDENT << pyTypeSlotEntry("Py_tp_str", m_tpFuncs.value(QLatin1String("__str__")))
- << INDENT << pyTypeSlotEntry("Py_tp_getattro", tp_getattro)
- << INDENT << pyTypeSlotEntry("Py_tp_setattro", tp_setattro)
- << INDENT << pyTypeSlotEntry("Py_tp_traverse", className + QLatin1String("_traverse"))
- << INDENT << pyTypeSlotEntry("Py_tp_clear", className + QLatin1String("_clear"))
- << INDENT << pyTypeSlotEntry("Py_tp_richcompare", tp_richcompare)
- << INDENT << pyTypeSlotEntry("Py_tp_iter", m_tpFuncs.value(QLatin1String("__iter__")))
- << INDENT << pyTypeSlotEntry("Py_tp_iternext", m_tpFuncs.value(QLatin1String("__next__")))
- << INDENT << pyTypeSlotEntry("Py_tp_methods", className + QLatin1String("_methods"))
- << INDENT << pyTypeSlotEntry("Py_tp_getset", tp_getset)
- << INDENT << pyTypeSlotEntry("Py_tp_init", tp_init)
- << INDENT << pyTypeSlotEntry("Py_tp_new", tp_new);
- if (supportsSequenceProtocol(metaClass)) {
- s << INDENT << "// type supports sequence protocol\n";
- writeTypeAsSequenceDefinition(s, metaClass);
- }
- if (supportsMappingProtocol(metaClass)) {
- s << INDENT << "// type supports mapping protocol\n";
- writeTypeAsMappingDefinition(s, metaClass);
- }
- if (supportsNumberProtocol(metaClass)) {
- // This one must come last. See the function itself.
- s << INDENT << "// type supports number protocol\n";
- writeTypeAsNumberDefinition(s, metaClass);
- }
- s << INDENT << "{0, " << NULL_PTR << "}\n";
- s << "};\n";
-
- int packageLevel = packageName().count(QLatin1Char('.')) + 1;
- s << "static PyType_Spec " << className << "_spec = {\n";
- s << INDENT << '"' << packageLevel << ':' << computedClassTargetFullName << "\",\n";
- s << INDENT << "sizeof(SbkObject),\n";
- s << INDENT << "0,\n";
- s << INDENT << tp_flags << ",\n";
- s << INDENT << className << "_slots\n";
- s << "};\n";
- s << Qt::endl;
- s << "} //extern \"C\"" << Qt::endl;
-}
-
-void CppGenerator::writeMappingMethods(QTextStream &s,
- const AbstractMetaClass *metaClass,
- const GeneratorContext &context)
-{
- for (auto it = m_mappingProtocol.cbegin(), end = m_mappingProtocol.cend(); it != end; ++it) {
- const AbstractMetaFunction *func = metaClass->findFunction(it.key());
- if (!func)
- continue;
- QString funcName = cpythonFunctionName(func);
- QString funcArgs = it.value().first;
- QString funcRetVal = it.value().second;
-
- CodeSnipList snips = func->injectedCodeSnips(TypeSystem::CodeSnipPositionAny, TypeSystem::TargetLangCode);
- s << funcRetVal << ' ' << funcName << '(' << funcArgs << ")\n{\n";
- writeInvalidPyObjectCheck(s, QLatin1String("self"));
-
- writeCppSelfDefinition(s, func, context);
-
- const AbstractMetaArgument *lastArg = func->arguments().isEmpty() ? nullptr : func->arguments().constLast();
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionAny, TypeSystem::TargetLangCode, func, lastArg);
- s<< "}\n\n";
- }
-}
-
-void CppGenerator::writeSequenceMethods(QTextStream &s,
- const AbstractMetaClass *metaClass,
- const GeneratorContext &context)
-{
- bool injectedCode = false;
-
- for (auto it = m_sequenceProtocol.cbegin(), end = m_sequenceProtocol.cend(); it != end; ++it) {
- const AbstractMetaFunction *func = metaClass->findFunction(it.key());
- if (!func)
- continue;
- injectedCode = true;
- QString funcName = cpythonFunctionName(func);
- QString funcArgs = it.value().first;
- QString funcRetVal = it.value().second;
-
- CodeSnipList snips = func->injectedCodeSnips(TypeSystem::CodeSnipPositionAny, TypeSystem::TargetLangCode);
- s << funcRetVal << ' ' << funcName << '(' << funcArgs << ")\n{\n";
- writeInvalidPyObjectCheck(s, QLatin1String("self"));
-
- writeCppSelfDefinition(s, func, context);
-
- const AbstractMetaArgument *lastArg = func->arguments().isEmpty() ? nullptr : func->arguments().constLast();
- writeCodeSnips(s, snips,TypeSystem::CodeSnipPositionAny, TypeSystem::TargetLangCode, func, lastArg);
- s<< "}\n\n";
- }
-
- if (!injectedCode)
- writeDefaultSequenceMethods(s, context);
-}
-
-void CppGenerator::writeTypeAsSequenceDefinition(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- bool hasFunctions = false;
- QMap<QString, QString> funcs;
- for (auto it = m_sequenceProtocol.cbegin(), end = m_sequenceProtocol.cend(); it != end; ++it) {
- const QString &funcName = it.key();
- const AbstractMetaFunction *func = metaClass->findFunction(funcName);
- funcs[funcName] = func ? cpythonFunctionName(func).prepend(QLatin1Char('&')) : QString();
- if (!hasFunctions && func)
- hasFunctions = true;
- }
-
- QString baseName = cpythonBaseName(metaClass);
-
- //use default implementation
- if (!hasFunctions) {
- funcs[QLatin1String("__len__")] = baseName + QLatin1String("__len__");
- funcs[QLatin1String("__getitem__")] = baseName + QLatin1String("__getitem__");
- funcs[QLatin1String("__setitem__")] = baseName + QLatin1String("__setitem__");
- }
-
- for (QHash<QString, QString>::const_iterator it = m_sqFuncs.cbegin(), end = m_sqFuncs.cend(); it != end; ++it) {
- const QString &sqName = it.key();
- if (funcs[sqName].isEmpty())
- continue;
- if (it.value() == QLatin1String("sq_slice"))
- s << "#ifndef IS_PY3K\n";
- s << INDENT << "{Py_" << it.value() << ", (void *)" << funcs[sqName] << "},\n";
- if (it.value() == QLatin1String("sq_slice"))
- s << "#endif\n";
- }
-}
-
-void CppGenerator::writeTypeAsMappingDefinition(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- bool hasFunctions = false;
- QMap<QString, QString> funcs;
- for (auto it = m_mappingProtocol.cbegin(), end = m_mappingProtocol.cend(); it != end; ++it) {
- const QString &funcName = it.key();
- const AbstractMetaFunction *func = metaClass->findFunction(funcName);
- funcs[funcName] = func ? cpythonFunctionName(func).prepend(QLatin1Char('&')) : QLatin1String("0");
- if (!hasFunctions && func)
- hasFunctions = true;
- }
-
- //use default implementation
- if (!hasFunctions) {
- funcs.insert(QLatin1String("__mlen__"), QString());
- funcs.insert(QLatin1String("__mgetitem__"), QString());
- funcs.insert(QLatin1String("__msetitem__"), QString());
- }
-
- for (auto it = m_mpFuncs.cbegin(), end = m_mpFuncs.cend(); it != end; ++it) {
- const QString &mpName = it.key();
- if (funcs[mpName].isEmpty())
- continue;
- s << INDENT << "{Py_" << it.value() << ", (void *)" << funcs[mpName] << "},\n";
- }
-}
-
-void CppGenerator::writeTypeAsNumberDefinition(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- QMap<QString, QString> nb;
-
- nb.insert(QLatin1String("__add__"), QString());
- nb.insert(QLatin1String("__sub__"), QString());
- nb.insert(QLatin1String("__mul__"), QString());
- nb.insert(QLatin1String("__div__"), QString());
- nb.insert(QLatin1String("__mod__"), QString());
- nb.insert(QLatin1String("__neg__"), QString());
- nb.insert(QLatin1String("__pos__"), QString());
- nb.insert(QLatin1String("__invert__"), QString());
- nb.insert(QLatin1String("__lshift__"), QString());
- nb.insert(QLatin1String("__rshift__"), QString());
- nb.insert(QLatin1String("__and__"), QString());
- nb.insert(QLatin1String("__xor__"), QString());
- nb.insert(QLatin1String("__or__"), QString());
- nb.insert(QLatin1String("__iadd__"), QString());
- nb.insert(QLatin1String("__isub__"), QString());
- nb.insert(QLatin1String("__imul__"), QString());
- nb.insert(QLatin1String("__idiv__"), QString());
- nb.insert(QLatin1String("__imod__"), QString());
- nb.insert(QLatin1String("__ilshift__"), QString());
- nb.insert(QLatin1String("__irshift__"), QString());
- nb.insert(QLatin1String("__iand__"), QString());
- nb.insert(QLatin1String("__ixor__"), QString());
- nb.insert(QLatin1String("__ior__"), QString());
-
- const QVector<AbstractMetaFunctionList> opOverloads =
- filterGroupedOperatorFunctions(metaClass,
- AbstractMetaClass::ArithmeticOp
- | AbstractMetaClass::LogicalOp
- | AbstractMetaClass::BitwiseOp);
-
- for (const AbstractMetaFunctionList &opOverload : opOverloads) {
- const AbstractMetaFunction *rfunc = opOverload.at(0);
- QString opName = ShibokenGenerator::pythonOperatorFunctionName(rfunc);
- nb[opName] = cpythonFunctionName(rfunc);
- }
-
- QString baseName = cpythonBaseName(metaClass);
-
- if (hasBoolCast(metaClass))
- nb.insert(QLatin1String("bool"), baseName + QLatin1String("___nb_bool"));
-
- for (QHash<QString, QString>::const_iterator it = m_nbFuncs.cbegin(), end = m_nbFuncs.cend(); it != end; ++it) {
- const QString &nbName = it.key();
- if (nb[nbName].isEmpty())
- continue;
-
- // bool is special because the field name differs on Python 2 and 3 (nb_nonzero vs nb_bool)
- // so a shiboken macro is used.
- if (nbName == QLatin1String("bool")) {
- s << "#ifdef IS_PY3K\n";
- s << INDENT << "{Py_nb_bool, (void *)" << nb[nbName] << "},\n";
- s << "#else\n";
- s << INDENT << "{Py_nb_nonzero, (void *)" << nb[nbName] << "},\n";
- s << "#endif\n";
- } else {
- bool excludeFromPy3K = nbName == QLatin1String("__div__") || nbName == QLatin1String("__idiv__");
- if (!excludeFromPy3K)
- s << INDENT << "{Py_" << it.value() << ", (void *)" << nb[nbName] << "},\n";
- }
- }
- if (!nb[QLatin1String("__div__")].isEmpty()) {
- s << INDENT << "{Py_nb_true_divide, (void *)" << nb[QLatin1String("__div__")] << "},\n";
- s << "#ifndef IS_PY3K\n";
- s << INDENT << "{Py_nb_divide, (void *)" << nb[QLatin1String("__div__")] << "},\n";
- s << "#endif\n";
- }
- if (!nb[QLatin1String("__idiv__")].isEmpty()) {
- s << INDENT << "// This function is unused in Python 3. We reference it here.\n";
- s << INDENT << "{0, (void *)" << nb[QLatin1String("__idiv__")] << "},\n";
- s << INDENT << "// This list is ending at the first 0 entry.\n";
- s << INDENT << "// Therefore, we need to put the unused functions at the very end.\n";
- }
-}
-
-void CppGenerator::writeTpTraverseFunction(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- QString baseName = cpythonBaseName(metaClass);
- s << "static int ";
- s << baseName << "_traverse(PyObject *self, visitproc visit, void *arg)\n";
- s << "{\n";
- s << INDENT << "return reinterpret_cast<PyTypeObject *>(SbkObject_TypeF())->tp_traverse(self, visit, arg);\n";
- s << "}\n";
-}
-
-void CppGenerator::writeTpClearFunction(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- QString baseName = cpythonBaseName(metaClass);
- s << "static int ";
- s << baseName << "_clear(PyObject *self)\n";
- s << "{\n";
- s << INDENT << "return reinterpret_cast<PyTypeObject *>(SbkObject_TypeF())->tp_clear(self);\n";
- s << "}\n";
-}
-
-void CppGenerator::writeCopyFunction(QTextStream &s, const GeneratorContext &context)
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- const QString className = chopType(cpythonTypeName(metaClass));
- s << "static PyObject *" << className << "___copy__(PyObject *self)\n";
- s << "{\n";
- writeCppSelfDefinition(s, context, false, true);
- QString conversionCode;
- if (!context.forSmartPointer())
- conversionCode = cpythonToPythonConversionFunction(metaClass);
- else
- conversionCode = cpythonToPythonConversionFunction(context.preciseType());
-
- s << INDENT << "PyObject *" << PYTHON_RETURN_VAR << " = " << conversionCode;
- s << CPP_SELF_VAR << ");\n";
- writeFunctionReturnErrorCheckSection(s);
- s << INDENT << "return " << PYTHON_RETURN_VAR << ";\n";
- s << "}\n";
- s << Qt::endl;
-}
-
-void CppGenerator::writeGetterFunction(QTextStream &s,
- const AbstractMetaField *metaField,
- const GeneratorContext &context)
-{
- ErrorCode errorCode(QString::fromLatin1(NULL_PTR));
- s << "static PyObject *" << cpythonGetterFunctionName(metaField) << "(PyObject *self, void *)\n";
- s << "{\n";
-
- writeCppSelfDefinition(s, context);
-
- AbstractMetaType *fieldType = metaField->type();
- // Force use of pointer to return internal variable memory
- bool newWrapperSameObject = !fieldType->isConstant() && isWrapperType(fieldType) && !isPointer(fieldType);
-
- QString cppField;
- if (avoidProtectedHack() && metaField->isProtected()) {
- QTextStream(&cppField) << "static_cast<"
- << context.wrapperName() << " *>("
- << CPP_SELF_VAR << ")->" << protectedFieldGetterName(metaField) << "()";
- } else {
- cppField = QLatin1String(CPP_SELF_VAR) + QLatin1String("->") + metaField->name();
- if (newWrapperSameObject) {
- cppField.prepend(QLatin1String("&("));
- cppField.append(QLatin1Char(')'));
- }
- }
- if (isCppIntegralPrimitive(fieldType) || fieldType->isEnum()) {
- s << INDENT << getFullTypeNameWithoutModifiers(fieldType) << " cppOut_local = " << cppField << ";\n";
- cppField = QLatin1String("cppOut_local");
- } else if (avoidProtectedHack() && metaField->isProtected()) {
- s << INDENT << getFullTypeNameWithoutModifiers(fieldType);
- if (fieldType->isContainer() || fieldType->isFlags() || fieldType->isSmartPointer()) {
- s << " &";
- cppField.prepend(QLatin1Char('*'));
- } else if ((!fieldType->isConstant() && !fieldType->isEnum() && !fieldType->isPrimitive()) || fieldType->indirections() == 1) {
- s << " *";
- }
- s << " fieldValue = " << cppField << ";\n";
- cppField = QLatin1String("fieldValue");
- }
-
- s << INDENT << "PyObject *pyOut = {};\n";
- if (newWrapperSameObject) {
- // Special case colocated field with same address (first field in a struct)
- s << INDENT << "if (reinterpret_cast<void *>("
- << cppField
- << ") == reinterpret_cast<void *>("
- << CPP_SELF_VAR << ")) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "pyOut = reinterpret_cast<PyObject *>(Shiboken::Object::findColocatedChild("
- << "reinterpret_cast<SbkObject *>(self), reinterpret_cast<SbkObjectType *>("
- << cpythonTypeNameExt(fieldType)
- << ")));\n";
- s << INDENT << "if (pyOut) {Py_IncRef(pyOut); return pyOut;}\n";
- }
- s << INDENT << "}\n";
- // Check if field wrapper has already been created.
- s << INDENT << "else if (Shiboken::BindingManager::instance().hasWrapper(" << cppField << ")) {" << "\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "pyOut = reinterpret_cast<PyObject *>(Shiboken::BindingManager::instance().retrieveWrapper("
- << cppField << "));" << "\n";
- s << INDENT << "Py_IncRef(pyOut);" << "\n";
- s << INDENT << "return pyOut;" << "\n";
- }
- s << INDENT << "}\n";
- // Create and register new wrapper
- s << INDENT << "pyOut = ";
- s << "Shiboken::Object::newObject(reinterpret_cast<SbkObjectType *>(" << cpythonTypeNameExt(fieldType)
- << "), " << cppField << ", false, true);\n";
- s << INDENT << "Shiboken::Object::setParent(self, pyOut)";
- } else {
- s << INDENT << "pyOut = ";
- writeToPythonConversion(s, fieldType, metaField->enclosingClass(), cppField);
- }
- s << ";\n";
-
- s << INDENT << "return pyOut;\n";
- s << "}\n";
-}
-
-void CppGenerator::writeSetterFunction(QTextStream &s,
- const AbstractMetaField *metaField,
- const GeneratorContext &context)
-{
- ErrorCode errorCode(0);
- s << "static int " << cpythonSetterFunctionName(metaField) << "(PyObject *self, PyObject *pyIn, void *)\n";
- s << "{\n";
-
- writeCppSelfDefinition(s, context);
-
- s << INDENT << "if (pyIn == " << NULL_PTR << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_TypeError, \"'";
- s << metaField->name() << "' may not be deleted\");\n";
- s << INDENT << "return -1;\n";
- }
- s << INDENT << "}\n";
-
- AbstractMetaType *fieldType = metaField->type();
-
- s << INDENT << "PythonToCppFunc " << PYTHON_TO_CPP_VAR << "{nullptr};\n";
- s << INDENT << "if (!";
- writeTypeCheck(s, fieldType, QLatin1String("pyIn"), isNumber(fieldType->typeEntry()));
- s << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_TypeError, \"wrong type attributed to '";
- s << metaField->name() << "', '" << fieldType->name() << "' or convertible type expected\");\n";
- s << INDENT << "return -1;\n";
- }
- s << INDENT<< "}\n\n";
-
- QString cppField = QString::fromLatin1("%1->%2").arg(QLatin1String(CPP_SELF_VAR), metaField->name());
- s << INDENT;
- if (avoidProtectedHack() && metaField->isProtected()) {
- s << getFullTypeNameWithoutModifiers(fieldType);
- s << (fieldType->indirections() == 1 ? " *" : "") << " cppOut;\n";
- s << INDENT << PYTHON_TO_CPP_VAR << "(pyIn, &cppOut);\n";
- s << INDENT << "static_cast<" << context.wrapperName()
- << " *>(" << CPP_SELF_VAR << ")->" << protectedFieldSetterName(metaField)
- << "(cppOut)";
- } else if (isCppIntegralPrimitive(fieldType) || fieldType->typeEntry()->isEnum() || fieldType->typeEntry()->isFlags()) {
- s << getFullTypeNameWithoutModifiers(fieldType) << " cppOut_local = " << cppField << ";\n";
- s << INDENT << PYTHON_TO_CPP_VAR << "(pyIn, &cppOut_local);\n";
- s << INDENT << cppField << " = cppOut_local";
- } else {
- if (isPointerToConst(fieldType))
- s << "const ";
- s << getFullTypeNameWithoutModifiers(fieldType);
- s << QString::fromLatin1(" *").repeated(fieldType->indirections()) << "& cppOut_ptr = ";
- s << cppField << ";\n";
- s << INDENT << PYTHON_TO_CPP_VAR << "(pyIn, &cppOut_ptr)";
- }
- s << ";\n" << Qt::endl;
-
- if (isPointerToWrapperType(fieldType)) {
- s << INDENT << "Shiboken::Object::keepReference(reinterpret_cast<SbkObject *>(self), \"";
- s << metaField->name() << "\", pyIn);\n";
- }
-
- s << INDENT << "return 0;\n";
- s << "}\n";
-}
-
-void CppGenerator::writeRichCompareFunction(QTextStream &s, const GeneratorContext &context)
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- QString baseName = cpythonBaseName(metaClass);
- s << "static PyObject * ";
- s << baseName << "_richcompare(PyObject *self, PyObject *" << PYTHON_ARG
- << ", int op)\n{\n";
- writeCppSelfDefinition(s, context, false, true);
- writeUnusedVariableCast(s, QLatin1String(CPP_SELF_VAR));
- s << INDENT << "PyObject *" << PYTHON_RETURN_VAR << "{};\n";
- s << INDENT << "PythonToCppFunc " << PYTHON_TO_CPP_VAR << ";\n";
- writeUnusedVariableCast(s, QLatin1String(PYTHON_TO_CPP_VAR));
- s << Qt::endl;
-
- s << INDENT << "switch (op) {\n";
- {
- Indentation indent(INDENT);
- const QVector<AbstractMetaFunctionList> &groupedFuncs = filterGroupedOperatorFunctions(metaClass, AbstractMetaClass::ComparisonOp);
- for (const AbstractMetaFunctionList &overloads : groupedFuncs) {
- const AbstractMetaFunction *rfunc = overloads[0];
-
- QString operatorId = ShibokenGenerator::pythonRichCompareOperatorId(rfunc);
- s << INDENT << "case " << operatorId << ':' << Qt::endl;
-
- Indentation indent(INDENT);
-
- QString op = rfunc->originalName();
- op = op.right(op.size() - QLatin1String("operator").size());
-
- int alternativeNumericTypes = 0;
- for (const AbstractMetaFunction *func : overloads) {
- if (!func->isStatic() &&
- ShibokenGenerator::isNumber(func->arguments().at(0)->type()->typeEntry()))
- alternativeNumericTypes++;
- }
-
- bool first = true;
- OverloadData overloadData(overloads, this);
- const OverloadDataList &nextOverloads = overloadData.nextOverloadData();
- for (OverloadData *od : nextOverloads) {
- const AbstractMetaFunction *func = od->referenceFunction();
- if (func->isStatic())
- continue;
- const AbstractMetaType *argType = getArgumentType(func, 1);
- if (!argType)
- continue;
- if (!first) {
- s << " else ";
- } else {
- first = false;
- s << INDENT;
- }
- s << "if (";
- writeTypeCheck(s, argType, QLatin1String(PYTHON_ARG), alternativeNumericTypes == 1 || isPyInt(argType));
- s << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "// " << func->signature() << Qt::endl;
- writeArgumentConversion(s, argType, QLatin1String(CPP_ARG0),
- QLatin1String(PYTHON_ARG), metaClass,
- QString(), func->isUserAdded());
-
- // If the function is user added, use the inject code
- if (func->isUserAdded()) {
- CodeSnipList snips = func->injectedCodeSnips();
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionAny, TypeSystem::TargetLangCode, func, func->arguments().constLast());
- } else {
- s << INDENT;
- if (func->type())
- s << func->type()->cppSignature() << " " << CPP_RETURN_VAR << " = ";
- // expression
- if (func->isPointerOperator())
- s << '&';
- s << CPP_SELF_VAR << ' ' << op << '(';
- if (shouldDereferenceAbstractMetaTypePointer(argType))
- s << '*';
- s << CPP_ARG0 << ");\n";
- s << INDENT << PYTHON_RETURN_VAR << " = ";
- if (func->type())
- writeToPythonConversion(s, func->type(), metaClass, QLatin1String(CPP_RETURN_VAR));
- else
- s << "Py_None;\n" << INDENT << "Py_INCREF(Py_None)";
- s << ";\n";
- }
- }
- s << INDENT << '}';
- }
-
- s << " else {\n";
- if (operatorId == QLatin1String("Py_EQ") || operatorId == QLatin1String("Py_NE")) {
- Indentation indent(INDENT);
- s << INDENT << PYTHON_RETURN_VAR << " = "
- << (operatorId == QLatin1String("Py_EQ") ? "Py_False" : "Py_True") << ";\n";
- s << INDENT << "Py_INCREF(" << PYTHON_RETURN_VAR << ");\n";
- } else {
- Indentation indent(INDENT);
- s << INDENT << "goto " << baseName << "_RichComparison_TypeError;\n";
- }
- s << INDENT<< "}\n\n";
-
- s << INDENT << "break;\n";
- }
- s << INDENT << "default:\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "goto " << baseName << "_RichComparison_TypeError;\n";
- }
- }
- s << INDENT<< "}\n\n";
-
- s << INDENT << "if (" << PYTHON_RETURN_VAR << " && !PyErr_Occurred())\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return " << PYTHON_RETURN_VAR << ";\n";
- }
- s << INDENT << baseName << "_RichComparison_TypeError:\n";
- s << INDENT << "PyErr_SetString(PyExc_NotImplementedError, \"operator not implemented.\");\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl << Qt::endl;
- s<< "}\n\n";
-}
-
-void CppGenerator::writeMethodDefinitionEntry(QTextStream &s, const AbstractMetaFunctionList &overloads)
-{
- Q_ASSERT(!overloads.isEmpty());
- OverloadData overloadData(overloads, this);
- bool usePyArgs = pythonFunctionWrapperUsesListOfArguments(overloadData);
- const AbstractMetaFunction *func = overloadData.referenceFunction();
- int min = overloadData.minArgs();
- int max = overloadData.maxArgs();
-
- s << '"' << func->name() << "\", reinterpret_cast<PyCFunction>("
- << cpythonFunctionName(func) << "), ";
- if ((min == max) && (max < 2) && !usePyArgs) {
- if (max == 0)
- s << "METH_NOARGS";
- else
- s << "METH_O";
- } else {
- s << "METH_VARARGS";
- if (overloadData.hasArgumentWithDefaultValue())
- s << "|METH_KEYWORDS";
- }
- if (func->ownerClass() && overloadData.hasStaticFunction())
- s << "|METH_STATIC";
-}
-
-void CppGenerator::writeMethodDefinition(QTextStream &s, const AbstractMetaFunctionList &overloads)
-{
- Q_ASSERT(!overloads.isEmpty());
- const AbstractMetaFunction *func = overloads.constFirst();
- if (m_tpFuncs.contains(func->name()))
- return;
-
- s << INDENT;
- if (OverloadData::hasStaticAndInstanceFunctions(overloads)) {
- s << cpythonMethodDefinitionName(func);
- } else {
- s << '{';
- writeMethodDefinitionEntry(s, overloads);
- s << '}';
- }
- s << ',' << Qt::endl;
-}
-
-void CppGenerator::writeSignatureInfo(QTextStream &s, const AbstractMetaFunctionList &overloads)
-{
- OverloadData overloadData(overloads, this);
- const AbstractMetaFunction *rfunc = overloadData.referenceFunction();
- QString funcName = fullPythonFunctionName(rfunc);
-
- int idx = overloads.length() - 1;
- bool multiple = idx > 0;
-
- for (const AbstractMetaFunction *f : overloads) {
- QStringList args;
- const AbstractMetaArgumentList &arguments = f->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- QString strArg = arg->type()->pythonSignature();
- if (!arg->defaultValueExpression().isEmpty()) {
- strArg += QLatin1Char('=');
- QString e = arg->defaultValueExpression();
- e.replace(QLatin1String("::"), QLatin1String("."));
- strArg += e;
- }
- args << arg->name() + QLatin1Char(':') + strArg;
- }
- // mark the multiple signatures as such, to make it easier to generate different code
- if (multiple)
- s << idx-- << ':';
- s << funcName << '(' << args.join(QLatin1Char(',')) << ')';
- if (f->type())
- s << "->" << f->type()->pythonSignature();
- s << Qt::endl;
- }
-}
-
-void CppGenerator::writeEnumsInitialization(QTextStream &s, AbstractMetaEnumList &enums)
-{
- if (enums.isEmpty())
- return;
- s << INDENT << "// Initialization of enums.\n\n";
- for (const AbstractMetaEnum *cppEnum : qAsConst(enums)) {
- if (cppEnum->isPrivate())
- continue;
- writeEnumInitialization(s, cppEnum);
- }
-}
-
-static QString mangleName(QString name)
-{
- if ( name == QLatin1String("None")
- || name == QLatin1String("False")
- || name == QLatin1String("True"))
- name += QLatin1Char('_');
- return name;
-}
-
-void CppGenerator::writeEnumInitialization(QTextStream &s, const AbstractMetaEnum *cppEnum)
-{
- const AbstractMetaClass *enclosingClass = cppEnum->targetLangEnclosingClass();
- bool hasUpperEnclosingClass = enclosingClass && enclosingClass->targetLangEnclosingClass() != nullptr;
- const EnumTypeEntry *enumTypeEntry = cppEnum->typeEntry();
- QString enclosingObjectVariable;
- if (enclosingClass)
- enclosingObjectVariable = cpythonTypeName(enclosingClass);
- else if (hasUpperEnclosingClass)
- enclosingObjectVariable = QLatin1String("enclosingClass");
- else
- enclosingObjectVariable = QLatin1String("module");
-
- s << INDENT << "// Initialization of ";
- s << (cppEnum->isAnonymous() ? "anonymous enum identified by enum value" : "enum");
- s << " '" << cppEnum->name() << "'.\n";
-
- QString enumVarTypeObj;
- if (!cppEnum->isAnonymous()) {
- int packageLevel = packageName().count(QLatin1Char('.')) + 1;
- FlagsTypeEntry *flags = enumTypeEntry->flags();
- if (flags) {
- // The following could probably be made nicer:
- // We need 'flags->flagsName()' with the full module/class path.
- QString fullPath = getClassTargetFullName(cppEnum);
- fullPath.truncate(fullPath.lastIndexOf(QLatin1Char('.')) + 1);
- s << INDENT << cpythonTypeNameExt(flags) << " = PySide::QFlags::create(\""
- << packageLevel << ':' << fullPath << flags->flagsName() << "\", "
- << cpythonEnumName(cppEnum) << "_number_slots);\n";
- }
-
- enumVarTypeObj = cpythonTypeNameExt(enumTypeEntry);
-
- s << INDENT << enumVarTypeObj << " = Shiboken::Enum::";
- s << ((enclosingClass || hasUpperEnclosingClass) ? "createScopedEnum" : "createGlobalEnum");
- s << '(' << enclosingObjectVariable << ',' << Qt::endl;
- {
- Indentation indent(INDENT);
- s << INDENT << '"' << cppEnum->name() << "\",\n";
- s << INDENT << '"' << packageLevel << ':' << getClassTargetFullName(cppEnum) << "\",\n";
- s << INDENT << '"' << (cppEnum->enclosingClass() ? (cppEnum->enclosingClass()->qualifiedCppName() + QLatin1String("::")) : QString());
- s << cppEnum->name() << '"';
- if (flags)
- s << ',' << Qt::endl << INDENT << cpythonTypeNameExt(flags);
- s << ");\n";
- }
- s << INDENT << "if (!" << cpythonTypeNameExt(cppEnum->typeEntry()) << ")\n";
- {
- Indentation indent(INDENT);
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl << Qt::endl;
- }
- }
-
- const AbstractMetaEnumValueList &enumValues = cppEnum->values();
- for (const AbstractMetaEnumValue *enumValue : enumValues) {
- if (enumTypeEntry->isEnumValueRejected(enumValue->name()))
- continue;
-
- QString enumValueText;
- if (!avoidProtectedHack() || !cppEnum->isProtected()) {
- enumValueText = QLatin1String("(long) ");
- if (cppEnum->enclosingClass())
- enumValueText += cppEnum->enclosingClass()->qualifiedCppName() + QLatin1String("::");
- // Fully qualify the value which is required for C++ 11 enum classes.
- if (!cppEnum->isAnonymous())
- enumValueText += cppEnum->name() + QLatin1String("::");
- enumValueText += enumValue->name();
- } else {
- enumValueText += enumValue->value().toString();
- }
-
- switch (cppEnum->enumKind()) {
- case AnonymousEnum:
- if (enclosingClass || hasUpperEnclosingClass) {
- s << INDENT << "{\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyObject *anonEnumItem = PyInt_FromLong(" << enumValueText << ");\n";
- s << INDENT << "if (PyDict_SetItemString(reinterpret_cast<PyTypeObject *>(reinterpret_cast<SbkObjectType *>(" << enclosingObjectVariable
- << "))->tp_dict, \"" << mangleName(enumValue->name()) << "\", anonEnumItem) < 0)\n";
- {
- Indentation indent(INDENT);
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT << "Py_DECREF(anonEnumItem);\n";
- }
- s << INDENT << "}\n";
- } else {
- s << INDENT << "if (PyModule_AddIntConstant(module, \"" << mangleName(enumValue->name()) << "\", ";
- s << enumValueText << ") < 0)\n";
- {
- Indentation indent(INDENT);
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- }
- break;
- case CEnum: {
- s << INDENT << "if (!Shiboken::Enum::";
- s << ((enclosingClass || hasUpperEnclosingClass) ? "createScopedEnumItem" : "createGlobalEnumItem");
- s << '(' << enumVarTypeObj << ',' << Qt::endl;
- Indentation indent(INDENT);
- s << INDENT << enclosingObjectVariable << ", \"" << mangleName(enumValue->name()) << "\", ";
- s << enumValueText << "))\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- break;
- case EnumClass: {
- s << INDENT << "if (!Shiboken::Enum::createScopedEnumItem("
- << enumVarTypeObj << ',' << Qt::endl;
- Indentation indent(INDENT);
- s << INDENT << enumVarTypeObj<< ", \"" << mangleName(enumValue->name()) << "\", "
- << enumValueText << "))\n"
- << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- break;
- }
- }
-
- writeEnumConverterInitialization(s, cppEnum);
-
- s << INDENT << "// End of '" << cppEnum->name() << "' enum";
- if (cppEnum->typeEntry()->flags())
- s << "/flags";
- s << '.' << Qt::endl << Qt::endl;
-}
-
-void CppGenerator::writeSignalInitialization(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- // Try to check something and print some warnings
- const AbstractMetaFunctionList &signalFuncs = metaClass->cppSignalFunctions();
- for (const AbstractMetaFunction *cppSignal : signalFuncs) {
- if (cppSignal->declaringClass() != metaClass)
- continue;
- const AbstractMetaArgumentList &arguments = cppSignal->arguments();
- for (AbstractMetaArgument *arg : arguments) {
- AbstractMetaType *metaType = arg->type();
- const QByteArray origType =
- QMetaObject::normalizedType(qPrintable(metaType->originalTypeDescription()));
- const QByteArray cppSig =
- QMetaObject::normalizedType(qPrintable(metaType->cppSignature()));
- if ((origType != cppSig) && (!metaType->isFlags())) {
- qCWarning(lcShiboken).noquote().nospace()
- << "Typedef used on signal " << metaClass->qualifiedCppName() << "::"
- << cppSignal->signature();
- }
- }
- }
-
- s << INDENT << "PySide::Signal::registerSignals(" << cpythonTypeName(metaClass) << ", &::"
- << metaClass->qualifiedCppName() << "::staticMetaObject);\n";
-}
-
-void CppGenerator::writeFlagsToLong(QTextStream &s, const AbstractMetaEnum *cppEnum)
-{
- FlagsTypeEntry *flagsEntry = cppEnum->typeEntry()->flags();
- if (!flagsEntry)
- return;
- s << "static PyObject *" << cpythonEnumName(cppEnum) << "_long(PyObject *self)\n";
- s << "{\n";
- s << INDENT << "int val;\n";
- AbstractMetaType *flagsType = buildAbstractMetaTypeFromTypeEntry(flagsEntry);
- s << INDENT << cpythonToCppConversionFunction(flagsType) << "self, &val);\n";
- s << INDENT << "return Shiboken::Conversions::copyToPython(Shiboken::Conversions::PrimitiveTypeConverter<int>(), &val);\n";
- s << "}\n";
-}
-
-void CppGenerator::writeFlagsNonZero(QTextStream &s, const AbstractMetaEnum *cppEnum)
-{
- FlagsTypeEntry *flagsEntry = cppEnum->typeEntry()->flags();
- if (!flagsEntry)
- return;
- s << "static int " << cpythonEnumName(cppEnum) << "__nonzero(PyObject *self)\n";
- s << "{\n";
-
- s << INDENT << "int val;\n";
- AbstractMetaType *flagsType = buildAbstractMetaTypeFromTypeEntry(flagsEntry);
- s << INDENT << cpythonToCppConversionFunction(flagsType) << "self, &val);\n";
- s << INDENT << "return val != 0;\n";
- s << "}\n";
-}
-
-void CppGenerator::writeFlagsMethods(QTextStream &s, const AbstractMetaEnum *cppEnum)
-{
- writeFlagsBinaryOperator(s, cppEnum, QLatin1String("and"), QLatin1String("&"));
- writeFlagsBinaryOperator(s, cppEnum, QLatin1String("or"), QLatin1String("|"));
- writeFlagsBinaryOperator(s, cppEnum, QLatin1String("xor"), QLatin1String("^"));
-
- writeFlagsUnaryOperator(s, cppEnum, QLatin1String("invert"), QLatin1String("~"));
- writeFlagsToLong(s, cppEnum);
- writeFlagsNonZero(s, cppEnum);
-
- s << Qt::endl;
-}
-
-void CppGenerator::writeFlagsNumberMethodsDefinition(QTextStream &s, const AbstractMetaEnum *cppEnum)
-{
- QString cpythonName = cpythonEnumName(cppEnum);
-
- s << "static PyType_Slot " << cpythonName << "_number_slots[] = {\n";
- s << "#ifdef IS_PY3K\n";
- s << INDENT << "{Py_nb_bool, (void *)" << cpythonName << "__nonzero},\n";
- s << "#else\n";
- s << INDENT << "{Py_nb_nonzero, (void *)" << cpythonName << "__nonzero},\n";
- s << INDENT << "{Py_nb_long, (void *)" << cpythonName << "_long},\n";
- s << "#endif\n";
- s << INDENT << "{Py_nb_invert, (void *)" << cpythonName << "___invert__},\n";
- s << INDENT << "{Py_nb_and, (void *)" << cpythonName << "___and__},\n";
- s << INDENT << "{Py_nb_xor, (void *)" << cpythonName << "___xor__},\n";
- s << INDENT << "{Py_nb_or, (void *)" << cpythonName << "___or__},\n";
- s << INDENT << "{Py_nb_int, (void *)" << cpythonName << "_long},\n";
- s << INDENT << "{Py_nb_index, (void *)" << cpythonName << "_long},\n";
- s << "#ifndef IS_PY3K\n";
- s << INDENT << "{Py_nb_long, (void *)" << cpythonName << "_long},\n";
- s << "#endif\n";
- s << INDENT << "{0, " << NULL_PTR << "} // sentinel\n";
- s << "};\n\n";
-}
-
-void CppGenerator::writeFlagsBinaryOperator(QTextStream &s, const AbstractMetaEnum *cppEnum,
- const QString &pyOpName, const QString &cppOpName)
-{
- FlagsTypeEntry *flagsEntry = cppEnum->typeEntry()->flags();
- Q_ASSERT(flagsEntry);
-
- s << "PyObject * " << cpythonEnumName(cppEnum) << "___" << pyOpName
- << "__(PyObject *self, PyObject *" << PYTHON_ARG << ")\n{\n";
-
- AbstractMetaType *flagsType = buildAbstractMetaTypeFromTypeEntry(flagsEntry);
- s << INDENT << "::" << flagsEntry->originalName() << " cppResult, " << CPP_SELF_VAR << ", cppArg;\n";
- s << "#ifdef IS_PY3K\n";
- s << INDENT << CPP_SELF_VAR << " = static_cast<::" << flagsEntry->originalName()
- << ">(int(PyLong_AsLong(self)));\n";
- s << INDENT << "cppArg = static_cast<" << flagsEntry->originalName() << ">(int(PyLong_AsLong("
- << PYTHON_ARG << ")));\n";
- s << "#else\n";
- s << INDENT << CPP_SELF_VAR << " = static_cast<::" << flagsEntry->originalName()
- << ">(int(PyInt_AsLong(self)));\n";
- s << INDENT << "cppArg = static_cast<" << flagsEntry->originalName()
- << ">(int(PyInt_AsLong(" << PYTHON_ARG << ")));\n";
- s << "#endif\n\n";
- s << INDENT << "cppResult = " << CPP_SELF_VAR << " " << cppOpName << " cppArg;\n";
- s << INDENT << "return ";
- writeToPythonConversion(s, flagsType, nullptr, QLatin1String("cppResult"));
- s << ";\n";
- s<< "}\n\n";
-}
-
-void CppGenerator::writeFlagsUnaryOperator(QTextStream &s, const AbstractMetaEnum *cppEnum,
- const QString &pyOpName,
- const QString &cppOpName, bool boolResult)
-{
- FlagsTypeEntry *flagsEntry = cppEnum->typeEntry()->flags();
- Q_ASSERT(flagsEntry);
-
- s << "PyObject *" << cpythonEnumName(cppEnum) << "___" << pyOpName
- << "__(PyObject *self, PyObject *" << PYTHON_ARG << ")\n{\n";
-
- AbstractMetaType *flagsType = buildAbstractMetaTypeFromTypeEntry(flagsEntry);
- s << INDENT << "::" << flagsEntry->originalName() << " " << CPP_SELF_VAR << ";\n";
- s << INDENT << cpythonToCppConversionFunction(flagsType) << "self, &" << CPP_SELF_VAR << ");\n";
- s << INDENT;
- if (boolResult)
- s << "bool";
- else
- s << "::" << flagsEntry->originalName();
- s << " cppResult = " << cppOpName << CPP_SELF_VAR << ";\n";
- s << INDENT << "return ";
- if (boolResult)
- s << "PyBool_FromLong(cppResult)";
- else
- writeToPythonConversion(s, flagsType, nullptr, QLatin1String("cppResult"));
- s << ";\n";
- s<< "}\n\n";
-}
-
-QString CppGenerator::getSimpleClassInitFunctionName(const AbstractMetaClass *metaClass) const
-{
- QString initFunctionName;
- // Disambiguate namespaces per module to allow for extending them.
- if (metaClass->isNamespace())
- initFunctionName += moduleName();
- initFunctionName += metaClass->qualifiedCppName();
- initFunctionName.replace(QLatin1String("::"), QLatin1String("_"));
- return initFunctionName;
-}
-
-QString CppGenerator::getInitFunctionName(const GeneratorContext &context) const
-{
- return !context.forSmartPointer()
- ? getSimpleClassInitFunctionName(context.metaClass())
- : getFilteredCppSignatureString(context.preciseType()->cppSignature());
-}
-
-void CppGenerator::writeSignatureStrings(QTextStream &s,
- QTextStream &signatureStream,
- const QString &arrayName,
- const char *comment) const
-{
- s << "// The signatures string for the " << comment << ".\n";
- s << "// Multiple signatures have their index \"n:\" in front.\n";
- s << "static const char *" << arrayName << "_SignatureStrings[] = {\n";
- QString line;
- while (signatureStream.readLineInto(&line))
- s << INDENT << "R\"CPP(" << line << ")CPP\",\n";
- s << INDENT << NULL_PTR << "}; // Sentinel\n\n";
-}
-
-void CppGenerator::writeClassRegister(QTextStream &s,
- const AbstractMetaClass *metaClass,
- const GeneratorContext &classContext,
- QTextStream &signatureStream)
-{
- const ComplexTypeEntry *classTypeEntry = metaClass->typeEntry();
-
- const AbstractMetaClass *enc = metaClass->targetLangEnclosingClass();
- QString enclosingObjectVariable = enc ? QLatin1String("enclosingClass") : QLatin1String("module");
-
- QString pyTypeName = cpythonTypeName(metaClass);
- QString initFunctionName = getInitFunctionName(classContext);
-
- // PYSIDE-510: Create a signatures string for the introspection feature.
- writeSignatureStrings(s, signatureStream, initFunctionName, "functions");
- s << "void init_" << initFunctionName;
- s << "(PyObject *" << enclosingObjectVariable << ")\n{\n";
-
- // Multiple inheritance
- QString pyTypeBasesVariable = chopType(pyTypeName) + QLatin1String("_Type_bases");
- const AbstractMetaClassList baseClasses = getBaseClasses(metaClass);
- if (metaClass->baseClassNames().size() > 1) {
- s << INDENT << "PyObject *" << pyTypeBasesVariable
- << " = PyTuple_Pack(" << baseClasses.size() << ',' << Qt::endl;
- Indentation indent(INDENT);
- for (int i = 0, size = baseClasses.size(); i < size; ++i) {
- if (i)
- s << ",\n";
- s << INDENT << "reinterpret_cast<PyObject *>("
- << cpythonTypeNameExt(baseClasses.at(i)->typeEntry()) << ')';
- }
- s << ");\n\n";
- }
-
- // Create type and insert it in the module or enclosing class.
- const QString typePtr = QLatin1String("_") + chopType(pyTypeName)
- + QLatin1String("_Type");
-
- s << INDENT << typePtr << " = Shiboken::ObjectType::introduceWrapperType(\n";
- {
- Indentation indent(INDENT);
- // 1:enclosingObject
- s << INDENT << enclosingObjectVariable << ",\n";
- QString typeName;
- if (!classContext.forSmartPointer())
- typeName = metaClass->name();
- else
- typeName = classContext.preciseType()->cppSignature();
-
- // 2:typeName
- s << INDENT << "\"" << typeName << "\",\n";
-
- // 3:originalName
- s << INDENT << "\"";
- if (!classContext.forSmartPointer()) {
- s << metaClass->qualifiedCppName();
- if (isObjectType(classTypeEntry))
- s << '*';
- } else {
- s << classContext.preciseType()->cppSignature();
- }
-
- s << "\",\n";
- // 4:typeSpec
- s << INDENT << '&' << chopType(pyTypeName) << "_spec,\n";
-
- // 5:signatureStrings
- s << INDENT << initFunctionName << "_SignatureStrings,\n";
-
- // 6:cppObjDtor
- s << INDENT;
- if (!metaClass->isNamespace() && !metaClass->hasPrivateDestructor()) {
- QString dtorClassName = metaClass->qualifiedCppName();
- if (((avoidProtectedHack() && metaClass->hasProtectedDestructor()) || classTypeEntry->isValue())
- && classContext.useWrapper()) {
- dtorClassName = classContext.wrapperName();
- }
- if (classContext.forSmartPointer())
- dtorClassName = classContext.smartPointerWrapperName();
-
- s << "&Shiboken::callCppDestructor< ::" << dtorClassName << " >,\n";
- } else {
- s << "0,\n";
- }
-
- // 7:baseType
- const auto base = metaClass->isNamespace()
- ? metaClass->extendedNamespace() : metaClass->baseClass();
- if (base) {
- s << INDENT << "reinterpret_cast<SbkObjectType *>("
- << cpythonTypeNameExt(base->typeEntry()) << "),\n";
- } else {
- s << INDENT << "0,\n";
- }
-
- // 8:baseTypes
- if (metaClass->baseClassNames().size() > 1)
- s << INDENT << pyTypeBasesVariable << ',' << Qt::endl;
- else
- s << INDENT << "0,\n";
-
- // 9:wrapperflags
- QByteArrayList wrapperFlags;
- if (enc)
- wrapperFlags.append(QByteArrayLiteral("Shiboken::ObjectType::WrapperFlags::InnerClass"));
- if (metaClass->deleteInMainThread())
- wrapperFlags.append(QByteArrayLiteral("Shiboken::ObjectType::WrapperFlags::DeleteInMainThread"));
- if (wrapperFlags.isEmpty())
- s << INDENT << '0';
- else
- s << INDENT << wrapperFlags.join(" | ");
- }
- s << INDENT << ");\n";
- s << INDENT << Qt::endl;
-
- if (!classContext.forSmartPointer())
- s << INDENT << cpythonTypeNameExt(classTypeEntry) << Qt::endl;
- else
- s << INDENT << cpythonTypeNameExt(classContext.preciseType()) << Qt::endl;
- s << INDENT << " = reinterpret_cast<PyTypeObject *>(" << pyTypeName << ");\n";
- s << Qt::endl;
-
- // Register conversions for the type.
- writeConverterRegister(s, metaClass, classContext);
- s << Qt::endl;
-
- // class inject-code target/beginning
- if (!classTypeEntry->codeSnips().isEmpty()) {
- writeClassCodeSnips(s, classTypeEntry->codeSnips(),
- TypeSystem::CodeSnipPositionBeginning, TypeSystem::TargetLangCode,
- classContext);
- s << Qt::endl;
- }
-
- // Fill multiple inheritance data, if needed.
- const AbstractMetaClass *miClass = getMultipleInheritingClass(metaClass);
- if (miClass) {
- s << INDENT << "MultipleInheritanceInitFunction func = ";
- if (miClass == metaClass) {
- s << multipleInheritanceInitializerFunctionName(miClass) << ";\n";
- } else {
- s << "Shiboken::ObjectType::getMultipleInheritanceFunction(reinterpret_cast<SbkObjectType *>(";
- s << cpythonTypeNameExt(miClass->typeEntry()) << "));\n";
- }
- s << INDENT << "Shiboken::ObjectType::setMultipleInheritanceFunction(";
- s << cpythonTypeName(metaClass) << ", func);\n";
- s << INDENT << "Shiboken::ObjectType::setCastFunction(" << cpythonTypeName(metaClass);
- s << ", &" << cpythonSpecialCastFunctionName(metaClass) << ");\n";
- }
-
- // Set typediscovery struct or fill the struct of another one
- if (metaClass->isPolymorphic() && metaClass->baseClass()) {
- s << INDENT << "Shiboken::ObjectType::setTypeDiscoveryFunctionV2(" << cpythonTypeName(metaClass);
- s << ", &" << cpythonBaseName(metaClass) << "_typeDiscovery);\n\n";
- }
-
- AbstractMetaEnumList classEnums = metaClass->enums();
- const AbstractMetaClassList &innerClasses = metaClass->innerClasses();
- for (AbstractMetaClass *innerClass : innerClasses)
- lookForEnumsInClassesNotToBeGenerated(classEnums, innerClass);
-
- ErrorCode errorCode(QString::fromLatin1(""));
- writeEnumsInitialization(s, classEnums);
-
- if (metaClass->hasSignals())
- writeSignalInitialization(s, metaClass);
-
- // Write static fields
- const AbstractMetaFieldList &fields = metaClass->fields();
- for (const AbstractMetaField *field : fields) {
- if (!field->isStatic())
- continue;
- s << INDENT << QLatin1String("PyDict_SetItemString(reinterpret_cast<PyTypeObject *>(") + cpythonTypeName(metaClass) + QLatin1String(")->tp_dict, \"");
- s << field->name() << "\", ";
- writeToPythonConversion(s, field->type(), metaClass, metaClass->qualifiedCppName() + QLatin1String("::") + field->name());
- s << ");\n";
- }
- s << Qt::endl;
-
- // class inject-code target/end
- if (!classTypeEntry->codeSnips().isEmpty()) {
- s << Qt::endl;
- writeClassCodeSnips(s, classTypeEntry->codeSnips(),
- TypeSystem::CodeSnipPositionEnd, TypeSystem::TargetLangCode,
- classContext);
- }
-
- if (usePySideExtensions()) {
- if (avoidProtectedHack() && classContext.useWrapper())
- s << INDENT << classContext.wrapperName() << "::pysideInitQtMetaTypes();\n";
- else
- writeInitQtMetaTypeFunctionBody(s, classContext);
- }
-
- if (usePySideExtensions() && metaClass->isQObject()) {
- s << INDENT << "Shiboken::ObjectType::setSubTypeInitHook(" << pyTypeName << ", &PySide::initQObjectSubType);\n";
- s << INDENT << "PySide::initDynamicMetaObject(" << pyTypeName << ", &::" << metaClass->qualifiedCppName()
- << "::staticMetaObject, sizeof(";
- if (shouldGenerateCppWrapper(metaClass))
- s << wrapperName(metaClass);
- else
- s << "::" << metaClass->qualifiedCppName();
- s << "));\n";
- }
-
- s << "}\n";
-}
-
-void CppGenerator::writeInitQtMetaTypeFunctionBody(QTextStream &s, const GeneratorContext &context) const
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- // Gets all class name variants used on different possible scopes
- QStringList nameVariants;
- if (!context.forSmartPointer())
- nameVariants << metaClass->name();
- else
- nameVariants << context.preciseType()->cppSignature();
-
- const AbstractMetaClass *enclosingClass = metaClass->enclosingClass();
- while (enclosingClass) {
- if (enclosingClass->typeEntry()->generateCode())
- nameVariants << (enclosingClass->name() + QLatin1String("::") + nameVariants.constLast());
- enclosingClass = enclosingClass->enclosingClass();
- }
-
- QString className;
- if (!context.forSmartPointer())
- className = metaClass->qualifiedCppName();
- else
- className = context.preciseType()->cppSignature();
-
- if (!metaClass->isNamespace() && !metaClass->isAbstract()) {
- // Qt metatypes are registered only on their first use, so we do this now.
- bool canBeValue = false;
- if (!isObjectType(metaClass)) {
- // check if there's a empty ctor
- const AbstractMetaFunctionList &funcs = metaClass->functions();
- for (AbstractMetaFunction *func : funcs) {
- if (func->isConstructor() && !func->arguments().count()) {
- canBeValue = true;
- break;
- }
- }
- }
-
- if (canBeValue) {
- for (const QString &name : qAsConst(nameVariants)) {
- if (name == QLatin1String("iterator")) {
- qCWarning(lcShiboken).noquote().nospace()
- << QString::fromLatin1("%1:%2 FIXME:\n"
- " The code tried to qRegisterMetaType the unqualified name "
- "'iterator'. This is currently fixed by a hack(ct) and needs improvement!")
- .arg(QFile::decodeName(__FILE__)).arg(__LINE__);
- continue;
- }
- s << INDENT << "qRegisterMetaType< ::" << className << " >(\"" << name << "\");\n";
- }
- }
- }
-
- const AbstractMetaEnumList &enums = metaClass->enums();
- for (AbstractMetaEnum *metaEnum : enums) {
- if (!metaEnum->isPrivate() && !metaEnum->isAnonymous()) {
- for (const QString &name : qAsConst(nameVariants))
- s << INDENT << "qRegisterMetaType< ::" << metaEnum->typeEntry()->qualifiedCppName() << " >(\"" << name << "::" << metaEnum->name() << "\");\n";
-
- if (metaEnum->typeEntry()->flags()) {
- QString n = metaEnum->typeEntry()->flags()->originalName();
- s << INDENT << "qRegisterMetaType< ::" << n << " >(\"" << n << "\");\n";
- }
- }
- }
-}
-
-void CppGenerator::writeTypeDiscoveryFunction(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- QString polymorphicExpr = metaClass->typeEntry()->polymorphicIdValue();
-
- s << "static void *" << cpythonBaseName(metaClass) << "_typeDiscovery(void *cptr, SbkObjectType *instanceType)\n{\n";
-
- if (!polymorphicExpr.isEmpty()) {
- polymorphicExpr = polymorphicExpr.replace(QLatin1String("%1"),
- QLatin1String(" reinterpret_cast< ::")
- + metaClass->qualifiedCppName()
- + QLatin1String(" *>(cptr)"));
- s << INDENT << " if (" << polymorphicExpr << ")\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return cptr;\n";
- }
- } else if (metaClass->isPolymorphic()) {
- const AbstractMetaClassList &ancestors = getAllAncestors(metaClass);
- for (AbstractMetaClass *ancestor : ancestors) {
- if (ancestor->baseClass())
- continue;
- if (ancestor->isPolymorphic()) {
- s << INDENT << "if (instanceType == reinterpret_cast<SbkObjectType *>(Shiboken::SbkType< ::"
- << ancestor->qualifiedCppName() << " >()))\n";
- Indentation indent(INDENT);
- s << INDENT << "return dynamic_cast< ::" << metaClass->qualifiedCppName()
- << " *>(reinterpret_cast< ::"<< ancestor->qualifiedCppName() << " *>(cptr));\n";
- } else {
- qCWarning(lcShiboken).noquote().nospace()
- << metaClass->qualifiedCppName() << " inherits from a non polymorphic type ("
- << ancestor->qualifiedCppName() << "), type discovery based on RTTI is "
- "impossible, write a polymorphic-id-expression for this type.";
- }
-
- }
- }
- s << INDENT << "return {};\n";
- s << "}\n\n";
-}
-
-QString CppGenerator::writeSmartPointerGetterCast()
-{
- return QLatin1String("const_cast<char *>(")
- + QLatin1String(SMART_POINTER_GETTER) + QLatin1Char(')');
-}
-
-void CppGenerator::writeSetattroDefinition(QTextStream &s, const AbstractMetaClass *metaClass) const
-{
- s << "static int " << ShibokenGenerator::cpythonSetattroFunctionName(metaClass)
- << "(PyObject *self, PyObject *name, PyObject *value)\n{\n";
- if (wrapperDiagnostics()) {
- s << INDENT << R"(std::cerr << __FUNCTION__ << ' ' << Shiboken::debugPyObject(name)
- << ' ' << Shiboken::debugPyObject(value) << '\n';)" << '\n';
- }
-}
-
-inline void CppGenerator::writeSetattroDefaultReturn(QTextStream &s) const
-{
- s << INDENT << "return PyObject_GenericSetAttr(self, name, value);\n}\n\n";
-}
-
-void CppGenerator::writeSetattroFunction(QTextStream &s, AttroCheck attroCheck,
- const GeneratorContext &context)
-{
- Q_ASSERT(!context.forSmartPointer());
- const AbstractMetaClass *metaClass = context.metaClass();
- writeSetattroDefinition(s, metaClass);
- // PYSIDE-803: Detect duck-punching; clear cache if a method is set.
- if (attroCheck.testFlag(AttroCheckFlag::SetattroMethodOverride)
- && context.useWrapper()) {
- s << INDENT << "if (value && PyCallable_Check(value)) {\n";
- s << INDENT << " auto plain_inst = " << cpythonWrapperCPtr(metaClass, QLatin1String("self")) << ";\n";
- s << INDENT << " auto inst = dynamic_cast<" << context.wrapperName() << " *>(plain_inst);\n";
- s << INDENT << " if (inst)\n";
- s << INDENT << " inst->resetPyMethodCache();\n";
- s << INDENT << "}\n";
- }
- if (attroCheck.testFlag(AttroCheckFlag::SetattroQObject)) {
- s << INDENT << "Shiboken::AutoDecRef pp(reinterpret_cast<PyObject *>(PySide::Property::getObject(self, name)));\n";
- s << INDENT << "if (!pp.isNull())\n";
- Indentation indent(INDENT);
- s << INDENT << "return PySide::Property::setValue(reinterpret_cast<PySideProperty *>(pp.object()), self, value);\n";
- }
-
- if (attroCheck.testFlag(AttroCheckFlag::SetattroUser)) {
- auto func = AbstractMetaClass::queryFirstFunction(metaClass->functions(),
- AbstractMetaClass::SetAttroFunction);
- Q_ASSERT(func);
- s << INDENT << "{\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "auto " << CPP_SELF_VAR << " = "
- << cpythonWrapperCPtr(metaClass, QLatin1String("self")) << ";\n";
- writeClassCodeSnips(s, func->injectedCodeSnips(), TypeSystem::CodeSnipPositionAny,
- TypeSystem::TargetLangCode, context);
- }
- s << INDENT << "}\n";
- }
-
- writeSetattroDefaultReturn(s);
-}
-
-void CppGenerator::writeSmartPointerSetattroFunction(QTextStream &s, const GeneratorContext &context)
-{
- Q_ASSERT(context.forSmartPointer());
- writeSetattroDefinition(s, context.metaClass());
- s << INDENT << "// Try to find the 'name' attribute, by retrieving the PyObject for the corresponding C++ object held by the smart pointer.\n";
- s << INDENT << "PyObject *rawObj = PyObject_CallMethod(self, "
- << writeSmartPointerGetterCast() << ", 0);\n";
- s << INDENT << "if (rawObj) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "int hasAttribute = PyObject_HasAttr(rawObj, name);\n";
- s << INDENT << "if (hasAttribute) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return PyObject_GenericSetAttr(rawObj, name, value);\n";
- }
- s << INDENT << "}\n";
- s << INDENT << "Py_DECREF(rawObj);\n";
- }
- s << INDENT << "}\n";
- writeSetattroDefaultReturn(s);
-}
-
-static inline QString qObjectClassName() { return QStringLiteral("QObject"); }
-static inline QString qMetaObjectClassName() { return QStringLiteral("QMetaObject"); }
-
-void CppGenerator::writeGetattroDefinition(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- s << "static PyObject *" << cpythonGetattroFunctionName(metaClass)
- << "(PyObject *self, PyObject *name)\n{\n";
-}
-
-QString CppGenerator::qObjectGetAttroFunction() const
-{
- static QString result;
- if (result.isEmpty()) {
- AbstractMetaClass *qobjectClass = AbstractMetaClass::findClass(classes(), qObjectClassName());
- Q_ASSERT(qobjectClass);
- result = QLatin1String("PySide::getMetaDataFromQObject(")
- + cpythonWrapperCPtr(qobjectClass, QLatin1String("self"))
- + QLatin1String(", self, name)");
- }
- return result;
-}
-
-void CppGenerator::writeGetattroFunction(QTextStream &s, AttroCheck attroCheck,
- const GeneratorContext &context)
-{
- Q_ASSERT(!context.forSmartPointer());
- const AbstractMetaClass *metaClass = context.metaClass();
- writeGetattroDefinition(s, metaClass);
-
- const QString getattrFunc = usePySideExtensions() && metaClass->isQObject()
- ? qObjectGetAttroFunction() : QLatin1String("PyObject_GenericGetAttr(self, name)");
-
- if (attroCheck.testFlag(AttroCheckFlag::GetattroOverloads)) {
- s << INDENT << "// Search the method in the instance dict\n";
- s << INDENT << "if (auto ob_dict = reinterpret_cast<SbkObject *>(self)->ob_dict) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "if (auto meth = PyDict_GetItem(ob_dict, name)) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "Py_INCREF(meth);\n";
- s << INDENT << "return meth;\n";
- }
- s << INDENT << "}\n";
- }
- s << INDENT << "}\n";
- s << INDENT << "// Search the method in the type dict\n";
- s << INDENT << "if (Shiboken::Object::isUserType(self)) {\n";
- {
- Indentation indent(INDENT);
- // PYSIDE-772: Perform optimized name mangling.
- s << INDENT << "Shiboken::AutoDecRef tmp(_Pep_PrivateMangle(self, name));\n";
- s << INDENT << "if (auto meth = PyDict_GetItem(Py_TYPE(self)->tp_dict, tmp))\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return PyFunction_Check(meth) ? SBK_PyMethod_New(meth, self) : " << getattrFunc << ";\n";
- }
- }
- s << INDENT << "}\n";
-
- const AbstractMetaFunctionList &funcs = getMethodsWithBothStaticAndNonStaticMethods(metaClass);
- for (const AbstractMetaFunction *func : funcs) {
- QString defName = cpythonMethodDefinitionName(func);
- s << INDENT << "static PyMethodDef non_static_" << defName << " = {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << defName << ".ml_name,\n";
- s << INDENT << defName << ".ml_meth,\n";
- s << INDENT << defName << ".ml_flags & (~METH_STATIC),\n";
- s << INDENT << defName << ".ml_doc,\n";
- }
- s << INDENT << "};\n";
- s << INDENT << "if (Shiboken::String::compare(name, \"" << func->name() << "\") == 0)\n";
- Indentation indent(INDENT);
- s << INDENT << "return PyCFunction_NewEx(&non_static_" << defName << ", self, 0);\n";
- }
- }
-
- if (attroCheck.testFlag(AttroCheckFlag::GetattroUser)) {
- auto func = AbstractMetaClass::queryFirstFunction(metaClass->functions(),
- AbstractMetaClass::GetAttroFunction);
- Q_ASSERT(func);
- s << INDENT << "{\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "auto " << CPP_SELF_VAR << " = "
- << cpythonWrapperCPtr(metaClass, QLatin1String("self")) << ";\n";
- writeClassCodeSnips(s, func->injectedCodeSnips(), TypeSystem::CodeSnipPositionAny,
- TypeSystem::TargetLangCode, context);
- }
- s << INDENT << "}\n";
- }
-
- s << INDENT << "return " << getattrFunc << ";\n}\n\n";
-}
-
-void CppGenerator::writeSmartPointerGetattroFunction(QTextStream &s, const GeneratorContext &context)
-{
- Q_ASSERT(context.forSmartPointer());
- const AbstractMetaClass *metaClass = context.metaClass();
- writeGetattroDefinition(s, metaClass);
- s << INDENT << "PyObject *tmp = PyObject_GenericGetAttr(self, name);\n";
- s << INDENT << "if (tmp)\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return tmp;\n";
- }
- s << INDENT << "if (!PyErr_ExceptionMatches(PyExc_AttributeError))\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return nullptr;\n";
- }
- s << INDENT << "PyErr_Clear();\n";
-
- // This generates the code which dispatches access to member functions
- // and fields from the smart pointer to its pointee.
- s << INDENT << "// Try to find the 'name' attribute, by retrieving the PyObject for "
- "the corresponding C++ object held by the smart pointer.\n";
- s << INDENT << "if (auto rawObj = PyObject_CallMethod(self, "
- << writeSmartPointerGetterCast() << ", 0)) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "if (auto attribute = PyObject_GetAttr(rawObj, name))\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "tmp = attribute;\n";
- }
- s << INDENT << "Py_DECREF(rawObj);\n";
- }
- s << INDENT << "}\n";
- s << INDENT << "if (!tmp) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyTypeObject *tp = Py_TYPE(self);\n";
- s << INDENT << "PyErr_Format(PyExc_AttributeError,\n";
- s << INDENT << " \"'%.50s' object has no attribute '%.400s'\",\n";
- s << INDENT << " tp->tp_name, Shiboken::String::toCString(name));\n";
- }
- s << INDENT << "}\n";
- s << INDENT << "return tmp;\n}\n\n";
-}
-
-// Write declaration and invocation of the init function for the module init
-// function.
-void CppGenerator::writeInitFunc(QTextStream &declStr, QTextStream &callStr,
- const Indentor &indent, const QString &initFunctionName,
- const TypeEntry *enclosingEntry)
-{
- const bool hasParent =
- enclosingEntry && enclosingEntry->type() != TypeEntry::TypeSystemType;
- declStr << "void init_" << initFunctionName << "(PyObject *"
- << (hasParent ? "enclosingClass" : "module") << ");\n";
- callStr << indent << "init_" << initFunctionName;
- if (hasParent) {
- callStr << "(reinterpret_cast<PyTypeObject *>("
- << cpythonTypeNameExt(enclosingEntry) << ")->tp_dict);\n";
- } else {
- callStr << "(module);\n";
- }
-}
-
-bool CppGenerator::finishGeneration()
-{
- //Generate CPython wrapper file
- QString classInitDecl;
- QTextStream s_classInitDecl(&classInitDecl);
- QString classPythonDefines;
- QTextStream s_classPythonDefines(&classPythonDefines);
-
- QSet<Include> includes;
- QString globalFunctionImpl;
- QTextStream s_globalFunctionImpl(&globalFunctionImpl);
- QString globalFunctionDecl;
- QTextStream s_globalFunctionDef(&globalFunctionDecl);
- QString signaturesString;
- QTextStream signatureStream(&signaturesString);
-
- Indentation indent(INDENT);
-
- const auto functionGroups = getGlobalFunctionGroups();
- for (auto it = functionGroups.cbegin(), end = functionGroups.cend(); it != end; ++it) {
- AbstractMetaFunctionList overloads;
- for (AbstractMetaFunction *func : it.value()) {
- if (!func->isModifiedRemoved()) {
- overloads.append(func);
- if (func->typeEntry())
- includes << func->typeEntry()->include();
- }
- }
-
- if (overloads.isEmpty())
- continue;
-
- // Dummy context to satisfy the API.
- GeneratorContext classContext;
- writeMethodWrapper(s_globalFunctionImpl, overloads, classContext);
- writeSignatureInfo(signatureStream, overloads);
- writeMethodDefinition(s_globalFunctionDef, overloads);
- }
-
- //this is a temporary solution before new type revison implementation
- //We need move QMetaObject register before QObject
- Dependencies additionalDependencies;
- const AbstractMetaClassList &allClasses = classes();
- if (auto qObjectClass = AbstractMetaClass::findClass(allClasses, qObjectClassName())) {
- if (auto qMetaObjectClass = AbstractMetaClass::findClass(allClasses, qMetaObjectClassName())) {
- Dependency dependency;
- dependency.parent = qMetaObjectClass;
- dependency.child = qObjectClass;
- additionalDependencies.append(dependency);
- }
- }
- const AbstractMetaClassList lst = classesTopologicalSorted(additionalDependencies);
-
- for (const AbstractMetaClass *cls : lst){
- if (shouldGenerate(cls)) {
- writeInitFunc(s_classInitDecl, s_classPythonDefines, INDENT,
- getSimpleClassInitFunctionName(cls),
- cls->typeEntry()->targetLangEnclosingEntry());
- }
- }
-
- // Initialize smart pointer types.
- const QVector<const AbstractMetaType *> &smartPtrs = instantiatedSmartPointers();
- for (const AbstractMetaType *metaType : smartPtrs) {
- GeneratorContext context = contextForSmartPointer(nullptr, metaType);
- writeInitFunc(s_classInitDecl, s_classPythonDefines, INDENT,
- getInitFunctionName(context),
- metaType->typeEntry()->targetLangEnclosingEntry());
- }
-
- QString moduleFileName(outputDirectory() + QLatin1Char('/') + subDirectoryForPackage(packageName()));
- moduleFileName += QLatin1Char('/') + moduleName().toLower() + QLatin1String("_module_wrapper.cpp");
-
-
- verifyDirectoryFor(moduleFileName);
- FileOut file(moduleFileName);
-
- QTextStream &s = file.stream;
-
- // write license comment
- s << licenseComment() << Qt::endl;
-
- s << "#include <sbkpython.h>\n";
- s << "#include <shiboken.h>\n";
- s << "#include <algorithm>\n";
- s << "#include <signature.h>\n";
- if (usePySideExtensions()) {
- s << includeQDebug;
- s << "#include <pyside.h>\n";
- s << "#include <qapp_macro.h>\n";
- }
-
- s << "#include \"" << getModuleHeaderFileName() << '"' << Qt::endl << Qt::endl;
- for (const Include &include : qAsConst(includes))
- s << include;
- s << Qt::endl;
-
- // Global enums
- AbstractMetaEnumList globalEnums = this->globalEnums();
- const AbstractMetaClassList &classList = classes();
- for (const AbstractMetaClass *metaClass : classList) {
- const AbstractMetaClass *encClass = metaClass->enclosingClass();
- if (!encClass || !NamespaceTypeEntry::isVisibleScope(encClass->typeEntry()))
- lookForEnumsInClassesNotToBeGenerated(globalEnums, metaClass);
- }
-
- TypeDatabase *typeDb = TypeDatabase::instance();
- const TypeSystemTypeEntry *moduleEntry = typeDb->defaultTypeSystemType();
- Q_ASSERT(moduleEntry);
-
- //Extra includes
- s << Qt::endl << "// Extra includes\n";
- QVector<Include> extraIncludes = moduleEntry->extraIncludes();
- for (AbstractMetaEnum *cppEnum : qAsConst(globalEnums))
- extraIncludes.append(cppEnum->typeEntry()->extraIncludes());
- std::sort(extraIncludes.begin(), extraIncludes.end());
- for (const Include &inc : qAsConst(extraIncludes))
- s << inc;
- s << Qt::endl;
-
- s << "// Current module's type array.\n";
- s << "PyTypeObject **" << cppApiVariableName() << " = nullptr;\n";
-
- s << "// Current module's PyObject pointer.\n";
- s << "PyObject *" << pythonModuleObjectName() << " = nullptr;\n";
-
- s << "// Current module's converter array.\n";
- s << "SbkConverter **" << convertersVariableName() << " = nullptr;\n";
-
- const CodeSnipList snips = moduleEntry->codeSnips();
-
- // module inject-code native/beginning
- if (!snips.isEmpty()) {
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionBeginning, TypeSystem::NativeCode);
- s << Qt::endl;
- }
-
- // cleanup staticMetaObject attribute
- if (usePySideExtensions()) {
- s << "void cleanTypesAttributes(void) {\n";
- s << INDENT << "if (PY_VERSION_HEX >= 0x03000000 && PY_VERSION_HEX < 0x03060000)\n";
- s << INDENT << " return; // PYSIDE-953: testbinding crashes in Python 3.5 when hasattr touches types!\n";
- s << INDENT << "for (int i = 0, imax = SBK_" << moduleName() << "_IDX_COUNT; i < imax; i++) {\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << "PyObject *pyType = reinterpret_cast<PyObject *>(" << cppApiVariableName() << "[i]);\n";
- s << INDENT << "Shiboken::AutoDecRef attrName(Py_BuildValue(\"s\", \"staticMetaObject\"));\n";
- s << INDENT << "if (pyType && PyObject_HasAttr(pyType, attrName))\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << "PyObject_SetAttr(pyType, attrName, Py_None);\n";
- }
- }
- s << INDENT << "}\n";
- s << "}\n";
- }
-
- s << "// Global functions ";
- s << "------------------------------------------------------------\n";
- s << globalFunctionImpl << Qt::endl;
-
- s << "static PyMethodDef " << moduleName() << "_methods[] = {\n";
- s << globalFunctionDecl;
- s << INDENT << "{0} // Sentinel\n" << "};\n\n";
-
- s << "// Classes initialization functions ";
- s << "------------------------------------------------------------\n";
- s << classInitDecl << Qt::endl;
-
- if (!globalEnums.isEmpty()) {
- QString converterImpl;
- QTextStream convImpl(&converterImpl);
-
- s << "// Enum definitions ";
- s << "------------------------------------------------------------\n";
- for (const AbstractMetaEnum *cppEnum : qAsConst(globalEnums)) {
- if (cppEnum->isAnonymous() || cppEnum->isPrivate())
- continue;
- writeEnumConverterFunctions(s, cppEnum);
- s << Qt::endl;
- }
-
- if (!converterImpl.isEmpty()) {
- s << "// Enum converters ";
- s << "------------------------------------------------------------\n";
- s << "namespace Shiboken\n{\n";
- s << converterImpl << Qt::endl;
- s << "} // namespace Shiboken\n\n";
- }
- }
-
- const QStringList &requiredModules = typeDb->requiredTargetImports();
- if (!requiredModules.isEmpty())
- s << "// Required modules' type and converter arrays.\n";
- for (const QString &requiredModule : requiredModules) {
- s << "PyTypeObject **" << cppApiVariableName(requiredModule) << ";\n";
- s << "SbkConverter **" << convertersVariableName(requiredModule) << ";\n";
- }
- s << Qt::endl;
-
- s << "// Module initialization ";
- s << "------------------------------------------------------------\n";
- ExtendedConverterData extendedConverters = getExtendedConverters();
- if (!extendedConverters.isEmpty()) {
- s << Qt::endl << "// Extended Converters.\n\n";
- for (ExtendedConverterData::const_iterator it = extendedConverters.cbegin(), end = extendedConverters.cend(); it != end; ++it) {
- const TypeEntry *externalType = it.key();
- s << "// Extended implicit conversions for " << externalType->qualifiedTargetLangName() << '.' << Qt::endl;
- for (const AbstractMetaClass *sourceClass : it.value()) {
- AbstractMetaType *sourceType = buildAbstractMetaTypeFromAbstractMetaClass(sourceClass);
- AbstractMetaType *targetType = buildAbstractMetaTypeFromTypeEntry(externalType);
- writePythonToCppConversionFunctions(s, sourceType, targetType);
- }
- }
- }
-
- const QVector<const CustomConversion *> &typeConversions = getPrimitiveCustomConversions();
- if (!typeConversions.isEmpty()) {
- s << Qt::endl << "// Primitive Type converters.\n\n";
- for (const CustomConversion *conversion : typeConversions) {
- s << "// C++ to Python conversion for type '" << conversion->ownerType()->qualifiedCppName() << "'.\n";
- writeCppToPythonFunction(s, conversion);
- writeCustomConverterFunctions(s, conversion);
- }
- s << Qt::endl;
- }
-
- const QVector<const AbstractMetaType *> &containers = instantiatedContainers();
- if (!containers.isEmpty()) {
- s << "// Container Type converters.\n\n";
- for (const AbstractMetaType *container : containers) {
- s << "// C++ to Python conversion for type '" << container->cppSignature() << "'.\n";
- writeContainerConverterFunctions(s, container);
- }
- s << Qt::endl;
- }
-
- s << "#if defined _WIN32 || defined __CYGWIN__\n";
- s << " #define SBK_EXPORT_MODULE __declspec(dllexport)\n";
- s << "#elif __GNUC__ >= 4\n";
- s << " #define SBK_EXPORT_MODULE __attribute__ ((visibility(\"default\")))\n";
- s << "#else\n";
- s << " #define SBK_EXPORT_MODULE\n";
- s << "#endif\n\n";
-
- s << "#ifdef IS_PY3K\n";
- s << "static struct PyModuleDef moduledef = {\n";
- s << " /* m_base */ PyModuleDef_HEAD_INIT,\n";
- s << " /* m_name */ \"" << moduleName() << "\",\n";
- s << " /* m_doc */ nullptr,\n";
- s << " /* m_size */ -1,\n";
- s << " /* m_methods */ " << moduleName() << "_methods,\n";
- s << " /* m_reload */ nullptr,\n";
- s << " /* m_traverse */ nullptr,\n";
- s << " /* m_clear */ nullptr,\n";
- s << " /* m_free */ nullptr\n";
- s << "};\n\n";
- s << "#endif\n\n";
-
- // PYSIDE-510: Create a signatures string for the introspection feature.
- writeSignatureStrings(s, signatureStream, moduleName(), "global functions");
-
- s << "SBK_MODULE_INIT_FUNCTION_BEGIN(" << moduleName() << ")\n";
-
- ErrorCode errorCode(QLatin1String("SBK_MODULE_INIT_ERROR"));
- // module inject-code target/beginning
- if (!snips.isEmpty()) {
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionBeginning, TypeSystem::TargetLangCode);
- s << Qt::endl;
- }
-
- for (const QString &requiredModule : requiredModules) {
- s << INDENT << "{\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << "Shiboken::AutoDecRef requiredModule(Shiboken::Module::import(\"" << requiredModule << "\"));\n";
- s << INDENT << "if (requiredModule.isNull())\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << "return SBK_MODULE_INIT_ERROR;\n";
- }
- s << INDENT << cppApiVariableName(requiredModule) << " = Shiboken::Module::getTypes(requiredModule);\n";
- s << INDENT << convertersVariableName(requiredModule) << " = Shiboken::Module::getTypeConverters(requiredModule);\n";
- }
- s << INDENT << "}\n\n";
- }
-
- int maxTypeIndex = getMaxTypeIndex() + instantiatedSmartPointers().size();
- if (maxTypeIndex) {
- s << INDENT << "// Create an array of wrapper types for the current module.\n";
- s << INDENT << "static PyTypeObject *cppApi[SBK_" << moduleName() << "_IDX_COUNT];\n";
- s << INDENT << cppApiVariableName() << " = cppApi;\n\n";
- }
-
- s << INDENT << "// Create an array of primitive type converters for the current module.\n";
- s << INDENT << "static SbkConverter *sbkConverters[SBK_" << moduleName() << "_CONVERTERS_IDX_COUNT" << "];\n";
- s << INDENT << convertersVariableName() << " = sbkConverters;\n\n";
-
- s << "#ifdef IS_PY3K\n";
- s << INDENT << "PyObject *module = Shiboken::Module::create(\"" << moduleName() << "\", &moduledef);\n";
- s << "#else\n";
- s << INDENT << "PyObject *module = Shiboken::Module::create(\"" << moduleName() << "\", ";
- s << moduleName() << "_methods);\n";
- s << "#endif\n\n";
-
- s << INDENT << "// Make module available from global scope\n";
- s << INDENT << pythonModuleObjectName() << " = module;\n\n";
-
- //s << INDENT << "// Initialize converters for primitive types.\n";
- //s << INDENT << "initConverters();\n\n";
-
- s << INDENT << "// Initialize classes in the type system\n";
- s << classPythonDefines;
-
- if (!typeConversions.isEmpty()) {
- s << Qt::endl;
- for (const CustomConversion *conversion : typeConversions) {
- writePrimitiveConverterInitialization(s, conversion);
- s << Qt::endl;
- }
- }
-
- if (!containers.isEmpty()) {
- s << Qt::endl;
- for (const AbstractMetaType *container : containers) {
- writeContainerConverterInitialization(s, container);
- s << Qt::endl;
- }
- }
-
- if (!extendedConverters.isEmpty()) {
- s << Qt::endl;
- for (ExtendedConverterData::const_iterator it = extendedConverters.cbegin(), end = extendedConverters.cend(); it != end; ++it) {
- writeExtendedConverterInitialization(s, it.key(), it.value());
- s << Qt::endl;
- }
- }
-
- writeEnumsInitialization(s, globalEnums);
-
- s << INDENT << "// Register primitive types converters.\n";
- const PrimitiveTypeEntryList &primitiveTypeList = primitiveTypes();
- for (const PrimitiveTypeEntry *pte : primitiveTypeList) {
- if (!pte->generateCode() || !pte->isCppPrimitive())
- continue;
- const TypeEntry *referencedType = pte->basicReferencedTypeEntry();
- if (!referencedType)
- continue;
- QString converter = converterObject(referencedType);
- QStringList cppSignature = pte->qualifiedCppName().split(QLatin1String("::"), Qt::SkipEmptyParts);
- while (!cppSignature.isEmpty()) {
- QString signature = cppSignature.join(QLatin1String("::"));
- s << INDENT << "Shiboken::Conversions::registerConverterName(" << converter << ", \"" << signature << "\");\n";
- cppSignature.removeFirst();
- }
- }
-
- s << Qt::endl;
- if (maxTypeIndex)
- s << INDENT << "Shiboken::Module::registerTypes(module, " << cppApiVariableName() << ");\n";
- s << INDENT << "Shiboken::Module::registerTypeConverters(module, " << convertersVariableName() << ");\n";
-
- s << Qt::endl << INDENT << "if (PyErr_Occurred()) {\n";
- {
- Indentation indentation(INDENT);
- s << INDENT << "PyErr_Print();\n";
- s << INDENT << "Py_FatalError(\"can't initialize module " << moduleName() << "\");\n";
- }
- s << INDENT << "}\n";
-
- // module inject-code target/end
- if (!snips.isEmpty()) {
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionEnd, TypeSystem::TargetLangCode);
- s << Qt::endl;
- }
-
- // module inject-code native/end
- if (!snips.isEmpty()) {
- writeCodeSnips(s, snips, TypeSystem::CodeSnipPositionEnd, TypeSystem::NativeCode);
- s << Qt::endl;
- }
-
- if (usePySideExtensions()) {
- for (AbstractMetaEnum *metaEnum : qAsConst(globalEnums))
- if (!metaEnum->isAnonymous()) {
- s << INDENT << "qRegisterMetaType< ::" << metaEnum->typeEntry()->qualifiedCppName() << " >(\"" << metaEnum->name() << "\");\n";
- }
-
- // cleanup staticMetaObject attribute
- s << INDENT << "PySide::registerCleanupFunction(cleanTypesAttributes);\n\n";
- }
-
- // finish the rest of __signature__ initialization.
- s << INDENT << "FinishSignatureInitialization(module, " << moduleName()
- << "_SignatureStrings);\n";
-
- s << Qt::endl;
- s << "SBK_MODULE_INIT_FUNCTION_END\n";
-
- return file.done() != FileOut::Failure;
-}
-
-static ArgumentOwner getArgumentOwner(const AbstractMetaFunction *func, int argIndex)
-{
- ArgumentOwner argOwner = func->argumentOwner(func->ownerClass(), argIndex);
- if (argOwner.index == ArgumentOwner::InvalidIndex)
- argOwner = func->argumentOwner(func->declaringClass(), argIndex);
- return argOwner;
-}
-
-bool CppGenerator::writeParentChildManagement(QTextStream &s, const AbstractMetaFunction *func, int argIndex, bool useHeuristicPolicy)
-{
- const int numArgs = func->arguments().count();
- bool ctorHeuristicEnabled = func->isConstructor() && useCtorHeuristic() && useHeuristicPolicy;
-
- const auto &groups = func->implementingClass()
- ? getFunctionGroups(func->implementingClass())
- : getGlobalFunctionGroups();
- bool usePyArgs = pythonFunctionWrapperUsesListOfArguments(OverloadData(groups[func->name()], this));
-
- ArgumentOwner argOwner = getArgumentOwner(func, argIndex);
- ArgumentOwner::Action action = argOwner.action;
- int parentIndex = argOwner.index;
- int childIndex = argIndex;
- if (ctorHeuristicEnabled && argIndex > 0 && numArgs) {
- AbstractMetaArgument *arg = func->arguments().at(argIndex-1);
- if (arg->name() == QLatin1String("parent") && isObjectType(arg->type())) {
- action = ArgumentOwner::Add;
- parentIndex = argIndex;
- childIndex = -1;
- }
- }
-
- QString parentVariable;
- QString childVariable;
- if (action != ArgumentOwner::Invalid) {
- if (!usePyArgs && argIndex > 1)
- qCWarning(lcShiboken).noquote().nospace()
- << "Argument index for parent tag out of bounds: " << func->signature();
-
- if (action == ArgumentOwner::Remove) {
- parentVariable = QLatin1String("Py_None");
- } else {
- if (parentIndex == 0) {
- parentVariable = QLatin1String(PYTHON_RETURN_VAR);
- } else if (parentIndex == -1) {
- parentVariable = QLatin1String("self");
- } else {
- parentVariable = usePyArgs
- ? pythonArgsAt(parentIndex - 1) : QLatin1String(PYTHON_ARG);
- }
- }
-
- if (childIndex == 0) {
- childVariable = QLatin1String(PYTHON_RETURN_VAR);
- } else if (childIndex == -1) {
- childVariable = QLatin1String("self");
- } else {
- childVariable = usePyArgs
- ? pythonArgsAt(childIndex - 1) : QLatin1String(PYTHON_ARG);
- }
-
- s << INDENT << "Shiboken::Object::setParent(" << parentVariable << ", " << childVariable << ");\n";
- return true;
- }
-
- return false;
-}
-
-void CppGenerator::writeParentChildManagement(QTextStream &s, const AbstractMetaFunction *func, bool useHeuristicForReturn)
-{
- const int numArgs = func->arguments().count();
-
- // -1 = return value
- // 0 = self
- // 1..n = func. args.
- for (int i = -1; i <= numArgs; ++i)
- writeParentChildManagement(s, func, i, useHeuristicForReturn);
-
- if (useHeuristicForReturn)
- writeReturnValueHeuristics(s, func);
-}
-
-void CppGenerator::writeReturnValueHeuristics(QTextStream &s, const AbstractMetaFunction *func)
-{
- AbstractMetaType *type = func->type();
- if (!useReturnValueHeuristic()
- || !func->ownerClass()
- || !type
- || func->isStatic()
- || func->isConstructor()
- || !func->typeReplaced(0).isEmpty()) {
- return;
- }
-
- ArgumentOwner argOwner = getArgumentOwner(func, ArgumentOwner::ReturnIndex);
- if (argOwner.action == ArgumentOwner::Invalid || argOwner.index != ArgumentOwner::ThisIndex) {
- if (isPointerToWrapperType(type))
- s << INDENT << "Shiboken::Object::setParent(self, " << PYTHON_RETURN_VAR << ");\n";
- }
-}
-
-void CppGenerator::writeHashFunction(QTextStream &s, const GeneratorContext &context)
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- const char hashType[] = "Py_hash_t";
- s << "static " << hashType << ' ' << cpythonBaseName(metaClass)
- << "_HashFunc(PyObject *self) {\n";
- writeCppSelfDefinition(s, context);
- s << INDENT << "return " << hashType << '('
- << metaClass->typeEntry()->hashFunction() << '('
- << (isObjectType(metaClass) ? "" : "*") << CPP_SELF_VAR << "));\n";
- s<< "}\n\n";
-}
-
-void CppGenerator::writeDefaultSequenceMethods(QTextStream &s, const GeneratorContext &context)
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- ErrorCode errorCode(0);
-
- // __len__
- s << "Py_ssize_t " << cpythonBaseName(metaClass->typeEntry())
- << "__len__(PyObject *self)\n{\n";
- writeCppSelfDefinition(s, context);
- s << INDENT << "return " << CPP_SELF_VAR << "->size();\n";
- s << "}\n";
-
- // __getitem__
- s << "PyObject *" << cpythonBaseName(metaClass->typeEntry())
- << "__getitem__(PyObject *self, Py_ssize_t _i)\n{\n";
- writeCppSelfDefinition(s, context);
- writeIndexError(s, QLatin1String("index out of bounds"));
-
- QString value;
- s << INDENT << metaClass->qualifiedCppName() << "::const_iterator _item = "
- << CPP_SELF_VAR << "->begin();\n"
- << INDENT << "std::advance(_item, _i);\n";
-
- const AbstractMetaTypeList instantiations = metaClass->templateBaseClassInstantiations();
- if (instantiations.isEmpty()) {
- qFatal("shiboken: %s: Internal error, no instantiations of \"%s\" were found.",
- __FUNCTION__, qPrintable(metaClass->qualifiedCppName()));
- }
- const AbstractMetaType *itemType = instantiations.constFirst();
-
- s << INDENT << "return ";
- writeToPythonConversion(s, itemType, metaClass, QLatin1String("*_item"));
- s << ";\n";
- s << "}\n";
-
- // __setitem__
- ErrorCode errorCode2(-1);
- s << "int " << cpythonBaseName(metaClass->typeEntry())
- << "__setitem__(PyObject *self, Py_ssize_t _i, PyObject *pyArg)\n{\n";
- writeCppSelfDefinition(s, context);
- writeIndexError(s, QLatin1String("list assignment index out of range"));
-
- s << INDENT << "PythonToCppFunc " << PYTHON_TO_CPP_VAR << ";\n";
- s << INDENT << "if (!";
- writeTypeCheck(s, itemType, QLatin1String("pyArg"), isNumber(itemType->typeEntry()));
- s << ") {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_TypeError, \"attributed value with wrong type, '";
- s << itemType->name() << "' or other convertible type expected\");\n";
- s << INDENT << "return -1;\n";
- }
- s << INDENT << "}\n";
- writeArgumentConversion(s, itemType, QLatin1String("cppValue"), QLatin1String("pyArg"), metaClass);
-
- s << INDENT << metaClass->qualifiedCppName() << "::iterator _item = "
- << CPP_SELF_VAR << "->begin();\n"
- << INDENT << "std::advance(_item, _i);\n"
- << INDENT << "*_item = cppValue;\n";
-
- s << INDENT << "return {};\n";
- s << "}\n";
-}
-void CppGenerator::writeIndexError(QTextStream &s, const QString &errorMsg)
-{
- s << INDENT << "if (_i < 0 || _i >= (Py_ssize_t) " << CPP_SELF_VAR << "->size()) {\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "PyErr_SetString(PyExc_IndexError, \"" << errorMsg << "\");\n";
- s << INDENT << returnStatement(m_currentErrorCode) << Qt::endl;
- }
- s << INDENT << "}\n";
-}
-
-QString CppGenerator::writeReprFunction(QTextStream &s,
- const GeneratorContext &context,
- uint indirections)
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- QString funcName = cpythonBaseName(metaClass) + QLatin1String("__repr__");
- s << "extern \"C\"\n{\n";
- s << "static PyObject *" << funcName << "(PyObject *self)\n{\n";
- writeCppSelfDefinition(s, context);
- s << INDENT << "QBuffer buffer;\n";
- s << INDENT << "buffer.open(QBuffer::ReadWrite);\n";
- s << INDENT << "QDebug dbg(&buffer);\n";
- s << INDENT << "dbg << ";
- if (metaClass->typeEntry()->isValue() || indirections == 0)
- s << '*';
- s << CPP_SELF_VAR << ";\n";
- s << INDENT << "buffer.close();\n";
- s << INDENT << "QByteArray str = buffer.data();\n";
- s << INDENT << "int idx = str.indexOf('(');\n";
- s << INDENT << "if (idx >= 0)\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "str.replace(0, idx, Py_TYPE(self)->tp_name);\n";
- }
- s << INDENT << "str = str.trimmed();\n";
- s << INDENT << "PyObject *mod = PyDict_GetItem(Py_TYPE(self)->tp_dict, Shiboken::PyMagicName::module());\n";
- // PYSIDE-595: The introduction of heap types has the side effect that the module name
- // is always prepended to the type name. Therefore the strchr check:
- s << INDENT << "if (mod && !strchr(str, '.'))\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return Shiboken::String::fromFormat(\"<%s.%s at %p>\", Shiboken::String::toCString(mod), str.constData(), self);\n";
- }
- s << INDENT << "else\n";
- {
- Indentation indent(INDENT);
- s << INDENT << "return Shiboken::String::fromFormat(\"<%s at %p>\", str.constData(), self);\n";
- }
- s << "}\n";
- s << "} // extern C\n\n";
- return funcName;
-}
diff --git a/sources/shiboken2/generator/shiboken2/cppgenerator.h b/sources/shiboken2/generator/shiboken2/cppgenerator.h
deleted file mode 100644
index 4e995d56f..000000000
--- a/sources/shiboken2/generator/shiboken2/cppgenerator.h
+++ /dev/null
@@ -1,396 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CPPGENERATOR_H
-#define CPPGENERATOR_H
-
-#include "shibokengenerator.h"
-
-/**
- * The CppGenerator generate the implementations of C++ bindings classes.
- */
-class CppGenerator : public ShibokenGenerator
-{
-public:
- CppGenerator();
-
- const char *name() const override { return "Source generator"; }
-
-protected:
- QString fileNameSuffix() const override;
- QString fileNameForContext(const GeneratorContext &context) const override;
- QVector<AbstractMetaFunctionList> filterGroupedOperatorFunctions(const AbstractMetaClass *metaClass,
- uint query);
- void generateClass(QTextStream &s, const GeneratorContext &classContext) override;
- bool finishGeneration() override;
-
-private:
- void writeInitFunc(QTextStream &declStr, QTextStream &callStr,
- const Indentor &indent, const QString &initFunctionName,
- const TypeEntry *enclosingEntry = nullptr);
- void writeCacheResetNative(QTextStream &s, const GeneratorContext &classContext);
- void writeConstructorNative(QTextStream &s, const GeneratorContext &classContext,
- const AbstractMetaFunction *func);
- void writeDestructorNative(QTextStream &s, const GeneratorContext &classContext);
-
- QString getVirtualFunctionReturnTypeName(const AbstractMetaFunction *func);
- void writeVirtualMethodNative(QTextStream &s, const AbstractMetaFunction *func, int cacheIndex);
-
- void writeMetaObjectMethod(QTextStream &s, const GeneratorContext &classContext);
- void writeMetaCast(QTextStream &s, const GeneratorContext &classContext);
-
- void writeEnumConverterFunctions(QTextStream &s, const TypeEntry *enumType);
- void writeEnumConverterFunctions(QTextStream &s, const AbstractMetaEnum *metaEnum);
- void writeConverterFunctions(QTextStream &s, const AbstractMetaClass *metaClass,
- const GeneratorContext &classContext);
- void writeCustomConverterFunctions(QTextStream &s, const CustomConversion *customConversion);
- void writeConverterRegister(QTextStream &s, const AbstractMetaClass *metaClass,
- const GeneratorContext &classContext);
- void writeCustomConverterRegister(QTextStream &s, const CustomConversion *customConversion, const QString &converterVar);
-
- void writeContainerConverterFunctions(QTextStream &s, const AbstractMetaType *containerType);
-
- void writeMethodWrapperPreamble(QTextStream &s, OverloadData &overloadData,
- const GeneratorContext &context);
- void writeConstructorWrapper(QTextStream &s, const AbstractMetaFunctionList &overloads,
- const GeneratorContext &classContext);
- void writeMethodWrapper(QTextStream &s, const AbstractMetaFunctionList &overloads,
- const GeneratorContext &classContext);
- void writeArgumentsInitializer(QTextStream &s, OverloadData &overloadData);
- void writeCppSelfConversion(QTextStream &s, const GeneratorContext &context,
- const QString &className, bool useWrapperClass);
- void writeCppSelfDefinition(QTextStream &s,
- const AbstractMetaFunction *func,
- const GeneratorContext &context,
- bool hasStaticOverload = false);
- void writeCppSelfDefinition(QTextStream &s,
- const GeneratorContext &context,
- bool hasStaticOverload = false,
- bool cppSelfAsReference = false);
-
- void writeErrorSection(QTextStream &s, OverloadData &overloadData);
- void writeFunctionReturnErrorCheckSection(QTextStream &s, bool hasReturnValue = true);
-
- /// Writes the check section for the validity of wrapped C++ objects.
- void writeInvalidPyObjectCheck(QTextStream &s, const QString &pyObj);
-
- void writeTypeCheck(QTextStream &s, const AbstractMetaType *argType, const QString &argumentName,
- bool isNumber = false, const QString &customType = QString(),
- bool rejectNull = false);
- void writeTypeCheck(QTextStream& s, const OverloadData *overloadData, QString argumentName);
-
- void writeTypeDiscoveryFunction(QTextStream &s, const AbstractMetaClass *metaClass);
-
- void writeSetattroDefinition(QTextStream &s, const AbstractMetaClass *metaClass) const;
- void writeSetattroDefaultReturn(QTextStream &s) const;
- void writeSmartPointerSetattroFunction(QTextStream &s, const GeneratorContext &context);
- void writeSetattroFunction(QTextStream &s, AttroCheck attroCheck,
- const GeneratorContext &context);
- static void writeGetattroDefinition(QTextStream &s, const AbstractMetaClass *metaClass);
- void writeSmartPointerGetattroFunction(QTextStream &s, const GeneratorContext &context);
- void writeGetattroFunction(QTextStream &s, AttroCheck attroCheck,
- const GeneratorContext &context);
- QString writeSmartPointerGetterCast();
- QString qObjectGetAttroFunction() const;
-
- /**
- * Writes Python to C++ conversions for arguments on Python wrappers.
- * If implicit conversions, and thus new object allocation, are needed,
- * code to deallocate a possible new instance is also generated.
- * \param s text stream to write
- * \param argType a pointer to the argument type to be converted
- * \param argName C++ argument name
- * \param pyArgName Python argument name
- * \param context the current meta class
- * \param defaultValue an optional default value to be used instead of the conversion result
- * \param castArgumentAsUnused if true the converted argument is cast as unused to avoid compiler warnings
- */
- void writeArgumentConversion(QTextStream &s, const AbstractMetaType *argType,
- const QString &argName, const QString &pyArgName,
- const AbstractMetaClass *context = nullptr,
- const QString &defaultValue = QString(),
- bool castArgumentAsUnused = false);
-
- /**
- * Returns the AbstractMetaType for a function argument.
- * If the argument type was modified in the type system, this method will
- * try to build a new type based on the type name defined in the type system.
- * \param func The function which owns the argument.
- * \param argPos Argument position in the function signature.
- * Note that the position 0 represents the return value, and the function
- * parameters start counting on 1.
- * \param newType It is set to true if the type returned is a new object that must be deallocated.
- * \return The type of the argument indicated by \p argPos.
- */
- const AbstractMetaType *getArgumentType(const AbstractMetaFunction *func, int argPos);
-
- void writePythonToCppTypeConversion(QTextStream &s,
- const AbstractMetaType *type,
- const QString &pyIn,
- const QString &cppOut,
- const AbstractMetaClass *context = nullptr,
- const QString &defaultValue = QString());
-
- /// Writes the conversion rule for arguments of regular and virtual methods.
- void writeConversionRule(QTextStream &s, const AbstractMetaFunction *func, TypeSystem::Language language);
- /// Writes the conversion rule for the return value of a method.
- void writeConversionRule(QTextStream &s, const AbstractMetaFunction *func, TypeSystem::Language language, const QString &outputVar);
-
- /**
- * Set the Python method wrapper return value variable to Py_None if
- * there are return types different from void in any of the other overloads
- * for the function passed as parameter.
- * \param s text stream to write
- * \param func a pointer to the function that will possibly return Py_None
- * \param thereIsReturnValue indicates if the return type of any of the other overloads
- * for this function is different from 'void'
- */
- void writeNoneReturn(QTextStream &s, const AbstractMetaFunction *func, bool thereIsReturnValue);
-
- /**
- * Writes the Python function wrapper overload decisor that selects which C++
- * method/function to call with the received Python arguments.
- * \param s text stream to write
- * \param overloadData the overload data describing all the possible overloads for the function/method
- */
- void writeOverloadedFunctionDecisor(QTextStream &s, const OverloadData &overloadData);
- /// Recursive auxiliar method to the other writeOverloadedFunctionDecisor.
- void writeOverloadedFunctionDecisorEngine(QTextStream &s, const OverloadData *parentOverloadData);
-
- /// Writes calls to all the possible method/function overloads.
- void writeFunctionCalls(QTextStream &s,
- const OverloadData &overloadData,
- const GeneratorContext &context);
-
- /// Writes the call to a single function usually from a collection of overloads.
- void writeSingleFunctionCall(QTextStream &s,
- const OverloadData &overloadData,
- const AbstractMetaFunction *func,
- const GeneratorContext &context);
-
- /// Returns the name of a C++ to Python conversion function.
- static QString cppToPythonFunctionName(const QString &sourceTypeName, QString targetTypeName = QString());
-
- /// Returns the name of a Python to C++ conversion function.
- static QString pythonToCppFunctionName(const QString &sourceTypeName, const QString &targetTypeName);
- static QString pythonToCppFunctionName(const AbstractMetaType *sourceType, const AbstractMetaType *targetType);
- static QString pythonToCppFunctionName(const CustomConversion::TargetToNativeConversion *toNative, const TypeEntry *targetType);
-
- /// Returns the name of a Python to C++ convertible check function.
- static QString convertibleToCppFunctionName(const QString &sourceTypeName, const QString &targetTypeName);
- static QString convertibleToCppFunctionName(const AbstractMetaType *sourceType, const AbstractMetaType *targetType);
- static QString convertibleToCppFunctionName(const CustomConversion::TargetToNativeConversion *toNative, const TypeEntry *targetType);
-
- /// Writes a C++ to Python conversion function.
- void writeCppToPythonFunction(QTextStream &s, const QString &code, const QString &sourceTypeName, QString targetTypeName = QString());
- void writeCppToPythonFunction(QTextStream &s, const CustomConversion *customConversion);
- void writeCppToPythonFunction(QTextStream &s, const AbstractMetaType *containerType);
-
- /// Writes a Python to C++ conversion function.
- void writePythonToCppFunction(QTextStream &s, const QString &code, const QString &sourceTypeName, const QString &targetTypeName);
-
- /// Writes a Python to C++ convertible check function.
- void writeIsPythonConvertibleToCppFunction(QTextStream &s,
- const QString &sourceTypeName,
- const QString &targetTypeName,
- const QString &condition,
- QString pythonToCppFuncName = QString(),
- bool acceptNoneAsCppNull = false);
-
- /// Writes a pair of Python to C++ conversion and check functions.
- void writePythonToCppConversionFunctions(QTextStream &s,
- const AbstractMetaType *sourceType,
- const AbstractMetaType *targetType,
- QString typeCheck = QString(),
- QString conversion = QString(),
- const QString &preConversion = QString());
- /// Writes a pair of Python to C++ conversion and check functions for implicit conversions.
- void writePythonToCppConversionFunctions(QTextStream &s,
- const CustomConversion::TargetToNativeConversion *toNative,
- const TypeEntry *targetType);
-
- /// Writes a pair of Python to C++ conversion and check functions for instantiated container types.
- void writePythonToCppConversionFunctions(QTextStream &s, const AbstractMetaType *containerType);
-
- void writeAddPythonToCppConversion(QTextStream &s, const QString &converterVar, const QString &pythonToCppFunc, const QString &isConvertibleFunc);
-
- void writeNamedArgumentResolution(QTextStream &s, const AbstractMetaFunction *func, bool usePyArgs);
-
- /// Returns a string containing the name of an argument for the given function and argument index.
- QString argumentNameFromIndex(const AbstractMetaFunction *func, int argIndex, const AbstractMetaClass **wrappedClass);
- void writeMethodCall(QTextStream &s, const AbstractMetaFunction *func,
- const GeneratorContext &context, int maxArgs = 0);
-
- QString getInitFunctionName(const GeneratorContext &context) const;
- QString getSimpleClassInitFunctionName(const AbstractMetaClass *metaClass) const;
-
- void writeSignatureStrings(QTextStream &s, QTextStream &signatureStream,
- const QString &arrayName,
- const char *comment) const;
- void writeClassRegister(QTextStream &s,
- const AbstractMetaClass *metaClass,
- const GeneratorContext &classContext,
- QTextStream &signatureStream);
- void writeClassDefinition(QTextStream &s,
- const AbstractMetaClass *metaClass,
- const GeneratorContext &classContext);
- void writeMethodDefinitionEntry(QTextStream &s, const AbstractMetaFunctionList &overloads);
- void writeMethodDefinition(QTextStream &s, const AbstractMetaFunctionList &overloads);
- void writeSignatureInfo(QTextStream &s, const AbstractMetaFunctionList &overloads);
- /// Writes the implementation of all methods part of python sequence protocol
- void writeSequenceMethods(QTextStream &s,
- const AbstractMetaClass *metaClass,
- const GeneratorContext &context);
- void writeTypeAsSequenceDefinition(QTextStream &s, const AbstractMetaClass *metaClass);
-
- /// Writes the PyMappingMethods structure for types that supports the python mapping protocol.
- void writeTypeAsMappingDefinition(QTextStream &s, const AbstractMetaClass *metaClass);
- void writeMappingMethods(QTextStream &s,
- const AbstractMetaClass *metaClass,
- const GeneratorContext &context);
-
- void writeTypeAsNumberDefinition(QTextStream &s, const AbstractMetaClass *metaClass);
-
- void writeTpTraverseFunction(QTextStream &s, const AbstractMetaClass *metaClass);
- void writeTpClearFunction(QTextStream &s, const AbstractMetaClass *metaClass);
-
- void writeCopyFunction(QTextStream &s, const GeneratorContext &context);
-
- void writeGetterFunction(QTextStream &s,
- const AbstractMetaField *metaField,
- const GeneratorContext &context);
- void writeSetterFunction(QTextStream &s,
- const AbstractMetaField *metaField,
- const GeneratorContext &context);
-
- void writeRichCompareFunction(QTextStream &s, const GeneratorContext &context);
-
- void writeEnumsInitialization(QTextStream &s, AbstractMetaEnumList &enums);
- void writeEnumInitialization(QTextStream &s, const AbstractMetaEnum *metaEnum);
-
- void writeSignalInitialization(QTextStream &s, const AbstractMetaClass *metaClass);
-
- void writeFlagsMethods(QTextStream &s, const AbstractMetaEnum *cppEnum);
- void writeFlagsToLong(QTextStream &s, const AbstractMetaEnum *cppEnum);
- void writeFlagsNonZero(QTextStream &s, const AbstractMetaEnum *cppEnum);
- void writeFlagsNumberMethodsDefinition(QTextStream &s, const AbstractMetaEnum *cppEnum);
- void writeFlagsBinaryOperator(QTextStream &s, const AbstractMetaEnum *cppEnum,
- const QString &pyOpName, const QString &cppOpName);
- void writeFlagsUnaryOperator(QTextStream &s, const AbstractMetaEnum *cppEnum,
- const QString &pyOpName, const QString &cppOpName,
- bool boolResult = false);
-
- /// Writes the function that registers the multiple inheritance information for the classes that need it.
- void writeMultipleInheritanceInitializerFunction(QTextStream &s, const AbstractMetaClass *metaClass);
- /// Writes the implementation of special cast functions, used when we need to cast a class with multiple inheritance.
- void writeSpecialCastFunction(QTextStream &s, const AbstractMetaClass *metaClass);
-
- void writePrimitiveConverterInitialization(QTextStream &s, const CustomConversion *customConversion);
- void writeEnumConverterInitialization(QTextStream &s, const TypeEntry *enumType);
- void writeEnumConverterInitialization(QTextStream &s, const AbstractMetaEnum *metaEnum);
- void writeContainerConverterInitialization(QTextStream &s, const AbstractMetaType *type);
- void writeExtendedConverterInitialization(QTextStream &s, const TypeEntry *externalType, const QVector<const AbstractMetaClass *>& conversions);
-
- void writeParentChildManagement(QTextStream &s, const AbstractMetaFunction *func, bool userHeuristicForReturn);
- bool writeParentChildManagement(QTextStream &s, const AbstractMetaFunction *func, int argIndex, bool userHeuristicPolicy);
- void writeReturnValueHeuristics(QTextStream &s, const AbstractMetaFunction *func);
- void writeInitQtMetaTypeFunctionBody(QTextStream &s, const GeneratorContext &context) const;
-
- /**
- * Returns the multiple inheritance initializer function for the given class.
- * \param metaClass the class for whom the function name must be generated.
- * \return name of the multiple inheritance information initializer function or
- * an empty string if there is no multiple inheritance in its ancestry.
- */
- QString multipleInheritanceInitializerFunctionName(const AbstractMetaClass *metaClass);
-
- /// Returns a list of all classes to which the given class could be cast.
- QStringList getAncestorMultipleInheritance(const AbstractMetaClass *metaClass);
-
- /// Returns true if the given class supports the python number protocol
- bool supportsNumberProtocol(const AbstractMetaClass *metaClass);
-
- /// Returns true if the given class supports the python sequence protocol
- bool supportsSequenceProtocol(const AbstractMetaClass *metaClass);
-
- /// Returns true if the given class supports the python mapping protocol
- bool supportsMappingProtocol(const AbstractMetaClass *metaClass);
-
- /// Returns true if generator should produce getters and setters for the given class.
- bool shouldGenerateGetSetList(const AbstractMetaClass *metaClass);
-
- void writeHashFunction(QTextStream &s, const GeneratorContext &context);
-
- /// Write default implementations for sequence protocol
- void writeDefaultSequenceMethods(QTextStream &s, const GeneratorContext &context);
- /// Helper function for writeStdListWrapperMethods.
- void writeIndexError(QTextStream &s, const QString &errorMsg);
-
- QString writeReprFunction(QTextStream &s, const GeneratorContext &context, uint indirections);
-
- const AbstractMetaFunction *boolCast(const AbstractMetaClass *metaClass) const;
- bool hasBoolCast(const AbstractMetaClass *metaClass) const
- { return boolCast(metaClass) != nullptr; }
-
- // Number protocol structure members names.
- static QHash<QString, QString> m_nbFuncs;
-
- // Maps special function names to function parameters and return types
- // used by CPython API in the sequence protocol.
- QHash<QString, QPair<QString, QString> > m_sequenceProtocol;
- // Sequence protocol structure members names.
- static QHash<QString, QString> m_sqFuncs;
-
- // Maps special function names to function parameters and return types
- // used by CPython API in the mapping protocol.
- QHash<QString, QPair<QString, QString> > m_mappingProtocol;
- // Mapping protocol structure members names.
- static QHash<QString, QString> m_mpFuncs;
-
- static QString m_currentErrorCode;
-
- /// Helper class to set and restore the current error code.
- class ErrorCode {
- public:
- explicit ErrorCode(QString errorCode) {
- m_savedErrorCode = CppGenerator::m_currentErrorCode;
- CppGenerator::m_currentErrorCode = errorCode;
- }
- explicit ErrorCode(int errorCode) {
- m_savedErrorCode = CppGenerator::m_currentErrorCode;
- CppGenerator::m_currentErrorCode = QString::number(errorCode);
- }
- ~ErrorCode() {
- CppGenerator::m_currentErrorCode = m_savedErrorCode;
- }
- private:
- QString m_savedErrorCode;
- };
-};
-
-#endif // CPPGENERATOR_H
diff --git a/sources/shiboken2/generator/shiboken2/headergenerator.cpp b/sources/shiboken2/generator/shiboken2/headergenerator.cpp
deleted file mode 100644
index 8b3fe1653..000000000
--- a/sources/shiboken2/generator/shiboken2/headergenerator.cpp
+++ /dev/null
@@ -1,652 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "headergenerator.h"
-#include <abstractmetalang.h>
-#include <typedatabase.h>
-#include <reporthandler.h>
-#include <fileout.h>
-#include "parser/codemodel.h"
-
-#include <algorithm>
-
-#include <QtCore/QDir>
-#include <QtCore/QTextStream>
-#include <QtCore/QVariant>
-#include <QtCore/QDebug>
-
-QString HeaderGenerator::fileNameSuffix() const
-{
- return QLatin1String("_wrapper.h");
-}
-
-QString HeaderGenerator::fileNameForContext(const GeneratorContext &context) const
-{
- const AbstractMetaClass *metaClass = context.metaClass();
- if (!context.forSmartPointer()) {
- QString fileNameBase = metaClass->qualifiedCppName().toLower();
- fileNameBase.replace(QLatin1String("::"), QLatin1String("_"));
- return fileNameBase + fileNameSuffix();
- }
- const AbstractMetaType *smartPointerType = context.preciseType();
- QString fileNameBase = getFileNameBaseForSmartPointer(smartPointerType, metaClass);
- return fileNameBase + fileNameSuffix();
-}
-
-void HeaderGenerator::writeCopyCtor(QTextStream &s, const AbstractMetaClass *metaClass) const
-{
- s << INDENT << wrapperName(metaClass) << "(const " << metaClass->qualifiedCppName() << "& self)";
- s << " : " << metaClass->qualifiedCppName() << "(self)\n";
- s << INDENT << "{\n";
- s << INDENT << "}\n\n";
-}
-
-void HeaderGenerator::writeProtectedFieldAccessors(QTextStream &s, const AbstractMetaField *field) const
-{
- AbstractMetaType *metaType = field->type();
- QString fieldType = metaType->cppSignature();
- QString fieldName = field->enclosingClass()->qualifiedCppName() + QLatin1String("::") + field->name();
-
- // Force use of pointer to return internal variable memory
- bool useReference = (!metaType->isConstant() &&
- !metaType->isEnum() &&
- !metaType->isPrimitive() &&
- metaType->indirections() == 0);
-
-
- // Get function
- s << INDENT << "inline " << fieldType
- << (useReference ? " *" : " ")
- << ' ' << protectedFieldGetterName(field) << "()"
- << " { return "
- << (useReference ? " &" : " ") << "this->" << fieldName << "; }\n";
-
- // Set function
- s << INDENT << "inline void " << protectedFieldSetterName(field) << '(' << fieldType << " value)"
- << " { " << fieldName << " = value; }\n";
-}
-
-void HeaderGenerator::generateClass(QTextStream &s, const GeneratorContext &classContextIn)
-{
- GeneratorContext classContext = classContextIn;
- const AbstractMetaClass *metaClass = classContext.metaClass();
- m_inheritedOverloads.clear();
- Indentation indent(INDENT);
-
- // write license comment
- s << licenseComment();
-
- QString wrapperName;
- if (!classContext.forSmartPointer()) {
- wrapperName = classContext.useWrapper()
- ? classContext.wrapperName() : metaClass->qualifiedCppName();
- } else {
- wrapperName = classContext.smartPointerWrapperName();
- }
- QString outerHeaderGuard = getFilteredCppSignatureString(wrapperName).toUpper();
- QString innerHeaderGuard;
-
- // Header
- s << "#ifndef SBK_" << outerHeaderGuard << "_H\n";
- s << "#define SBK_" << outerHeaderGuard << "_H\n\n";
-
- if (!avoidProtectedHack())
- s << "#define protected public\n\n";
-
- //Includes
- s << metaClass->typeEntry()->include() << Qt::endl;
-
- if (classContext.useWrapper() && usePySideExtensions() && metaClass->isQObject())
- s << "namespace PySide { class DynamicQMetaObject; }\n\n";
-
- while (classContext.useWrapper()) {
- if (!innerHeaderGuard.isEmpty()) {
- s << "# ifndef SBK_" << innerHeaderGuard << "_H\n";
- s << "# define SBK_" << innerHeaderGuard << "_H\n\n";
- s << "// Inherited base class:\n";
- }
-
- // Class
- s << "class " << wrapperName;
- s << " : public " << metaClass->qualifiedCppName();
-
- s << "\n{\npublic:\n";
-
- const AbstractMetaFunctionList &funcs = filterFunctions(metaClass);
- int maxOverrides = 0;
- for (AbstractMetaFunction *func : funcs) {
- if ((func->attributes() & AbstractMetaAttributes::FinalCppMethod) == 0) {
- writeFunction(s, func);
- // PYSIDE-803: Build a boolean cache for unused overrides.
- if (shouldWriteVirtualMethodNative(func))
- maxOverrides++;
- }
- }
- if (!maxOverrides)
- maxOverrides = 1;
-
- if (avoidProtectedHack() && metaClass->hasProtectedFields()) {
- const AbstractMetaFieldList &fields = metaClass->fields();
- for (AbstractMetaField *field : fields) {
- if (!field->isProtected())
- continue;
- writeProtectedFieldAccessors(s, field);
- }
- }
-
- //destructor
- // PYSIDE-504: When C++ 11 is used, then the destructor must always be written.
- // See generator.h for further reference.
- if (!avoidProtectedHack() || !metaClass->hasPrivateDestructor() || alwaysGenerateDestructor) {
- s << INDENT;
- if (avoidProtectedHack() && metaClass->hasPrivateDestructor())
- s << "// C++11: need to declare (unimplemented) destructor because "
- "the base class destructor is private.\n";
- s << '~' << wrapperName << "();\n";
- }
-
- writeClassCodeSnips(s, metaClass->typeEntry()->codeSnips(),
- TypeSystem::CodeSnipPositionDeclaration, TypeSystem::NativeCode,
- classContext);
-
- if ((!avoidProtectedHack() || !metaClass->hasPrivateDestructor())
- && usePySideExtensions() && metaClass->isQObject()) {
- s << "public:\n";
- s << INDENT << "int qt_metacall(QMetaObject::Call call, int id, void **args) override;\n";
- s << INDENT << "void *qt_metacast(const char *_clname) override;\n";
- }
-
- if (!m_inheritedOverloads.isEmpty()) {
- s << INDENT << "// Inherited overloads, because the using keyword sux\n";
- writeInheritedOverloads(s);
- m_inheritedOverloads.clear();
- }
-
- if (usePySideExtensions())
- s << INDENT << "static void pysideInitQtMetaTypes();\n";
-
- s << INDENT << "void resetPyMethodCache();\n";
- s << "private:\n";
- s << INDENT << "mutable bool m_PyMethodCache[" << maxOverrides << "];\n";
-
- s << "};\n\n";
- if (!innerHeaderGuard.isEmpty())
- s << "# endif // SBK_" << innerHeaderGuard << "_H\n\n";
-
- // PYSIDE-500: Use also includes for inherited wrapper classes, because
- // without the protected hack, we sometimes need to cast inherited wrappers.
- // But we don't use multiple include files. Instead, they are inserted as recursive
- // headers. This keeps the file structure as simple as before the enhanced inheritance.
- metaClass = metaClass->baseClass();
- if (!metaClass || !avoidProtectedHack())
- break;
- classContext = contextForClass(metaClass);
- if (!classContext.forSmartPointer()) {
- wrapperName = classContext.useWrapper()
- ? classContext.wrapperName() : metaClass->qualifiedCppName();
- } else {
- wrapperName = classContext.smartPointerWrapperName();
- }
- innerHeaderGuard = getFilteredCppSignatureString(wrapperName).toUpper();
- }
-
- s << "#endif // SBK_" << outerHeaderGuard << "_H\n\n";
-}
-
-void HeaderGenerator::writeFunction(QTextStream &s, const AbstractMetaFunction *func)
-{
-
- // do not write copy ctors here.
- if (!func->isPrivate() && func->functionType() == AbstractMetaFunction::CopyConstructorFunction) {
- writeCopyCtor(s, func->ownerClass());
- return;
- }
- if (func->isUserAdded())
- return;
-
- if (avoidProtectedHack() && func->isProtected() && !func->isConstructor() && !func->isOperatorOverload()) {
- s << INDENT << "inline " << (func->isStatic() ? "static " : "");
- s << functionSignature(func, QString(), QLatin1String("_protected"), Generator::EnumAsInts|Generator::OriginalTypeDescription)
- << " { ";
- s << (func->type() ? "return " : "");
- if (!func->isAbstract())
- s << func->ownerClass()->qualifiedCppName() << "::";
- s << func->originalName() << '(';
- QStringList args;
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- QString argName = arg->name();
- const TypeEntry *enumTypeEntry = nullptr;
- if (arg->type()->isFlags())
- enumTypeEntry = static_cast<const FlagsTypeEntry *>(arg->type()->typeEntry())->originator();
- else if (arg->type()->isEnum())
- enumTypeEntry = arg->type()->typeEntry();
- if (enumTypeEntry)
- argName = QString::fromLatin1("%1(%2)").arg(arg->type()->cppSignature(), argName);
- args << argName;
- }
- s << args.join(QLatin1String(", ")) << ')';
- s << "; }\n";
- }
-
- // pure virtual functions need a default implementation
- const bool notAbstract = !func->isAbstract();
- if ((func->isPrivate() && notAbstract && !visibilityModifiedToPrivate(func))
- || (func->isModifiedRemoved() && notAbstract))
- return;
-
- if (avoidProtectedHack() && func->ownerClass()->hasPrivateDestructor()
- && (func->isAbstract() || func->isVirtual()))
- return;
-
- if (func->isConstructor() || func->isAbstract() || func->isVirtual()) {
- s << INDENT;
- Options virtualOption = Generator::OriginalTypeDescription;
-
- const bool virtualFunc = func->isVirtual() || func->isAbstract();
- if (!virtualFunc && !func->hasSignatureModifications())
- virtualOption = Generator::NoOption;
-
- s << functionSignature(func, QString(), QString(), virtualOption);
-
- if (virtualFunc)
- s << " override";
- s << ";\n";
- // Check if this method hide other methods in base classes
- const AbstractMetaFunctionList &ownerFuncs = func->ownerClass()->functions();
- for (const AbstractMetaFunction *f : ownerFuncs) {
- if (f != func
- && !f->isConstructor()
- && !f->isPrivate()
- && !f->isVirtual()
- && !f->isAbstract()
- && !f->isStatic()
- && f->name() == func->name()) {
- m_inheritedOverloads << f;
- }
- }
-
- // TODO: when modified an abstract method ceases to be virtual but stays abstract
- //if (func->isModifiedRemoved() && func->isAbstract()) {
- //}
- }
-}
-
-static void _writeTypeIndexValue(QTextStream &s, const QString &variableName,
- int typeIndex)
-{
- s << " ";
- s.setFieldWidth(56);
- s << variableName;
- s.setFieldWidth(0);
- s << " = " << typeIndex;
-}
-
-static inline void _writeTypeIndexValueLine(QTextStream &s,
- const QString &variableName,
- int typeIndex)
-{
- _writeTypeIndexValue(s, variableName, typeIndex);
- s << ",\n";
-}
-
-void HeaderGenerator::writeTypeIndexValueLine(QTextStream &s, const TypeEntry *typeEntry)
-{
- if (!typeEntry || !typeEntry->generateCode())
- return;
- s.setFieldAlignment(QTextStream::AlignLeft);
- const int typeIndex = typeEntry->sbkIndex();
- _writeTypeIndexValueLine(s, getTypeIndexVariableName(typeEntry), typeIndex);
- if (typeEntry->isComplex()) {
- const auto *cType = static_cast<const ComplexTypeEntry *>(typeEntry);
- if (cType->baseContainerType()) {
- const AbstractMetaClass *metaClass = AbstractMetaClass::findClass(classes(), cType);
- if (metaClass->templateBaseClass())
- _writeTypeIndexValueLine(s, getTypeIndexVariableName(metaClass, true), typeIndex);
- }
- }
- if (typeEntry->isEnum()) {
- auto ete = static_cast<const EnumTypeEntry *>(typeEntry);
- if (ete->flags())
- writeTypeIndexValueLine(s, ete->flags());
- }
-}
-
-void HeaderGenerator::writeTypeIndexValueLines(QTextStream &s, const AbstractMetaClass *metaClass)
-{
- auto typeEntry = metaClass->typeEntry();
- if (!typeEntry->generateCode() || !NamespaceTypeEntry::isVisibleScope(typeEntry))
- return;
- writeTypeIndexValueLine(s, metaClass->typeEntry());
- const AbstractMetaEnumList &enums = metaClass->enums();
- for (const AbstractMetaEnum *metaEnum : enums) {
- if (metaEnum->isPrivate())
- continue;
- writeTypeIndexValueLine(s, metaEnum->typeEntry());
- }
-}
-
-// Format the typedefs for the typedef entries to be generated
-static void formatTypeDefEntries(QTextStream &s)
-{
- QVector<const TypedefEntry *> entries;
- const auto typeDbEntries = TypeDatabase::instance()->typedefEntries();
- for (auto it = typeDbEntries.cbegin(), end = typeDbEntries.cend(); it != end; ++it) {
- if (it.value()->generateCode() != 0)
- entries.append(it.value());
- }
- if (entries.isEmpty())
- return;
- s << "\n// typedef entries\n";
- for (const auto e : entries) {
- const QString name = e->qualifiedCppName();
- // Fixme: simplify by using nested namespaces in C++ 17.
- const auto components = name.splitRef(QLatin1String("::"));
- const int nameSpaceCount = components.size() - 1;
- for (int n = 0; n < nameSpaceCount; ++n)
- s << "namespace " << components.at(n) << " {\n";
- s << "using " << components.constLast() << " = " << e->sourceType() << ";\n";
- for (int n = 0; n < nameSpaceCount; ++n)
- s << "}\n";
- }
- s << '\n';
-}
-
-
-bool HeaderGenerator::finishGeneration()
-{
- // Generate the main header for this module.
- // This header should be included by binding modules
- // extendind on top of this one.
- QSet<Include> includes;
- QString macros;
- QTextStream macrosStream(&macros);
- QString sbkTypeFunctions;
- QTextStream typeFunctions(&sbkTypeFunctions);
- QString protectedEnumSurrogates;
- QTextStream protEnumsSurrogates(&protectedEnumSurrogates);
-
- Indentation indent(INDENT);
-
- macrosStream << "// Type indices\nenum : int {\n";
- AbstractMetaEnumList globalEnums = this->globalEnums();
- AbstractMetaClassList classList = classes();
-
- std::sort(classList.begin(), classList.end(), [](AbstractMetaClass *a, AbstractMetaClass *b) {
- return a->typeEntry()->sbkIndex() < b->typeEntry()->sbkIndex();
- });
-
- for (const AbstractMetaClass *metaClass : classList) {
- writeTypeIndexValueLines(macrosStream, metaClass);
- lookForEnumsInClassesNotToBeGenerated(globalEnums, metaClass);
- }
-
- for (const AbstractMetaEnum *metaEnum : qAsConst(globalEnums))
- writeTypeIndexValueLine(macrosStream, metaEnum->typeEntry());
-
- // Write the smart pointer define indexes.
- int smartPointerCountIndex = getMaxTypeIndex();
- int smartPointerCount = 0;
- const QVector<const AbstractMetaType *> &instantiatedSmartPtrs = instantiatedSmartPointers();
- for (const AbstractMetaType *metaType : instantiatedSmartPtrs) {
- QString indexName = getTypeIndexVariableName(metaType);
- _writeTypeIndexValue(macrosStream, indexName, smartPointerCountIndex);
- macrosStream << ", // " << metaType->cppSignature() << Qt::endl;
- // Add a the same value for const pointees (shared_ptr<const Foo>).
- const auto ptrName = metaType->typeEntry()->entryName();
- int pos = indexName.indexOf(ptrName, 0, Qt::CaseInsensitive);
- if (pos >= 0) {
- indexName.insert(pos + ptrName.size() + 1, QLatin1String("CONST"));
- _writeTypeIndexValue(macrosStream, indexName, smartPointerCountIndex);
- macrosStream << ", // (const)\n";
- }
- ++smartPointerCountIndex;
- ++smartPointerCount;
- }
-
- _writeTypeIndexValue(macrosStream,
- QLatin1String("SBK_") + moduleName() + QLatin1String("_IDX_COUNT"),
- getMaxTypeIndex() + smartPointerCount);
- macrosStream << "\n};\n";
-
- macrosStream << "// This variable stores all Python types exported by this module.\n";
- macrosStream << "extern PyTypeObject **" << cppApiVariableName() << ";\n\n";
- macrosStream << "// This variable stores the Python module object exported by this module.\n";
- macrosStream << "extern PyObject *" << pythonModuleObjectName() << ";\n\n";
- macrosStream << "// This variable stores all type converters exported by this module.\n";
- macrosStream << "extern SbkConverter **" << convertersVariableName() << ";\n\n";
-
- // TODO-CONVERTER ------------------------------------------------------------------------------
- // Using a counter would not do, a fix must be made to APIExtractor's getTypeIndex().
- macrosStream << "// Converter indices\nenum : int {\n";
- const PrimitiveTypeEntryList &primitives = primitiveTypes();
- int pCount = 0;
- for (const PrimitiveTypeEntry *ptype : primitives) {
- /* Note: do not generate indices for typedef'd primitive types
- * as they'll use the primitive type converters instead, so we
- * don't need to create any other.
- */
- if (!ptype->generateCode() || !ptype->customConversion())
- continue;
-
- _writeTypeIndexValueLine(macrosStream, getTypeIndexVariableName(ptype), pCount++);
- }
-
- const QVector<const AbstractMetaType *> &containers = instantiatedContainers();
- for (const AbstractMetaType *container : containers) {
- _writeTypeIndexValue(macrosStream, getTypeIndexVariableName(container), pCount);
- macrosStream << ", // " << container->cppSignature() << Qt::endl;
- pCount++;
- }
-
- // Because on win32 the compiler will not accept a zero length array.
- if (pCount == 0)
- pCount++;
- _writeTypeIndexValue(macrosStream, QStringLiteral("SBK_%1_CONVERTERS_IDX_COUNT")
- .arg(moduleName()), pCount);
- macrosStream << "\n};\n";
-
- formatTypeDefEntries(macrosStream);
-
- // TODO-CONVERTER ------------------------------------------------------------------------------
-
- macrosStream << "// Macros for type check\n";
-
- if (usePySideExtensions()) {
- typeFunctions << "QT_WARNING_PUSH\n";
- typeFunctions << "QT_WARNING_DISABLE_DEPRECATED\n";
- }
- for (const AbstractMetaEnum *cppEnum : qAsConst(globalEnums)) {
- if (cppEnum->isAnonymous() || cppEnum->isPrivate())
- continue;
- includes << cppEnum->typeEntry()->include();
- writeProtectedEnumSurrogate(protEnumsSurrogates, cppEnum);
- writeSbkTypeFunction(typeFunctions, cppEnum);
- }
-
- for (AbstractMetaClass *metaClass : classList) {
- if (!shouldGenerate(metaClass))
- continue;
-
- //Includes
- const TypeEntry *classType = metaClass->typeEntry();
- includes << classType->include();
-
- const AbstractMetaEnumList &enums = metaClass->enums();
- for (const AbstractMetaEnum *cppEnum : enums) {
- if (cppEnum->isAnonymous() || cppEnum->isPrivate())
- continue;
- EnumTypeEntry *enumType = cppEnum->typeEntry();
- includes << enumType->include();
- writeProtectedEnumSurrogate(protEnumsSurrogates, cppEnum);
- writeSbkTypeFunction(typeFunctions, cppEnum);
- }
-
- if (!metaClass->isNamespace())
- writeSbkTypeFunction(typeFunctions, metaClass);
- }
-
- for (const AbstractMetaType *metaType : instantiatedSmartPtrs) {
- const TypeEntry *classType = metaType->typeEntry();
- includes << classType->include();
- writeSbkTypeFunction(typeFunctions, metaType);
- }
- if (usePySideExtensions())
- typeFunctions << "QT_WARNING_POP\n";
-
- QString moduleHeaderFileName(outputDirectory()
- + QDir::separator() + subDirectoryForPackage(packageName())
- + QDir::separator() + getModuleHeaderFileName());
-
- QString includeShield(QLatin1String("SBK_") + moduleName().toUpper() + QLatin1String("_PYTHON_H"));
-
- FileOut file(moduleHeaderFileName);
- QTextStream &s = file.stream;
- // write license comment
- s << licenseComment() << Qt::endl << Qt::endl;
-
- s << "#ifndef " << includeShield << Qt::endl;
- s << "#define " << includeShield << Qt::endl << Qt::endl;
- if (!avoidProtectedHack()) {
- s << "//workaround to access protected functions\n";
- s << "#define protected public\n\n";
- }
-
- s << "#include <sbkpython.h>\n";
- s << "#include <sbkconverter.h>\n";
-
- QStringList requiredTargetImports = TypeDatabase::instance()->requiredTargetImports();
- if (!requiredTargetImports.isEmpty()) {
- s << "// Module Includes\n";
- for (const QString &requiredModule : qAsConst(requiredTargetImports))
- s << "#include <" << getModuleHeaderFileName(requiredModule) << ">\n";
- s << Qt::endl;
- }
-
- s << "// Bound library includes\n";
- for (const Include &include : qAsConst(includes))
- s << include;
-
- if (!primitiveTypes().isEmpty()) {
- s << "// Conversion Includes - Primitive Types\n";
- const PrimitiveTypeEntryList &primitiveTypeList = primitiveTypes();
- for (const PrimitiveTypeEntry *ptype : primitiveTypeList)
- s << ptype->include();
- s << Qt::endl;
- }
-
- if (!containerTypes().isEmpty()) {
- s << "// Conversion Includes - Container Types\n";
- const ContainerTypeEntryList &containerTypeList = containerTypes();
- for (const ContainerTypeEntry *ctype : containerTypeList)
- s << ctype->include();
- s << Qt::endl;
- }
-
- s << macros << Qt::endl;
-
- if (!protectedEnumSurrogates.isEmpty()) {
- s << "// Protected enum surrogates\n";
- s << protectedEnumSurrogates << Qt::endl;
- }
-
- s << "namespace Shiboken\n{\n\n";
-
- s << "// PyType functions, to get the PyObjectType for a type T\n";
- s << sbkTypeFunctions << Qt::endl;
-
- s << "} // namespace Shiboken\n\n";
-
- s << "#endif // " << includeShield << Qt::endl << Qt::endl;
-
- return file.done() != FileOut::Failure;
-}
-
-void HeaderGenerator::writeProtectedEnumSurrogate(QTextStream &s, const AbstractMetaEnum *cppEnum)
-{
- if (avoidProtectedHack() && cppEnum->isProtected())
- s << "enum " << protectedEnumSurrogateName(cppEnum) << " {};\n";
-}
-
-void HeaderGenerator::writeSbkTypeFunction(QTextStream &s, const AbstractMetaEnum *cppEnum)
-{
- QString enumName;
- if (avoidProtectedHack() && cppEnum->isProtected()) {
- enumName = protectedEnumSurrogateName(cppEnum);
- } else {
- enumName = cppEnum->name();
- if (cppEnum->enclosingClass())
- enumName = cppEnum->enclosingClass()->qualifiedCppName() + QLatin1String("::") + enumName;
- }
-
- s << "template<> inline PyTypeObject *SbkType< ::" << enumName << " >() ";
- s << "{ return " << cpythonTypeNameExt(cppEnum->typeEntry()) << "; }\n";
-
- FlagsTypeEntry *flag = cppEnum->typeEntry()->flags();
- if (flag) {
- s << "template<> inline PyTypeObject *SbkType< ::" << flag->name() << " >() "
- << "{ return " << cpythonTypeNameExt(flag) << "; }\n";
- }
-}
-
-void HeaderGenerator::writeSbkTypeFunction(QTextStream &s, const AbstractMetaClass *cppClass)
-{
- s << "template<> inline PyTypeObject *SbkType< ::" << cppClass->qualifiedCppName() << " >() "
- << "{ return reinterpret_cast<PyTypeObject *>(" << cpythonTypeNameExt(cppClass->typeEntry()) << "); }\n";
-}
-
-void HeaderGenerator::writeSbkTypeFunction(QTextStream &s, const AbstractMetaType *metaType)
-{
- s << "template<> inline PyTypeObject *SbkType< ::" << metaType->cppSignature() << " >() "
- << "{ return reinterpret_cast<PyTypeObject *>(" << cpythonTypeNameExt(metaType) << "); }\n";
-}
-
-void HeaderGenerator::writeInheritedOverloads(QTextStream &s)
-{
- for (const AbstractMetaFunction *func : qAsConst(m_inheritedOverloads)) {
- s << INDENT << "inline ";
- s << functionSignature(func, QString(), QString(), Generator::EnumAsInts|Generator::OriginalTypeDescription) << " { ";
- s << (func->type() ? "return " : "");
- s << func->ownerClass()->qualifiedCppName() << "::" << func->originalName() << '(';
- QStringList args;
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- QString argName = arg->name();
- const TypeEntry *enumTypeEntry = nullptr;
- if (arg->type()->isFlags())
- enumTypeEntry = static_cast<const FlagsTypeEntry *>(arg->type()->typeEntry())->originator();
- else if (arg->type()->isEnum())
- enumTypeEntry = arg->type()->typeEntry();
- if (enumTypeEntry)
- argName = arg->type()->cppSignature() + QLatin1Char('(') + argName + QLatin1Char(')');
- args << argName;
- }
- s << args.join(QLatin1String(", ")) << ')';
- s << "; }\n";
- }
-}
diff --git a/sources/shiboken2/generator/shiboken2/headergenerator.h b/sources/shiboken2/generator/shiboken2/headergenerator.h
deleted file mode 100644
index 30ce06636..000000000
--- a/sources/shiboken2/generator/shiboken2/headergenerator.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef HEADERGENERATOR_H
-#define HEADERGENERATOR_H
-
-#include "shibokengenerator.h"
-
-#include <QtCore/QSet>
-
-class AbstractMetaFunction;
-
-/**
- * The HeaderGenerator generate the declarations of C++ bindings classes.
- */
-class HeaderGenerator : public ShibokenGenerator
-{
-public:
- OptionDescriptions options() const override { return OptionDescriptions(); }
-
- const char *name() const override { return "Header generator"; }
-
-protected:
- QString fileNameSuffix() const override;
- QString fileNameForContext(const GeneratorContext &context) const override;
- void generateClass(QTextStream &s, const GeneratorContext &classContext) override;
- bool finishGeneration() override;
-
-private:
- void writeCopyCtor(QTextStream &s, const AbstractMetaClass *metaClass) const;
- void writeProtectedFieldAccessors(QTextStream &s, const AbstractMetaField *field) const;
- void writeFunction(QTextStream &s, const AbstractMetaFunction *func);
- void writeSbkTypeFunction(QTextStream &s, const AbstractMetaEnum *cppEnum);
- void writeSbkTypeFunction(QTextStream &s, const AbstractMetaClass *cppClass);
- void writeSbkTypeFunction(QTextStream &s, const AbstractMetaType *metaType);
- void writeTypeIndexValueLine(QTextStream &s, const TypeEntry *typeEntry);
- void writeTypeIndexValueLines(QTextStream &s, const AbstractMetaClass *metaClass);
- void writeProtectedEnumSurrogate(QTextStream &s, const AbstractMetaEnum *cppEnum);
- void writeInheritedOverloads(QTextStream &s);
-
- QSet<const AbstractMetaFunction *> m_inheritedOverloads;
-};
-
-#endif // HEADERGENERATOR_H
-
diff --git a/sources/shiboken2/generator/shiboken2/overloaddata.cpp b/sources/shiboken2/generator/shiboken2/overloaddata.cpp
deleted file mode 100644
index bd39e9444..000000000
--- a/sources/shiboken2/generator/shiboken2/overloaddata.cpp
+++ /dev/null
@@ -1,1091 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <abstractmetalang.h>
-#include <reporthandler.h>
-#include <graph.h>
-#include "overloaddata.h"
-#include "indentor.h"
-#include "shibokengenerator.h"
-
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QTemporaryFile>
-
-static const TypeEntry *getReferencedTypeEntry(const TypeEntry *typeEntry)
-{
- if (typeEntry->isPrimitive()) {
- auto pte = dynamic_cast<const PrimitiveTypeEntry *>(typeEntry);
- while (pte->referencedTypeEntry())
- pte = pte->referencedTypeEntry();
- typeEntry = pte;
- }
- return typeEntry;
-}
-
-static QString getTypeName(const AbstractMetaType *type)
-{
- const TypeEntry *typeEntry = getReferencedTypeEntry(type->typeEntry());
- QString typeName = typeEntry->name();
- if (typeEntry->isContainer()) {
- QStringList types;
- const AbstractMetaTypeList &instantiations = type->instantiations();
- for (const AbstractMetaType *cType : instantiations) {
- const TypeEntry *typeEntry = getReferencedTypeEntry(cType->typeEntry());
- types << typeEntry->name();
- }
- typeName += QLatin1Char('<') + types.join(QLatin1Char(',')) + QLatin1String(" >");
- }
- return typeName;
-}
-
-static QString getTypeName(const OverloadData *ov)
-{
- return ov->hasArgumentTypeReplace() ? ov->argumentTypeReplaced() : getTypeName(ov->argType());
-}
-
-static bool typesAreEqual(const AbstractMetaType *typeA, const AbstractMetaType *typeB)
-{
- if (typeA->typeEntry() == typeB->typeEntry()) {
- if (typeA->isContainer() || typeA->isSmartPointer()) {
- if (typeA->instantiations().size() != typeB->instantiations().size())
- return false;
-
- for (int i = 0; i < typeA->instantiations().size(); ++i) {
- if (!typesAreEqual(typeA->instantiations().at(i), typeB->instantiations().at(i)))
- return false;
- }
- return true;
- }
-
- return !(ShibokenGenerator::isCString(typeA) ^ ShibokenGenerator::isCString(typeB));
- }
- return false;
-}
-
-
-/**
- * OverloadSortData just helps writing clearer code in the
- * OverloadData::sortNextOverloads method.
- */
-struct OverloadSortData
-{
- /**
- * Adds a typeName into the type map without associating it with
- * a OverloadData. This is done to express type dependencies that could
- * or could not appear in overloaded signatures not processed yet.
- */
- void mapType(const QString &typeName)
- {
- if (map.contains(typeName))
- return;
- map[typeName] = counter;
- if (!reverseMap.contains(counter))
- reverseMap[counter] = nullptr;
- counter++;
- }
-
- void mapType(OverloadData *overloadData)
- {
- QString typeName = getTypeName(overloadData);
- map[typeName] = counter;
- reverseMap[counter] = overloadData;
- counter++;
- }
-
- int lastProcessedItemId() { return counter - 1; }
-
- int counter = 0;
- QHash<QString, int> map; // typeName -> id
- QHash<int, OverloadData *> reverseMap; // id -> OverloadData;
-};
-
-/**
- * Helper function that returns the name of a container get from containerType argument and
- * an instantiation taken either from an implicit conversion expressed by the function argument,
- * or from the string argument implicitConvTypeName.
- */
-static QString getImplicitConversionTypeName(const AbstractMetaType *containerType,
- const AbstractMetaType *instantiation,
- const AbstractMetaFunction *function,
- const QString &implicitConvTypeName = QString())
-{
- QString impConv;
- if (!implicitConvTypeName.isEmpty())
- impConv = implicitConvTypeName;
- else if (function->isConversionOperator())
- impConv = function->ownerClass()->typeEntry()->name();
- else
- impConv = getTypeName(function->arguments().constFirst()->type());
-
- QStringList types;
- const AbstractMetaTypeList &instantiations = containerType->instantiations();
- for (const AbstractMetaType *otherType : instantiations)
- types << (otherType == instantiation ? impConv : getTypeName(otherType));
-
- return containerType->typeEntry()->qualifiedCppName() + QLatin1Char('<')
- + types.join(QLatin1String(", ")) + QLatin1String(" >");
-}
-
-// overloaddata.cpp
-static QString msgCyclicDependency(const QString &funcName, const QString &graphName,
- const OverloadData::MetaFunctionList &involvedConversions)
-{
- QString result;
- QTextStream str(&result);
- str << "Cyclic dependency found on overloaddata for \"" << funcName
- << "\" method! The graph boy saved the graph at \"" << QDir::toNativeSeparators(graphName)
- << "\".";
- if (const int count = involvedConversions.size()) {
- str << " Implicit conversions (" << count << "): ";
- for (int i = 0; i < count; ++i) {
- if (i)
- str << ", \"";
- str << involvedConversions.at(i)->signature() << '"';
- if (const AbstractMetaClass *c = involvedConversions.at(i)->implementingClass())
- str << '(' << c->name() << ')';
- }
- }
- return result;
-}
-
-/**
- * Topologically sort the overloads by implicit convertion order
- *
- * This avoids using an implicit conversion if there's an explicit
- * overload for the convertible type. So, if there's an implicit convert
- * like TargetType(ConvertibleType foo) and both are in the overload list,
- * ConvertibleType is checked before TargetType.
- *
- * Side effects: Modifies m_nextOverloadData
- */
-void OverloadData::sortNextOverloads()
-{
- OverloadSortData sortData;
- bool checkPyObject = false;
- int pyobjectIndex = 0;
- bool checkPySequence = false;
- int pySeqIndex = 0;
- bool checkQString = false;
- int qstringIndex = 0;
- bool checkQVariant = false;
- int qvariantIndex = 0;
- bool checkPyBuffer = false;
- int pyBufferIndex = 0;
-
- // Primitive types that are not int, long, short,
- // char and their respective unsigned counterparts.
- QStringList nonIntegerPrimitives;
- nonIntegerPrimitives << QLatin1String("float") << QLatin1String("double")
- << QLatin1String("bool");
-
- // Signed integer primitive types.
- QStringList signedIntegerPrimitives;
- signedIntegerPrimitives << QLatin1String("int") << QLatin1String("short")
- << QLatin1String("long");
-
- // sort the children overloads
- for (OverloadData *ov : qAsConst(m_nextOverloadData))
- ov->sortNextOverloads();
-
- if (m_nextOverloadData.size() <= 1)
- return;
-
- // Populates the OverloadSortData object containing map and reverseMap, to map type names to ids,
- // these ids will be used by the topological sort algorithm, because is easier and faster to work
- // with graph sorting using integers.
- for (OverloadData *ov : qAsConst(m_nextOverloadData)) {
- sortData.mapType(ov);
-
- const QString typeName(getTypeName(ov));
-
- if (!checkPyObject && typeName.contains(QLatin1String("PyObject"))) {
- checkPyObject = true;
- pyobjectIndex = sortData.lastProcessedItemId();
- } else if (!checkPySequence && typeName == QLatin1String("PySequence")) {
- checkPySequence = true;
- pySeqIndex = sortData.lastProcessedItemId();
- } else if (!checkPyBuffer && typeName == QLatin1String("PyBuffer")) {
- checkPyBuffer = true;
- pyBufferIndex = sortData.lastProcessedItemId();
- } else if (!checkQVariant && typeName == QLatin1String("QVariant")) {
- checkQVariant = true;
- qvariantIndex = sortData.lastProcessedItemId();
- } else if (!checkQString && typeName == QLatin1String("QString")) {
- checkQString = true;
- qstringIndex = sortData.lastProcessedItemId();
- }
-
- const AbstractMetaTypeList &instantiations = ov->argType()->instantiations();
- for (const AbstractMetaType *instantiation : instantiations) {
- // Add dependencies for type instantiation of container.
- QString typeName = getTypeName(instantiation);
- sortData.mapType(typeName);
-
- // Build dependency for implicit conversion types instantiations for base container.
- // For example, considering signatures "method(list<PointF>)" and "method(list<Point>)",
- // and being PointF implicitly convertible from Point, an list<T> instantiation with T
- // as Point must come before the PointF instantiation, or else list<Point> will never
- // be called. In the case of primitive types, list<double> must come before list<int>.
- if (instantiation->isPrimitive() && (signedIntegerPrimitives.contains(instantiation->name()))) {
- for (const QString &primitive : qAsConst(nonIntegerPrimitives))
- sortData.mapType(getImplicitConversionTypeName(ov->argType(), instantiation, nullptr, primitive));
- } else {
- const AbstractMetaFunctionList &funcs = m_generator->implicitConversions(instantiation);
- for (const AbstractMetaFunction *function : funcs)
- sortData.mapType(getImplicitConversionTypeName(ov->argType(), instantiation, function));
- }
- }
- }
-
-
- // Create the graph of type dependencies based on implicit conversions.
- Graph graph(sortData.reverseMap.count());
- // All C++ primitive types, add any forgotten type AT THE END OF THIS LIST!
- const char *primitiveTypes[] = {"int",
- "unsigned int",
- "long",
- "unsigned long",
- "short",
- "unsigned short",
- "bool",
- "unsigned char",
- "char",
- "float",
- "double",
- "const char*"
- };
- const int numPrimitives = sizeof(primitiveTypes)/sizeof(const char *);
- bool hasPrimitive[numPrimitives];
- for (int i = 0; i < numPrimitives; ++i)
- hasPrimitive[i] = sortData.map.contains(QLatin1String(primitiveTypes[i]));
-
- if (checkPySequence && checkPyObject)
- graph.addEdge(pySeqIndex, pyobjectIndex);
-
- QStringList classesWithIntegerImplicitConversion;
-
- MetaFunctionList involvedConversions;
-
- for (OverloadData *ov : qAsConst(m_nextOverloadData)) {
- const AbstractMetaType *targetType = ov->argType();
- const QString targetTypeEntryName(getTypeName(ov));
- int targetTypeId = sortData.map[targetTypeEntryName];
-
- // Process implicit conversions
- const AbstractMetaFunctionList &functions = m_generator->implicitConversions(targetType);
- for (AbstractMetaFunction *function : functions) {
- QString convertibleType;
- if (function->isConversionOperator())
- convertibleType = function->ownerClass()->typeEntry()->name();
- else
- convertibleType = getTypeName(function->arguments().constFirst()->type());
-
- if (convertibleType == QLatin1String("int") || convertibleType == QLatin1String("unsigned int"))
- classesWithIntegerImplicitConversion << targetTypeEntryName;
-
- if (!sortData.map.contains(convertibleType))
- continue;
-
- int convertibleTypeId = sortData.map[convertibleType];
-
- // If a reverse pair already exists, remove it. Probably due to the
- // container check (This happened to QVariant and QHash)
- graph.removeEdge(targetTypeId, convertibleTypeId);
- graph.addEdge(convertibleTypeId, targetTypeId);
- involvedConversions.append(function);
- }
-
- // Process inheritance relationships
- if (targetType->isValue() || targetType->isObject()) {
- const AbstractMetaClass *metaClass = AbstractMetaClass::findClass(m_generator->classes(), targetType->typeEntry());
- const AbstractMetaClassList &ancestors = m_generator->getAllAncestors(metaClass);
- for (const AbstractMetaClass *ancestor : ancestors) {
- QString ancestorTypeName = ancestor->typeEntry()->name();
- if (!sortData.map.contains(ancestorTypeName))
- continue;
- int ancestorTypeId = sortData.map[ancestorTypeName];
- graph.removeEdge(ancestorTypeId, targetTypeId);
- graph.addEdge(targetTypeId, ancestorTypeId);
- }
- }
-
- // Process template instantiations
- const AbstractMetaTypeList &instantiations = targetType->instantiations();
- for (const AbstractMetaType *instantiation : instantiations) {
- if (sortData.map.contains(getTypeName(instantiation))) {
- int convertible = sortData.map[getTypeName(instantiation)];
-
- if (!graph.containsEdge(targetTypeId, convertible)) // Avoid cyclic dependency.
- graph.addEdge(convertible, targetTypeId);
-
- if (instantiation->isPrimitive() && (signedIntegerPrimitives.contains(instantiation->name()))) {
- for (const QString &primitive : qAsConst(nonIntegerPrimitives)) {
- QString convertibleTypeName = getImplicitConversionTypeName(ov->argType(), instantiation, nullptr, primitive);
- if (!graph.containsEdge(targetTypeId, sortData.map[convertibleTypeName])) // Avoid cyclic dependency.
- graph.addEdge(sortData.map[convertibleTypeName], targetTypeId);
- }
-
- } else {
- const AbstractMetaFunctionList &funcs = m_generator->implicitConversions(instantiation);
- for (const AbstractMetaFunction *function : funcs) {
- QString convertibleTypeName = getImplicitConversionTypeName(ov->argType(), instantiation, function);
- if (!graph.containsEdge(targetTypeId, sortData.map[convertibleTypeName])) { // Avoid cyclic dependency.
- graph.addEdge(sortData.map[convertibleTypeName], targetTypeId);
- involvedConversions.append(function);
- }
- }
- }
- }
- }
-
-
- if ((checkPySequence || checkPyObject || checkPyBuffer)
- && !targetTypeEntryName.contains(QLatin1String("PyObject"))
- && !targetTypeEntryName.contains(QLatin1String("PyBuffer"))
- && !targetTypeEntryName.contains(QLatin1String("PySequence"))) {
- if (checkPySequence) {
- // PySequence will be checked after all more specific types, but before PyObject.
- graph.addEdge(targetTypeId, pySeqIndex);
- } else if (checkPyBuffer) {
- // PySequence will be checked after all more specific types, but before PyObject.
- graph.addEdge(targetTypeId, pyBufferIndex);
- } else {
- // Add dependency on PyObject, so its check is the last one (too generic).
- graph.addEdge(targetTypeId, pyobjectIndex);
- }
- } else if (checkQVariant && targetTypeEntryName != QLatin1String("QVariant")) {
- if (!graph.containsEdge(qvariantIndex, targetTypeId)) // Avoid cyclic dependency.
- graph.addEdge(targetTypeId, qvariantIndex);
- } else if (checkQString && ShibokenGenerator::isPointer(ov->argType())
- && targetTypeEntryName != QLatin1String("QString")
- && targetTypeEntryName != QLatin1String("QByteArray")
- && (!checkPyObject || targetTypeId != pyobjectIndex)) {
- if (!graph.containsEdge(qstringIndex, targetTypeId)) // Avoid cyclic dependency.
- graph.addEdge(targetTypeId, qstringIndex);
- }
-
- if (targetType->isEnum()) {
- // Enum values must precede primitive types.
- for (int i = 0; i < numPrimitives; ++i) {
- if (hasPrimitive[i])
- graph.addEdge(targetTypeId, sortData.map[QLatin1String(primitiveTypes[i])]);
- }
- }
- }
-
- // QByteArray args need to be checked after QString args
- if (sortData.map.contains(QLatin1String("QString")) && sortData.map.contains(QLatin1String("QByteArray")))
- graph.addEdge(sortData.map[QLatin1String("QString")], sortData.map[QLatin1String("QByteArray")]);
-
- for (OverloadData *ov : qAsConst(m_nextOverloadData)) {
- const AbstractMetaType *targetType = ov->argType();
- if (!targetType->isEnum())
- continue;
-
- QString targetTypeEntryName = getTypeName(targetType);
- // Enum values must precede types implicitly convertible from "int" or "unsigned int".
- for (const QString &implicitFromInt : qAsConst(classesWithIntegerImplicitConversion))
- graph.addEdge(sortData.map[targetTypeEntryName], sortData.map[implicitFromInt]);
- }
-
-
- // Special case for double(int i) (not tracked by m_generator->implicitConversions
- for (const QString &signedIntegerName : qAsConst(signedIntegerPrimitives)) {
- if (sortData.map.contains(signedIntegerName)) {
- for (const QString &nonIntegerName : qAsConst(nonIntegerPrimitives)) {
- if (sortData.map.contains(nonIntegerName))
- graph.addEdge(sortData.map[nonIntegerName], sortData.map[signedIntegerName]);
- }
- }
- }
-
- // sort the overloads topologically based on the dependency graph.
- const auto unmappedResult = graph.topologicalSort();
- if (unmappedResult.isEmpty()) {
- QString funcName = referenceFunction()->name();
- if (referenceFunction()->ownerClass())
- funcName.prepend(referenceFunction()->ownerClass()->name() + QLatin1Char('.'));
-
- // Dump overload graph
- QString graphName = QDir::tempPath() + QLatin1Char('/') + funcName + QLatin1String(".dot");
- QHash<int, QString> nodeNames;
- for (auto it = sortData.map.cbegin(), end = sortData.map.cend(); it != end; ++it)
- nodeNames.insert(it.value(), it.key());
- graph.dumpDot(nodeNames, graphName);
- qCWarning(lcShiboken).noquote() << qPrintable(msgCyclicDependency(funcName, graphName, involvedConversions));
- }
-
- m_nextOverloadData.clear();
- for (int i : unmappedResult) {
- if (!sortData.reverseMap[i])
- continue;
- m_nextOverloadData << sortData.reverseMap[i];
- }
-}
-
-/**
- * Root constructor for OverloadData
- *
- * This constructor receives the list of overloads for a given function and iterates generating
- * the graph of OverloadData instances. Each OverloadData instance references an argument/type
- * combination.
- *
- * Example:
- * addStuff(double, PyObject *)
- * addStuff(double, int)
- *
- * Given these two overloads, there will be the following graph:
- *
- * addStuff - double - PyObject *
- * \- int
- *
- */
-OverloadData::OverloadData(const AbstractMetaFunctionList &overloads, const ShibokenGenerator *generator)
- : m_minArgs(256), m_maxArgs(0), m_argPos(-1), m_argType(nullptr),
- m_headOverloadData(this), m_previousOverloadData(nullptr), m_generator(generator)
-{
- for (const AbstractMetaFunction *func : overloads) {
- m_overloads.append(func);
- int argSize = func->arguments().size() - numberOfRemovedArguments(func);
- if (m_minArgs > argSize)
- m_minArgs = argSize;
- else if (m_maxArgs < argSize)
- m_maxArgs = argSize;
- OverloadData *currentOverloadData = this;
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- if (func->argumentRemoved(arg->argumentIndex() + 1))
- continue;
- currentOverloadData = currentOverloadData->addOverloadData(func, arg);
- }
- }
-
- // Sort the overload possibilities so that the overload decisor code goes for the most
- // important cases first, based on the topological order of the implicit conversions
- sortNextOverloads();
-
- // Fix minArgs
- if (minArgs() > maxArgs())
- m_headOverloadData->m_minArgs = maxArgs();
-}
-
-OverloadData::OverloadData(OverloadData *headOverloadData, const AbstractMetaFunction *func,
- const AbstractMetaType *argType, int argPos)
- : m_minArgs(256), m_maxArgs(0), m_argPos(argPos), m_argType(argType),
- m_headOverloadData(headOverloadData), m_previousOverloadData(nullptr),
- m_generator(nullptr)
-{
- if (func)
- this->addOverload(func);
-}
-
-void OverloadData::addOverload(const AbstractMetaFunction *func)
-{
- int origNumArgs = func->arguments().size();
- int removed = numberOfRemovedArguments(func);
- int numArgs = origNumArgs - removed;
-
- if (numArgs > m_headOverloadData->m_maxArgs)
- m_headOverloadData->m_maxArgs = numArgs;
-
- if (numArgs < m_headOverloadData->m_minArgs)
- m_headOverloadData->m_minArgs = numArgs;
-
- for (int i = 0; m_headOverloadData->m_minArgs > 0 && i < origNumArgs; i++) {
- if (func->argumentRemoved(i + 1))
- continue;
- if (func->arguments().at(i)->hasDefaultValueExpression()) {
- int fixedArgIndex = i - removed;
- if (fixedArgIndex < m_headOverloadData->m_minArgs)
- m_headOverloadData->m_minArgs = fixedArgIndex;
- }
- }
-
- m_overloads.append(func);
-}
-
-OverloadData *OverloadData::addOverloadData(const AbstractMetaFunction *func,
- const AbstractMetaArgument *arg)
-{
- const AbstractMetaType *argType = arg->type();
- OverloadData *overloadData = nullptr;
- if (!func->isOperatorOverload()) {
- for (OverloadData *tmp : qAsConst(m_nextOverloadData)) {
- // TODO: 'const char *', 'char *' and 'char' will have the same TypeEntry?
-
- // If an argument have a type replacement, then we should create a new overloaddata
- // for it, unless the next argument also have a identical type replacement.
- QString replacedArg = func->typeReplaced(tmp->m_argPos + 1);
- bool argsReplaced = !replacedArg.isEmpty() || !tmp->m_argTypeReplaced.isEmpty();
- if ((!argsReplaced && typesAreEqual(tmp->m_argType, argType))
- || (argsReplaced && replacedArg == tmp->argumentTypeReplaced())) {
- tmp->addOverload(func);
- overloadData = tmp;
- }
- }
- }
-
- if (!overloadData) {
- overloadData = new OverloadData(m_headOverloadData, func, argType, m_argPos + 1);
- overloadData->m_previousOverloadData = this;
- overloadData->m_generator = this->m_generator;
- QString typeReplaced = func->typeReplaced(arg->argumentIndex() + 1);
-
- if (!typeReplaced.isEmpty())
- overloadData->m_argTypeReplaced = typeReplaced;
- m_nextOverloadData.append(overloadData);
- }
-
- return overloadData;
-}
-
-QStringList OverloadData::returnTypes() const
-{
- QSet<QString> retTypes;
- for (const AbstractMetaFunction *func : m_overloads) {
- if (!func->typeReplaced(0).isEmpty())
- retTypes << func->typeReplaced(0);
- else if (func->type() && !func->argumentRemoved(0))
- retTypes << func->type()->cppSignature();
- else
- retTypes << QLatin1String("void");
- }
- return retTypes.values();
-}
-
-bool OverloadData::hasNonVoidReturnType() const
-{
- QStringList retTypes = returnTypes();
- return !retTypes.contains(QLatin1String("void")) || retTypes.size() > 1;
-}
-
-bool OverloadData::hasVarargs() const
-{
- for (const AbstractMetaFunction *func : m_overloads) {
- AbstractMetaArgumentList args = func->arguments();
- if (args.size() > 1 && args.constLast()->type()->isVarargs())
- return true;
- }
- return false;
-}
-
-bool OverloadData::hasAllowThread() const
-{
- for (const AbstractMetaFunction *func : m_overloads) {
- if (func->allowThread())
- return true;
- }
- return false;
-}
-
-bool OverloadData::hasStaticFunction(const AbstractMetaFunctionList &overloads)
-{
- for (const AbstractMetaFunction *func : qAsConst(overloads)) {
- if (func->isStatic())
- return true;
- }
- return false;
-}
-
-bool OverloadData::hasStaticFunction() const
-{
- for (const AbstractMetaFunction *func : m_overloads) {
- if (func->isStatic())
- return true;
- }
- return false;
-}
-
-bool OverloadData::hasInstanceFunction(const AbstractMetaFunctionList &overloads)
-{
- for (const AbstractMetaFunction *func : qAsConst(overloads)) {
- if (!func->isStatic())
- return true;
- }
- return false;
-}
-
-bool OverloadData::hasInstanceFunction() const
-{
- for (const AbstractMetaFunction *func : m_overloads) {
- if (!func->isStatic())
- return true;
- }
- return false;
-}
-
-bool OverloadData::hasStaticAndInstanceFunctions(const AbstractMetaFunctionList &overloads)
-{
- return OverloadData::hasStaticFunction(overloads) && OverloadData::hasInstanceFunction(overloads);
-}
-
-bool OverloadData::hasStaticAndInstanceFunctions() const
-{
- return OverloadData::hasStaticFunction() && OverloadData::hasInstanceFunction();
-}
-
-const AbstractMetaFunction *OverloadData::referenceFunction() const
-{
- return m_overloads.constFirst();
-}
-
-const AbstractMetaArgument *OverloadData::argument(const AbstractMetaFunction *func) const
-{
- if (isHeadOverloadData() || !m_overloads.contains(func))
- return nullptr;
-
- int argPos = 0;
- int removed = 0;
- for (int i = 0; argPos <= m_argPos; i++) {
- if (func->argumentRemoved(i + 1))
- removed++;
- else
- argPos++;
- }
-
- return func->arguments().at(m_argPos + removed);
-}
-
-OverloadDataList OverloadData::overloadDataOnPosition(OverloadData *overloadData, int argPos) const
-{
- OverloadDataList overloadDataList;
- if (overloadData->argPos() == argPos) {
- overloadDataList.append(overloadData);
- } else if (overloadData->argPos() < argPos) {
- const OverloadDataList &data = overloadData->nextOverloadData();
- for (OverloadData *pd : data)
- overloadDataList += overloadDataOnPosition(pd, argPos);
- }
- return overloadDataList;
-}
-
-OverloadDataList OverloadData::overloadDataOnPosition(int argPos) const
-{
- OverloadDataList overloadDataList;
- overloadDataList += overloadDataOnPosition(m_headOverloadData, argPos);
- return overloadDataList;
-}
-
-bool OverloadData::nextArgumentHasDefaultValue() const
-{
- for (OverloadData *overloadData : m_nextOverloadData) {
- if (overloadData->getFunctionWithDefaultValue())
- return true;
- }
- return false;
-}
-
-static OverloadData *_findNextArgWithDefault(OverloadData *overloadData)
-{
- if (overloadData->getFunctionWithDefaultValue())
- return overloadData;
-
- OverloadData *result = nullptr;
- const OverloadDataList &data = overloadData->nextOverloadData();
- for (OverloadData *odata : data) {
- OverloadData *tmp = _findNextArgWithDefault(odata);
- if (!result || (tmp && result->argPos() > tmp->argPos()))
- result = tmp;
- }
- return result;
-}
-
-OverloadData *OverloadData::findNextArgWithDefault()
-{
- return _findNextArgWithDefault(this);
-}
-
-bool OverloadData::isFinalOccurrence(const AbstractMetaFunction *func) const
-{
- for (const OverloadData *pd : m_nextOverloadData) {
- if (pd->overloads().contains(func))
- return false;
- }
- return true;
-}
-
-OverloadData::MetaFunctionList OverloadData::overloadsWithoutRepetition() const
-{
- MetaFunctionList overloads = m_overloads;
- for (const AbstractMetaFunction *func : m_overloads) {
- if (func->minimalSignature().endsWith(QLatin1String("const")))
- continue;
- for (const AbstractMetaFunction *f : qAsConst(overloads)) {
- if ((func->minimalSignature() + QLatin1String("const")) == f->minimalSignature()) {
- overloads.removeOne(f);
- break;
- }
- }
- }
- return overloads;
-}
-
-const AbstractMetaFunction *OverloadData::getFunctionWithDefaultValue() const
-{
- for (const AbstractMetaFunction *func : m_overloads) {
- int removedArgs = 0;
- for (int i = 0; i <= m_argPos + removedArgs; i++) {
- if (func->argumentRemoved(i + 1))
- removedArgs++;
- }
- if (func->arguments().at(m_argPos + removedArgs)->hasDefaultValueExpression())
- return func;
- }
- return nullptr;
-}
-
-QVector<int> OverloadData::invalidArgumentLengths() const
-{
- QSet<int> validArgLengths;
-
- for (const AbstractMetaFunction *func : qAsConst(m_headOverloadData->m_overloads)) {
- const AbstractMetaArgumentList args = func->arguments();
- int offset = 0;
- for (int i = 0; i < args.size(); ++i) {
- if (func->argumentRemoved(i+1)) {
- offset++;
- } else {
- if (args.at(i)->hasDefaultValueExpression())
- validArgLengths << i-offset;
- }
- }
- validArgLengths << args.size() - offset;
- }
-
- QVector<int> invalidArgLengths;
- for (int i = minArgs() + 1; i < maxArgs(); i++) {
- if (!validArgLengths.contains(i))
- invalidArgLengths.append(i);
- }
-
- return invalidArgLengths;
-}
-
-int OverloadData::numberOfRemovedArguments(const AbstractMetaFunction *func, int finalArgPos)
-{
- int removed = 0;
- if (finalArgPos < 0) {
- for (int i = 0; i < func->arguments().size(); i++) {
- if (func->argumentRemoved(i + 1))
- removed++;
- }
- } else {
- for (int i = 0; i < finalArgPos + removed; i++) {
- if (func->argumentRemoved(i + 1))
- removed++;
- }
- }
- return removed;
-}
-
-QPair<int, int> OverloadData::getMinMaxArguments(const AbstractMetaFunctionList &overloads)
-{
- int minArgs = 10000;
- int maxArgs = 0;
- for (const AbstractMetaFunction *func : overloads) {
- int origNumArgs = func->arguments().size();
- int removed = numberOfRemovedArguments(func);
- int numArgs = origNumArgs - removed;
- if (maxArgs < numArgs)
- maxArgs = numArgs;
- if (minArgs > numArgs)
- minArgs = numArgs;
- for (int j = 0; j < origNumArgs; j++) {
- if (func->argumentRemoved(j + 1))
- continue;
- int fixedArgIndex = j - removed;
- if (fixedArgIndex < minArgs && func->arguments().at(j)->hasDefaultValueExpression())
- minArgs = fixedArgIndex;
- }
- }
- return {minArgs, maxArgs};
-}
-
-bool OverloadData::isSingleArgument(const AbstractMetaFunctionList &overloads)
-{
- bool singleArgument = true;
- for (const AbstractMetaFunction *func : overloads) {
- if (func->arguments().size() - numberOfRemovedArguments(func) != 1) {
- singleArgument = false;
- break;
- }
- }
- return singleArgument;
-}
-
-void OverloadData::dumpGraph(const QString &filename) const
-{
- QFile file(filename);
- if (file.open(QFile::WriteOnly)) {
- QTextStream s(&file);
- s << m_headOverloadData->dumpGraph();
- }
-}
-
-static inline QString toHtml(QString s)
-{
- s.replace(QLatin1Char('<'), QLatin1String("&lt;"));
- s.replace(QLatin1Char('>'), QLatin1String("&gt;"));
- s.replace(QLatin1Char('&'), QLatin1String("&amp;"));
- return s;
-}
-
-QString OverloadData::dumpGraph() const
-{
- Indentor INDENT;
- Indentation indent(INDENT);
- QString result;
- QTextStream s(&result);
- if (m_argPos == -1) {
- const AbstractMetaFunction *rfunc = referenceFunction();
- s << "digraph OverloadedFunction {\n";
- s << INDENT << "graph [fontsize=12 fontname=freemono labelloc=t splines=true overlap=false rankdir=LR];\n";
-
- // Shows all function signatures
- s << "legend [fontsize=9 fontname=freemono shape=rect label=\"";
- for (const AbstractMetaFunction *func : m_overloads) {
- s << "f" << functionNumber(func) << " : ";
- if (func->type())
- s << toHtml(func->type()->cppSignature());
- else
- s << "void";
- s << ' ' << toHtml(func->minimalSignature()) << "\\l";
- }
- s << "\"];\n";
-
- // Function box title
- s << INDENT << '"' << rfunc->name() << "\" [shape=plaintext style=\"filled,bold\" margin=0 fontname=freemono fillcolor=white penwidth=1 ";
- s << "label=<<table border=\"0\" cellborder=\"0\" cellpadding=\"3\" bgcolor=\"white\">";
- s << "<tr><td bgcolor=\"black\" align=\"center\" cellpadding=\"6\" colspan=\"2\"><font color=\"white\">";
- if (rfunc->ownerClass())
- s << rfunc->ownerClass()->name() << "::";
- s << toHtml(rfunc->name()) << "</font>";
- if (rfunc->isVirtual()) {
- s << "<br/><font color=\"white\" point-size=\"10\">&lt;&lt;";
- if (rfunc->isAbstract())
- s << "pure ";
- s << "virtual&gt;&gt;</font>";
- }
- s << "</td></tr>";
-
- // Function return type
- s << "<tr><td bgcolor=\"gray\" align=\"right\">original type</td><td bgcolor=\"gray\" align=\"left\">";
- if (rfunc->type())
- s << toHtml(rfunc->type()->cppSignature());
- else
- s << "void";
- s << "</td></tr>";
-
- // Shows type changes for all function signatures
- for (const AbstractMetaFunction *func : m_overloads) {
- if (func->typeReplaced(0).isEmpty())
- continue;
- s << "<tr><td bgcolor=\"gray\" align=\"right\">f" << functionNumber(func);
- s << "-type</td><td bgcolor=\"gray\" align=\"left\">";
- s << toHtml(func->typeReplaced(0)) << "</td></tr>";
- }
-
- // Minimum and maximum number of arguments
- s << "<tr><td bgcolor=\"gray\" align=\"right\">minArgs</td><td bgcolor=\"gray\" align=\"left\">";
- s << minArgs() << "</td></tr>";
- s << "<tr><td bgcolor=\"gray\" align=\"right\">maxArgs</td><td bgcolor=\"gray\" align=\"left\">";
- s << maxArgs() << "</td></tr>";
-
- if (rfunc->ownerClass()) {
- if (rfunc->implementingClass() != rfunc->ownerClass())
- s << "<tr><td align=\"right\">implementor</td><td align=\"left\">" << rfunc->implementingClass()->name() << "</td></tr>";
- if (rfunc->declaringClass() != rfunc->ownerClass() && rfunc->declaringClass() != rfunc->implementingClass())
- s << "<tr><td align=\"right\">declarator</td><td align=\"left\">" << rfunc->declaringClass()->name() << "</td></tr>";
- }
-
- // Overloads for the signature to present point
- s << "<tr><td bgcolor=\"gray\" align=\"right\">overloads</td><td bgcolor=\"gray\" align=\"left\">";
- for (const AbstractMetaFunction *func : m_overloads)
- s << 'f' << functionNumber(func) << ' ';
- s << "</td></tr>";
-
- s << "</table>> ];\n";
-
- for (const OverloadData *pd : m_nextOverloadData)
- s << INDENT << '"' << rfunc->name() << "\" -> " << pd->dumpGraph();
-
- s << "}\n";
- } else {
- QString argId = QLatin1String("arg_") + QString::number(quintptr(this));
- s << argId << ";\n";
-
- s << INDENT << '"' << argId << "\" [shape=\"plaintext\" style=\"filled,bold\" margin=\"0\" fontname=\"freemono\" fillcolor=\"white\" penwidth=1 ";
- s << "label=<<table border=\"0\" cellborder=\"0\" cellpadding=\"3\" bgcolor=\"white\">";
-
- // Argument box title
- s << "<tr><td bgcolor=\"black\" align=\"left\" cellpadding=\"2\" colspan=\"2\">";
- s << "<font color=\"white\" point-size=\"11\">arg #" << argPos() << "</font></td></tr>";
-
- // Argument type information
- QString type = hasArgumentTypeReplace() ? argumentTypeReplaced() : argType()->cppSignature();
- s << "<tr><td bgcolor=\"gray\" align=\"right\">type</td><td bgcolor=\"gray\" align=\"left\">";
- s << toHtml(type) << "</td></tr>";
- if (hasArgumentTypeReplace()) {
- s << "<tr><td bgcolor=\"gray\" align=\"right\">orig. type</td><td bgcolor=\"gray\" align=\"left\">";
- s << toHtml(argType()->cppSignature()) << "</td></tr>";
- }
-
- // Overloads for the signature to present point
- s << "<tr><td bgcolor=\"gray\" align=\"right\">overloads</td><td bgcolor=\"gray\" align=\"left\">";
- for (const AbstractMetaFunction *func : m_overloads)
- s << 'f' << functionNumber(func) << ' ';
- s << "</td></tr>";
-
- // Show default values (original and modified) for various functions
- for (const AbstractMetaFunction *func : m_overloads) {
- const AbstractMetaArgument *arg = argument(func);
- if (!arg)
- continue;
- QString argDefault = arg->defaultValueExpression();
- if (!argDefault.isEmpty() ||
- argDefault != arg->originalDefaultValueExpression()) {
- s << "<tr><td bgcolor=\"gray\" align=\"right\">f" << functionNumber(func);
- s << "-default</td><td bgcolor=\"gray\" align=\"left\">";
- s << argDefault << "</td></tr>";
- }
- if (argDefault != arg->originalDefaultValueExpression()) {
- s << "<tr><td bgcolor=\"gray\" align=\"right\">f" << functionNumber(func);
- s << "-orig-default</td><td bgcolor=\"gray\" align=\"left\">";
- s << arg->originalDefaultValueExpression() << "</td></tr>";
- }
- }
-
- s << "</table>>];\n";
-
- for (const OverloadData *pd : m_nextOverloadData)
- s << INDENT << argId << " -> " << pd->dumpGraph();
- }
- return result;
-}
-
-int OverloadData::functionNumber(const AbstractMetaFunction *func) const
-{
- return m_headOverloadData->m_overloads.indexOf(func);
-}
-
-OverloadData::~OverloadData()
-{
- while (!m_nextOverloadData.isEmpty())
- delete m_nextOverloadData.takeLast();
-}
-
-bool OverloadData::hasArgumentTypeReplace() const
-{
- return !m_argTypeReplaced.isEmpty();
-}
-
-QString OverloadData::argumentTypeReplaced() const
-{
- return m_argTypeReplaced;
-}
-
-bool OverloadData::hasArgumentWithDefaultValue(const AbstractMetaFunctionList &overloads)
-{
- if (OverloadData::getMinMaxArguments(overloads).second == 0)
- return false;
- for (const AbstractMetaFunction *func : overloads) {
- if (hasArgumentWithDefaultValue(func))
- return true;
- }
- return false;
-}
-
-bool OverloadData::hasArgumentWithDefaultValue() const
-{
- if (maxArgs() == 0)
- return false;
- for (const AbstractMetaFunction *func : m_overloads) {
- if (hasArgumentWithDefaultValue(func))
- return true;
- }
- return false;
-}
-
-bool OverloadData::hasArgumentWithDefaultValue(const AbstractMetaFunction *func)
-{
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- if (func->argumentRemoved(arg->argumentIndex() + 1))
- continue;
- if (arg->hasDefaultValueExpression())
- return true;
- }
- return false;
-}
-
-AbstractMetaArgumentList OverloadData::getArgumentsWithDefaultValues(const AbstractMetaFunction *func)
-{
- AbstractMetaArgumentList args;
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (AbstractMetaArgument *arg : arguments) {
- if (!arg->hasDefaultValueExpression()
- || func->argumentRemoved(arg->argumentIndex() + 1))
- continue;
- args << arg;
- }
- return args;
-}
-
-#ifndef QT_NO_DEBUG_STREAM
-void OverloadData::formatDebug(QDebug &d) const
-{
- const int count = m_overloads.size();
- d << "argType=" << m_argType << ", minArgs=" << m_minArgs << ", maxArgs=" << m_maxArgs
- << ", argPos=" << m_argPos << ", argTypeReplaced=\"" << m_argTypeReplaced
- << "\", overloads[" << count << "]=(";
- const int oldVerbosity = d.verbosity();
- d.setVerbosity(3);
- for (int i = 0; i < count; ++i) {
- if (i)
- d << '\n';
- d << m_overloads.at(i);
- }
- d << ')';
- d.setVerbosity(oldVerbosity);
-}
-
-QDebug operator<<(QDebug d, const OverloadData *od)
-{
- QDebugStateSaver saver(d);
- d.noquote();
- d.nospace();
- d << "OverloadData(";
- if (od)
- od->formatDebug(d);
- else
- d << '0';
- d << ')';
- return d;
-}
-#endif // !QT_NO_DEBUG_STREAM
diff --git a/sources/shiboken2/generator/shiboken2/overloaddata.h b/sources/shiboken2/generator/shiboken2/overloaddata.h
deleted file mode 100644
index 4fd4199e5..000000000
--- a/sources/shiboken2/generator/shiboken2/overloaddata.h
+++ /dev/null
@@ -1,163 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OVERLOADDATA_H
-#define OVERLOADDATA_H
-
-#include <abstractmetalang_typedefs.h>
-#include <QtCore/QBitArray>
-#include <QtCore/QVector>
-
-QT_FORWARD_DECLARE_CLASS(QDebug)
-
-class ShibokenGenerator;
-
-class OverloadData;
-using OverloadDataList = QVector<OverloadData *>;
-
-class OverloadData
-{
-public:
- using MetaFunctionList = QVector<const AbstractMetaFunction *>;
-
- OverloadData(const AbstractMetaFunctionList &overloads, const ShibokenGenerator *generator);
- ~OverloadData();
-
- int minArgs() const { return m_headOverloadData->m_minArgs; }
- int maxArgs() const { return m_headOverloadData->m_maxArgs; }
- int argPos() const { return m_argPos; }
-
- const AbstractMetaType *argType() const { return m_argType; }
-
- /// Returns a string list containing all the possible return types (including void) for the current OverloadData.
- QStringList returnTypes() const;
-
- /// Returns true if any of the overloads for the current OverloadData has a return type different from void.
- bool hasNonVoidReturnType() const;
-
- /// Returns true if any of the overloads for the current OverloadData has a varargs argument.
- bool hasVarargs() const;
-
- /// Returns true if any of the overloads for the current OverloadData allows threads when called.
- bool hasAllowThread() const;
-
- /// Returns true if any of the overloads for the current OverloadData is static.
- bool hasStaticFunction() const;
-
- /// Returns true if any of the overloads passed as argument is static.
- static bool hasStaticFunction(const AbstractMetaFunctionList &overloads);
-
- /// Returns true if any of the overloads for the current OverloadData is not static.
- bool hasInstanceFunction() const;
-
- /// Returns true if any of the overloads passed as argument is not static.
- static bool hasInstanceFunction(const AbstractMetaFunctionList &overloads);
-
- /// Returns true if among the overloads for the current OverloadData there are static and non-static methods altogether.
- bool hasStaticAndInstanceFunctions() const;
-
- /// Returns true if among the overloads passed as argument there are static and non-static methods altogether.
- static bool hasStaticAndInstanceFunctions(const AbstractMetaFunctionList &overloads);
-
- const AbstractMetaFunction *referenceFunction() const;
- const AbstractMetaArgument *argument(const AbstractMetaFunction *func) const;
- OverloadDataList overloadDataOnPosition(int argPos) const;
-
- bool isHeadOverloadData() const { return this == m_headOverloadData; }
-
- /// Returns the root OverloadData object that represents all the overloads.
- OverloadData *headOverloadData() const { return m_headOverloadData; }
-
- /// Returns the function that has a default value at the current OverloadData argument position, otherwise returns null.
- const AbstractMetaFunction *getFunctionWithDefaultValue() const;
-
- bool nextArgumentHasDefaultValue() const;
- /// Returns the nearest occurrence, including this instance, of an argument with a default value.
- OverloadData *findNextArgWithDefault();
- bool isFinalOccurrence(const AbstractMetaFunction *func) const;
-
- /// Returns the list of overloads removing repeated constant functions (ex.: "foo()" and "foo()const", the second is removed).
- MetaFunctionList overloadsWithoutRepetition() const;
- const MetaFunctionList &overloads() const { return m_overloads; }
- OverloadDataList nextOverloadData() const { return m_nextOverloadData; }
- OverloadData *previousOverloadData() const { return m_previousOverloadData; }
-
- QVector<int> invalidArgumentLengths() const;
-
- static int numberOfRemovedArguments(const AbstractMetaFunction *func, int finalArgPos = -1);
- static QPair<int, int> getMinMaxArguments(const AbstractMetaFunctionList &overloads);
- /// Returns true if all overloads have no more than one argument.
- static bool isSingleArgument(const AbstractMetaFunctionList &overloads);
-
- void dumpGraph(const QString &filename) const;
- QString dumpGraph() const;
-
- bool hasArgumentTypeReplace() const;
- QString argumentTypeReplaced() const;
-
- bool hasArgumentWithDefaultValue() const;
- static bool hasArgumentWithDefaultValue(const AbstractMetaFunctionList &overloads);
- static bool hasArgumentWithDefaultValue(const AbstractMetaFunction *func);
-
- /// Returns a list of function arguments which have default values and were not removed.
- static AbstractMetaArgumentList getArgumentsWithDefaultValues(const AbstractMetaFunction *func);
-
-#ifndef QT_NO_DEBUG_STREAM
- void formatDebug(QDebug &) const;
-#endif
-
-private:
- OverloadData(OverloadData *headOverloadData, const AbstractMetaFunction *func,
- const AbstractMetaType *argType, int argPos);
-
- void addOverload(const AbstractMetaFunction *func);
- OverloadData *addOverloadData(const AbstractMetaFunction *func, const AbstractMetaArgument *arg);
-
- void sortNextOverloads();
-
- int functionNumber(const AbstractMetaFunction *func) const;
- OverloadDataList overloadDataOnPosition(OverloadData *overloadData, int argPos) const;
-
- int m_minArgs;
- int m_maxArgs;
- int m_argPos;
- const AbstractMetaType *m_argType;
- QString m_argTypeReplaced;
- MetaFunctionList m_overloads;
-
- OverloadData *m_headOverloadData;
- OverloadDataList m_nextOverloadData;
- OverloadData *m_previousOverloadData;
- const ShibokenGenerator *m_generator;
-};
-
-#ifndef QT_NO_DEBUG_STREAM
-QDebug operator<<(QDebug, const OverloadData *);
-#endif
-
-#endif // OVERLOADDATA_H
diff --git a/sources/shiboken2/generator/shiboken2/shibokengenerator.cpp b/sources/shiboken2/generator/shiboken2/shibokengenerator.cpp
deleted file mode 100644
index 0e8809e97..000000000
--- a/sources/shiboken2/generator/shiboken2/shibokengenerator.cpp
+++ /dev/null
@@ -1,2855 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "shibokengenerator.h"
-#include <abstractmetalang.h>
-#include <messages.h>
-#include "overloaddata.h"
-#include <reporthandler.h>
-#include <typedatabase.h>
-#include <abstractmetabuilder.h>
-#include <iostream>
-
-#include <QtCore/QDir>
-#include <QtCore/QDebug>
-#include <QtCore/QRegularExpression>
-#include <limits>
-#include <memory>
-
-static const char AVOID_PROTECTED_HACK[] = "avoid-protected-hack";
-static const char PARENT_CTOR_HEURISTIC[] = "enable-parent-ctor-heuristic";
-static const char RETURN_VALUE_HEURISTIC[] = "enable-return-value-heuristic";
-static const char ENABLE_PYSIDE_EXTENSIONS[] = "enable-pyside-extensions";
-static const char DISABLE_VERBOSE_ERROR_MESSAGES[] = "disable-verbose-error-messages";
-static const char USE_ISNULL_AS_NB_NONZERO[] = "use-isnull-as-nb_nonzero";
-static const char WRAPPER_DIAGNOSTICS[] = "wrapper-diagnostics";
-
-const char *CPP_ARG = "cppArg";
-const char *CPP_ARG_REMOVED = "removed_cppArg";
-const char *CPP_RETURN_VAR = "cppResult";
-const char *CPP_SELF_VAR = "cppSelf";
-const char *NULL_PTR = "nullptr";
-const char *PYTHON_ARG = "pyArg";
-const char *PYTHON_ARGS = "pyArgs";
-const char *PYTHON_OVERRIDE_VAR = "pyOverride";
-const char *PYTHON_RETURN_VAR = "pyResult";
-const char *PYTHON_TO_CPP_VAR = "pythonToCpp";
-const char *SMART_POINTER_GETTER = "kSmartPointerGetter";
-
-const char *CONV_RULE_OUT_VAR_SUFFIX = "_out";
-const char *BEGIN_ALLOW_THREADS =
- "PyThreadState *_save = PyEval_SaveThread(); // Py_BEGIN_ALLOW_THREADS";
-const char *END_ALLOW_THREADS = "PyEval_RestoreThread(_save); // Py_END_ALLOW_THREADS";
-
-//static void dumpFunction(AbstractMetaFunctionList lst);
-
-QHash<QString, QString> ShibokenGenerator::m_pythonPrimitiveTypeName = QHash<QString, QString>();
-QHash<QString, QString> ShibokenGenerator::m_pythonOperators = QHash<QString, QString>();
-QHash<QString, QString> ShibokenGenerator::m_formatUnits = QHash<QString, QString>();
-QHash<QString, QString> ShibokenGenerator::m_tpFuncs = QHash<QString, QString>();
-QStringList ShibokenGenerator::m_knownPythonTypes = QStringList();
-
-static QRegularExpression placeHolderRegex(int index)
-{
- return QRegularExpression(QLatin1Char('%') + QString::number(index) + QStringLiteral("\\b"));
-}
-
-// Return a prefix to fully qualify value, eg:
-// resolveScopePrefix("Class::NestedClass::Enum::Value1", "Enum::Value1")
-// -> "Class::NestedClass::")
-static QString resolveScopePrefix(const QStringList &scopeList, const QString &value)
-{
- QString name;
- for (int i = scopeList.size() - 1 ; i >= 0; --i) {
- const QString prefix = scopeList.at(i) + QLatin1String("::");
- if (value.startsWith(prefix))
- name.clear();
- else
- name.prepend(prefix);
- }
- return name;
-}
-
-static inline QStringList splitClassScope(const AbstractMetaClass *scope)
-{
- return scope->qualifiedCppName().split(QLatin1String("::"), Qt::SkipEmptyParts);
-}
-
-static QString resolveScopePrefix(const AbstractMetaClass *scope, const QString &value)
-{
- return scope
- ? resolveScopePrefix(splitClassScope(scope), value)
- : QString();
-}
-
-static QString resolveScopePrefix(const AbstractMetaEnum *metaEnum,
- const QString &value)
-{
- QStringList parts;
- if (const AbstractMetaClass *scope = metaEnum->enclosingClass())
- parts.append(splitClassScope(scope));
- // Fully qualify the value which is required for C++ 11 enum classes.
- if (!metaEnum->isAnonymous())
- parts.append(metaEnum->name());
- return resolveScopePrefix(parts, value);
-}
-
-struct GeneratorClassInfoCacheEntry
-{
- ShibokenGenerator::FunctionGroups functionGroups;
- bool needsGetattroFunction = false;
-};
-
-using GeneratorClassInfoCache = QHash<const AbstractMetaClass *, GeneratorClassInfoCacheEntry>;
-
-Q_GLOBAL_STATIC(GeneratorClassInfoCache, generatorClassInfoCache)
-
-ShibokenGenerator::ShibokenGenerator()
-{
- if (m_pythonPrimitiveTypeName.isEmpty())
- ShibokenGenerator::initPrimitiveTypesCorrespondences();
-
- if (m_tpFuncs.isEmpty())
- ShibokenGenerator::clearTpFuncs();
-
- if (m_knownPythonTypes.isEmpty())
- ShibokenGenerator::initKnownPythonTypes();
-
- m_metaTypeFromStringCache = AbstractMetaTypeCache();
-
- m_typeSystemConvName[TypeSystemCheckFunction] = QLatin1String("checkType");
- m_typeSystemConvName[TypeSystemIsConvertibleFunction] = QLatin1String("isConvertible");
- m_typeSystemConvName[TypeSystemToCppFunction] = QLatin1String("toCpp");
- m_typeSystemConvName[TypeSystemToPythonFunction] = QLatin1String("toPython");
-
- const char CHECKTYPE_REGEX[] = R"(%CHECKTYPE\[([^\[]*)\]\()";
- const char ISCONVERTIBLE_REGEX[] = R"(%ISCONVERTIBLE\[([^\[]*)\]\()";
- const char CONVERTTOPYTHON_REGEX[] = R"(%CONVERTTOPYTHON\[([^\[]*)\]\()";
- // Capture a '*' leading the variable name into the target
- // so that "*valuePtr = %CONVERTTOCPP..." works as expected.
- const char CONVERTTOCPP_REGEX[] =
- R"((\*?%?[a-zA-Z_][\w\.]*(?:\[[^\[^<^>]+\])*)(?:\s+)=(?:\s+)%CONVERTTOCPP\[([^\[]*)\]\()";
- m_typeSystemConvRegEx[TypeSystemCheckFunction] = QRegularExpression(QLatin1String(CHECKTYPE_REGEX));
- m_typeSystemConvRegEx[TypeSystemIsConvertibleFunction] = QRegularExpression(QLatin1String(ISCONVERTIBLE_REGEX));
- m_typeSystemConvRegEx[TypeSystemToPythonFunction] = QRegularExpression(QLatin1String(CONVERTTOPYTHON_REGEX));
- m_typeSystemConvRegEx[TypeSystemToCppFunction] = QRegularExpression(QLatin1String(CONVERTTOCPP_REGEX));
-}
-
-ShibokenGenerator::~ShibokenGenerator() = default;
-
-void ShibokenGenerator::clearTpFuncs()
-{
- m_tpFuncs.insert(QLatin1String("__str__"), QString());
- m_tpFuncs.insert(QLatin1String("__repr__"), QString());
- m_tpFuncs.insert(QLatin1String("__iter__"), QString());
- m_tpFuncs.insert(QLatin1String("__next__"), QString());
-}
-
-void ShibokenGenerator::initPrimitiveTypesCorrespondences()
-{
- // Python primitive types names
- m_pythonPrimitiveTypeName.clear();
-
- // PyBool
- m_pythonPrimitiveTypeName.insert(QLatin1String("bool"), QLatin1String("PyBool"));
-
- const char *charTypes[] = {
- "char", "signed char", "unsigned char"
- };
- for (const char *charType : charTypes)
- m_pythonPrimitiveTypeName.insert(QLatin1String(charType), QStringLiteral("SbkChar"));
-
- // PyInt
- const char *intTypes[] = {
- "int", "signed int", "uint", "unsigned int",
- "short", "ushort", "signed short", "signed short int",
- "unsigned short", "unsigned short", "unsigned short int",
- "long"
- };
- for (const char *intType : intTypes)
- m_pythonPrimitiveTypeName.insert(QLatin1String(intType), QStringLiteral("PyInt"));
-
- // PyFloat
- m_pythonPrimitiveTypeName.insert(QLatin1String("double"), QLatin1String("PyFloat"));
- m_pythonPrimitiveTypeName.insert(QLatin1String("float"), QLatin1String("PyFloat"));
-
- // PyLong
- const char *longTypes[] = {
- "unsigned long", "signed long", "ulong", "unsigned long int",
- "long long", "__int64",
- "unsigned long long", "unsigned __int64", "size_t"
- };
- for (const char *longType : longTypes)
- m_pythonPrimitiveTypeName.insert(QLatin1String(longType), QStringLiteral("PyLong"));
-
- // Python operators
- m_pythonOperators.clear();
-
- // call operator
- m_pythonOperators.insert(QLatin1String("operator()"), QLatin1String("call"));
-
- // Arithmetic operators
- m_pythonOperators.insert(QLatin1String("operator+"), QLatin1String("add"));
- m_pythonOperators.insert(QLatin1String("operator-"), QLatin1String("sub"));
- m_pythonOperators.insert(QLatin1String("operator*"), QLatin1String("mul"));
- m_pythonOperators.insert(QLatin1String("operator/"), QLatin1String("div"));
- m_pythonOperators.insert(QLatin1String("operator%"), QLatin1String("mod"));
-
- // Inplace arithmetic operators
- m_pythonOperators.insert(QLatin1String("operator+="), QLatin1String("iadd"));
- m_pythonOperators.insert(QLatin1String("operator-="), QLatin1String("isub"));
- m_pythonOperators.insert(QLatin1String("operator++"), QLatin1String("iadd"));
- m_pythonOperators.insert(QLatin1String("operator--"), QLatin1String("isub"));
- m_pythonOperators.insert(QLatin1String("operator*="), QLatin1String("imul"));
- m_pythonOperators.insert(QLatin1String("operator/="), QLatin1String("idiv"));
- m_pythonOperators.insert(QLatin1String("operator%="), QLatin1String("imod"));
-
- // Bitwise operators
- m_pythonOperators.insert(QLatin1String("operator&"), QLatin1String("and"));
- m_pythonOperators.insert(QLatin1String("operator^"), QLatin1String("xor"));
- m_pythonOperators.insert(QLatin1String("operator|"), QLatin1String("or"));
- m_pythonOperators.insert(QLatin1String("operator<<"), QLatin1String("lshift"));
- m_pythonOperators.insert(QLatin1String("operator>>"), QLatin1String("rshift"));
- m_pythonOperators.insert(QLatin1String("operator~"), QLatin1String("invert"));
-
- // Inplace bitwise operators
- m_pythonOperators.insert(QLatin1String("operator&="), QLatin1String("iand"));
- m_pythonOperators.insert(QLatin1String("operator^="), QLatin1String("ixor"));
- m_pythonOperators.insert(QLatin1String("operator|="), QLatin1String("ior"));
- m_pythonOperators.insert(QLatin1String("operator<<="), QLatin1String("ilshift"));
- m_pythonOperators.insert(QLatin1String("operator>>="), QLatin1String("irshift"));
-
- // Comparison operators
- m_pythonOperators.insert(QLatin1String("operator=="), QLatin1String("eq"));
- m_pythonOperators.insert(QLatin1String("operator!="), QLatin1String("ne"));
- m_pythonOperators.insert(QLatin1String("operator<"), QLatin1String("lt"));
- m_pythonOperators.insert(QLatin1String("operator>"), QLatin1String("gt"));
- m_pythonOperators.insert(QLatin1String("operator<="), QLatin1String("le"));
- m_pythonOperators.insert(QLatin1String("operator>="), QLatin1String("ge"));
-
- // Initialize format units for C++->Python->C++ conversion
- m_formatUnits.clear();
- m_formatUnits.insert(QLatin1String("char"), QLatin1String("b"));
- m_formatUnits.insert(QLatin1String("unsigned char"), QLatin1String("B"));
- m_formatUnits.insert(QLatin1String("int"), QLatin1String("i"));
- m_formatUnits.insert(QLatin1String("unsigned int"), QLatin1String("I"));
- m_formatUnits.insert(QLatin1String("short"), QLatin1String("h"));
- m_formatUnits.insert(QLatin1String("unsigned short"), QLatin1String("H"));
- m_formatUnits.insert(QLatin1String("long"), QLatin1String("l"));
- m_formatUnits.insert(QLatin1String("unsigned long"), QLatin1String("k"));
- m_formatUnits.insert(QLatin1String("long long"), QLatin1String("L"));
- m_formatUnits.insert(QLatin1String("__int64"), QLatin1String("L"));
- m_formatUnits.insert(QLatin1String("unsigned long long"), QLatin1String("K"));
- m_formatUnits.insert(QLatin1String("unsigned __int64"), QLatin1String("K"));
- m_formatUnits.insert(QLatin1String("double"), QLatin1String("d"));
- m_formatUnits.insert(QLatin1String("float"), QLatin1String("f"));
-}
-
-void ShibokenGenerator::initKnownPythonTypes()
-{
- m_knownPythonTypes.clear();
- m_knownPythonTypes << QLatin1String("PyBool") << QLatin1String("PyInt")
- << QLatin1String("PyFloat") << QLatin1String("PyLong") << QLatin1String("PyObject")
- << QLatin1String("PyString") << QLatin1String("PyBuffer") << QLatin1String("PySequence")
- << QLatin1String("PyTuple") << QLatin1String("PyList") << QLatin1String("PyDict")
- << QLatin1String("PyObject*") << QLatin1String("PyObject *") << QLatin1String("PyTupleObject*");
-}
-
-QString ShibokenGenerator::translateTypeForWrapperMethod(const AbstractMetaType *cType,
- const AbstractMetaClass *context,
- Options options) const
-{
- if (cType->isArray())
- return translateTypeForWrapperMethod(cType->arrayElementType(), context, options) + QLatin1String("[]");
-
- if (avoidProtectedHack() && cType->isEnum()) {
- const AbstractMetaEnum *metaEnum = findAbstractMetaEnum(cType);
- if (metaEnum && metaEnum->isProtected())
- return protectedEnumSurrogateName(metaEnum);
- }
-
- return translateType(cType, context, options);
-}
-
-bool ShibokenGenerator::shouldGenerateCppWrapper(const AbstractMetaClass *metaClass) const
-{
- if (metaClass->isNamespace() || (metaClass->attributes() & AbstractMetaAttributes::FinalCppClass))
- return false;
- bool result = metaClass->isPolymorphic() || metaClass->hasVirtualDestructor();
- if (avoidProtectedHack()) {
- result = result || metaClass->hasProtectedFields() || metaClass->hasProtectedDestructor();
- if (!result && metaClass->hasProtectedFunctions()) {
- int protectedFunctions = 0;
- int protectedOperators = 0;
- const AbstractMetaFunctionList &funcs = metaClass->functions();
- for (const AbstractMetaFunction *func : funcs) {
- if (!func->isProtected() || func->isSignal() || func->isModifiedRemoved())
- continue;
- if (func->isOperatorOverload())
- protectedOperators++;
- else
- protectedFunctions++;
- }
- result = result || (protectedFunctions > protectedOperators);
- }
- } else {
- result = result && !metaClass->hasPrivateDestructor();
- }
- return result;
-}
-
-bool ShibokenGenerator::shouldWriteVirtualMethodNative(const AbstractMetaFunction *func)
-{
- // PYSIDE-803: Extracted this because it is used multiple times.
- const AbstractMetaClass *metaClass = func->ownerClass();
- return (!avoidProtectedHack() || !metaClass->hasPrivateDestructor())
- && ((func->isVirtual() || func->isAbstract())
- && (func->attributes() & AbstractMetaAttributes::FinalCppMethod) == 0);
-}
-
-void ShibokenGenerator::lookForEnumsInClassesNotToBeGenerated(AbstractMetaEnumList &enumList, const AbstractMetaClass *metaClass)
-{
- Q_ASSERT(metaClass);
- // if a scope is not to be generated, collect its enums into the parent scope
- if (!NamespaceTypeEntry::isVisibleScope(metaClass->typeEntry())) {
- const AbstractMetaEnumList &enums = metaClass->enums();
- for (AbstractMetaEnum *metaEnum : enums) {
- if (!metaEnum->isPrivate() && metaEnum->typeEntry()->generateCode()
- && !enumList.contains(metaEnum)) {
- enumList.append(metaEnum);
- }
- }
- }
-}
-
-QString ShibokenGenerator::wrapperName(const AbstractMetaClass *metaClass) const
-{
- Q_ASSERT(shouldGenerateCppWrapper(metaClass));
- QString result = metaClass->name();
- if (metaClass->enclosingClass()) // is a inner class
- result.replace(QLatin1String("::"), QLatin1String("_"));
- return result + QLatin1String("Wrapper");
-}
-
-QString ShibokenGenerator::fullPythonClassName(const AbstractMetaClass *metaClass)
-{
- QString fullClassName = metaClass->name();
- const AbstractMetaClass *enclosing = metaClass->enclosingClass();
- while (enclosing) {
- if (NamespaceTypeEntry::isVisibleScope(enclosing->typeEntry()))
- fullClassName.prepend(enclosing->name() + QLatin1Char('.'));
- enclosing = enclosing->enclosingClass();
- }
- fullClassName.prepend(packageName() + QLatin1Char('.'));
- return fullClassName;
-}
-
-QString ShibokenGenerator::fullPythonFunctionName(const AbstractMetaFunction *func)
-{
- QString funcName;
- if (func->isOperatorOverload())
- funcName = ShibokenGenerator::pythonOperatorFunctionName(func);
- else
- funcName = func->name();
- if (func->ownerClass()) {
- QString fullClassName = fullPythonClassName(func->ownerClass());
- if (func->isConstructor())
- funcName = fullClassName;
- else
- funcName.prepend(fullClassName + QLatin1Char('.'));
- }
- else {
- funcName = packageName() + QLatin1Char('.') + func->name();
- }
- return funcName;
-}
-
-QString ShibokenGenerator::protectedEnumSurrogateName(const AbstractMetaEnum *metaEnum)
-{
- return metaEnum->fullName().replace(QLatin1Char('.'), QLatin1Char('_')).replace(QLatin1String("::"), QLatin1String("_")) + QLatin1String("_Surrogate");
-}
-
-QString ShibokenGenerator::protectedFieldGetterName(const AbstractMetaField *field)
-{
- return QStringLiteral("protected_%1_getter").arg(field->name());
-}
-
-QString ShibokenGenerator::protectedFieldSetterName(const AbstractMetaField *field)
-{
- return QStringLiteral("protected_%1_setter").arg(field->name());
-}
-
-QString ShibokenGenerator::cpythonFunctionName(const AbstractMetaFunction *func)
-{
- QString result;
-
- // PYSIDE-331: For inherited functions, we need to find the same labels.
- // Therefore we use the implementing class.
- if (func->implementingClass()) {
- result = cpythonBaseName(func->implementingClass()->typeEntry());
- if (func->isConstructor()) {
- result += QLatin1String("_Init");
- } else {
- result += QLatin1String("Func_");
- if (func->isOperatorOverload())
- result += ShibokenGenerator::pythonOperatorFunctionName(func);
- else
- result += func->name();
- }
- } else {
- result = QLatin1String("Sbk") + moduleName() + QLatin1String("Module_") + func->name();
- }
-
- return result;
-}
-
-QString ShibokenGenerator::cpythonMethodDefinitionName(const AbstractMetaFunction *func)
-{
- if (!func->ownerClass())
- return QString();
- return QStringLiteral("%1Method_%2").arg(cpythonBaseName(func->ownerClass()->typeEntry()), func->name());
-}
-
-QString ShibokenGenerator::cpythonGettersSettersDefinitionName(const AbstractMetaClass *metaClass)
-{
- return cpythonBaseName(metaClass) + QLatin1String("_getsetlist");
-}
-
-QString ShibokenGenerator::cpythonSetattroFunctionName(const AbstractMetaClass *metaClass)
-{
- return cpythonBaseName(metaClass) + QLatin1String("_setattro");
-}
-
-
-QString ShibokenGenerator::cpythonGetattroFunctionName(const AbstractMetaClass *metaClass)
-{
- return cpythonBaseName(metaClass) + QLatin1String("_getattro");
-}
-
-QString ShibokenGenerator::cpythonGetterFunctionName(const AbstractMetaField *metaField)
-{
- return QStringLiteral("%1_get_%2").arg(cpythonBaseName(metaField->enclosingClass()), metaField->name());
-}
-
-QString ShibokenGenerator::cpythonSetterFunctionName(const AbstractMetaField *metaField)
-{
- return QStringLiteral("%1_set_%2").arg(cpythonBaseName(metaField->enclosingClass()), metaField->name());
-}
-
-static QString cpythonEnumFlagsName(const QString &moduleName,
- const QString &qualifiedCppName)
-{
- QString result = QStringLiteral("Sbk%1_%2").arg(moduleName, qualifiedCppName);
- result.replace(QLatin1String("::"), QLatin1String("_"));
- return result;
-}
-
-// Return the scope for fully qualifying the enumeration including trailing "::".
-static QString searchForEnumScope(const AbstractMetaClass *metaClass, const QString &value)
-{
- if (!metaClass)
- return QString();
- const AbstractMetaEnumList &enums = metaClass->enums();
- for (const AbstractMetaEnum *metaEnum : enums) {
- if (metaEnum->findEnumValue(value))
- return resolveScopePrefix(metaEnum, value);
- }
- // PYSIDE-331: We need to also search the base classes.
- QString ret = searchForEnumScope(metaClass->enclosingClass(), value);
- if (ret.isEmpty())
- ret = searchForEnumScope(metaClass->baseClass(), value);
- return ret;
-}
-
-// Handle QFlags<> for guessScopeForDefaultValue()
-QString ShibokenGenerator::guessScopeForDefaultFlagsValue(const AbstractMetaFunction *func,
- const AbstractMetaArgument *arg,
- const QString &value) const
-{
- // Numeric values -> "Options(42)"
- static const QRegularExpression numberRegEx(QStringLiteral("^\\d+$")); // Numbers to flags
- Q_ASSERT(numberRegEx.isValid());
- if (numberRegEx.match(value).hasMatch()) {
- QString typeName = translateTypeForWrapperMethod(arg->type(), func->implementingClass());
- if (arg->type()->isConstant())
- typeName.remove(0, sizeof("const ") / sizeof(char) - 1);
- switch (arg->type()->referenceType()) {
- case NoReference:
- break;
- case LValueReference:
- typeName.chop(1);
- break;
- case RValueReference:
- typeName.chop(2);
- break;
- }
- return typeName + QLatin1Char('(') + value + QLatin1Char(')');
- }
-
- // "Options(Option1 | Option2)" -> "Options(Class::Enum::Option1 | Class::Enum::Option2)"
- static const QRegularExpression enumCombinationRegEx(QStringLiteral("^([A-Za-z_][\\w:]*)\\(([^,\\(\\)]*)\\)$")); // FlagName(EnumItem|EnumItem|...)
- Q_ASSERT(enumCombinationRegEx.isValid());
- const QRegularExpressionMatch match = enumCombinationRegEx.match(value);
- if (match.hasMatch()) {
- const QString expression = match.captured(2).trimmed();
- if (expression.isEmpty())
- return value;
- const QStringList enumItems = expression.split(QLatin1Char('|'));
- const QString scope = searchForEnumScope(func->implementingClass(),
- enumItems.constFirst().trimmed());
- if (scope.isEmpty())
- return value;
- QString result;
- QTextStream str(&result);
- str << match.captured(1) << '('; // Flag name
- for (int i = 0, size = enumItems.size(); i < size; ++i) {
- if (i)
- str << '|';
- str << scope << enumItems.at(i).trimmed();
- }
- str << ')';
- return result;
- }
- // A single flag "Option1" -> "Class::Enum::Option1"
- return searchForEnumScope(func->implementingClass(), value) + value;
-}
-
-/*
- * This function uses some heuristics to find out the scope for a given
- * argument default value since they must be fully qualified when used outside the class:
- * class A {
- * enum Enum { e1, e1 };
- * void foo(Enum e = e1);
- * }
- * should be qualified to:
- * A::Enum cppArg0 = A::Enum::e1;
- *
- * New situations may arise in the future and
- * this method should be updated, do it with care.
- */
-QString ShibokenGenerator::guessScopeForDefaultValue(const AbstractMetaFunction *func,
- const AbstractMetaArgument *arg) const
-{
- QString value = arg->defaultValueExpression();
-
- if (value.isEmpty()
- || arg->hasModifiedDefaultValueExpression()
- || isPointer(arg->type())) {
- return value;
- }
-
- static const QRegularExpression enumValueRegEx(QStringLiteral("^([A-Za-z_]\\w*)?$"));
- Q_ASSERT(enumValueRegEx.isValid());
- // Do not qualify macros by class name, eg QSGGeometry(..., int t = GL_UNSIGNED_SHORT);
- static const QRegularExpression macroRegEx(QStringLiteral("^[A-Z_][A-Z0-9_]*$"));
- Q_ASSERT(macroRegEx.isValid());
- if (arg->type()->isPrimitive() && macroRegEx.match(value).hasMatch())
- return value;
-
- QString prefix;
- if (arg->type()->isEnum()) {
- if (const AbstractMetaEnum *metaEnum = findAbstractMetaEnum(arg->type()))
- prefix = resolveScopePrefix(metaEnum, value);
- } else if (arg->type()->isFlags()) {
- value = guessScopeForDefaultFlagsValue(func, arg, value);
- } else if (arg->type()->typeEntry()->isValue()) {
- const AbstractMetaClass *metaClass = AbstractMetaClass::findClass(classes(), arg->type()->typeEntry());
- if (enumValueRegEx.match(value).hasMatch() && value != QLatin1String("NULL"))
- prefix = resolveScopePrefix(metaClass, value);
- } else if (arg->type()->isPrimitive() && arg->type()->name() == QLatin1String("int")) {
- if (enumValueRegEx.match(value).hasMatch() && func->implementingClass())
- prefix = resolveScopePrefix(func->implementingClass(), value);
- } else if(arg->type()->isPrimitive()) {
- static const QRegularExpression unknowArgumentRegEx(QStringLiteral("^(?:[A-Za-z_][\\w:]*\\()?([A-Za-z_]\\w*)(?:\\))?$")); // [PrimitiveType(] DESIREDNAME [)]
- Q_ASSERT(unknowArgumentRegEx.isValid());
- const QRegularExpressionMatch match = unknowArgumentRegEx.match(value);
- if (match.hasMatch() && func->implementingClass()) {
- const AbstractMetaFieldList &fields = func->implementingClass()->fields();
- for (const AbstractMetaField *field : fields) {
- if (match.captured(1).trimmed() == field->name()) {
- QString fieldName = field->name();
- if (field->isStatic()) {
- prefix = resolveScopePrefix(func->implementingClass(), value);
- fieldName.prepend(prefix);
- prefix.clear();
- } else {
- fieldName.prepend(QLatin1String(CPP_SELF_VAR) + QLatin1String("->"));
- }
- value.replace(match.captured(1), fieldName);
- break;
- }
- }
- }
- }
-
- if (!prefix.isEmpty())
- value.prepend(prefix);
- return value;
-}
-
-QString ShibokenGenerator::cpythonEnumName(const EnumTypeEntry *enumEntry)
-{
- QString p = enumEntry->targetLangPackage();
- p.replace(QLatin1Char('.'), QLatin1Char('_'));
- return cpythonEnumFlagsName(p, enumEntry->qualifiedCppName());
-}
-
-QString ShibokenGenerator::cpythonEnumName(const AbstractMetaEnum *metaEnum)
-{
- return cpythonEnumName(metaEnum->typeEntry());
-}
-
-QString ShibokenGenerator::cpythonFlagsName(const FlagsTypeEntry *flagsEntry)
-{
- QString p = flagsEntry->targetLangPackage();
- p.replace(QLatin1Char('.'), QLatin1Char('_'));
- return cpythonEnumFlagsName(p, flagsEntry->originalName());
-}
-
-QString ShibokenGenerator::cpythonFlagsName(const AbstractMetaEnum *metaEnum)
-{
- const FlagsTypeEntry *flags = metaEnum->typeEntry()->flags();
- if (!flags)
- return QString();
- return cpythonFlagsName(flags);
-}
-
-QString ShibokenGenerator::cpythonSpecialCastFunctionName(const AbstractMetaClass *metaClass)
-{
- return cpythonBaseName(metaClass->typeEntry()) + QLatin1String("SpecialCastFunction");
-}
-
-QString ShibokenGenerator::cpythonWrapperCPtr(const AbstractMetaClass *metaClass,
- const QString &argName) const
-{
- return cpythonWrapperCPtr(metaClass->typeEntry(), argName);
-}
-
-QString ShibokenGenerator::cpythonWrapperCPtr(const AbstractMetaType *metaType,
- const QString &argName) const
-{
- if (!ShibokenGenerator::isWrapperType(metaType->typeEntry()))
- return QString();
- return QLatin1String("reinterpret_cast< ::") + metaType->cppSignature()
- + QLatin1String(" *>(Shiboken::Conversions::cppPointer(") + cpythonTypeNameExt(metaType)
- + QLatin1String(", reinterpret_cast<SbkObject *>(") + argName + QLatin1String(")))");
-}
-
-QString ShibokenGenerator::cpythonWrapperCPtr(const TypeEntry *type,
- const QString &argName) const
-{
- if (!ShibokenGenerator::isWrapperType(type))
- return QString();
- return QLatin1String("reinterpret_cast< ::") + type->qualifiedCppName()
- + QLatin1String(" *>(Shiboken::Conversions::cppPointer(") + cpythonTypeNameExt(type)
- + QLatin1String(", reinterpret_cast<SbkObject *>(") + argName + QLatin1String(")))");
-}
-
-void ShibokenGenerator::writeToPythonConversion(QTextStream & s, const AbstractMetaType *type,
- const AbstractMetaClass * /* context */,
- const QString &argumentName)
-{
- s << cpythonToPythonConversionFunction(type) << argumentName << ')';
-}
-
-void ShibokenGenerator::writeToCppConversion(QTextStream &s, const AbstractMetaClass *metaClass,
- const QString &inArgName, const QString &outArgName)
-{
- s << cpythonToCppConversionFunction(metaClass) << inArgName << ", &" << outArgName << ')';
-}
-
-void ShibokenGenerator::writeToCppConversion(QTextStream &s, const AbstractMetaType *type, const AbstractMetaClass *context,
- const QString &inArgName, const QString &outArgName)
-{
- s << cpythonToCppConversionFunction(type, context) << inArgName << ", &" << outArgName << ')';
-}
-
-bool ShibokenGenerator::shouldRejectNullPointerArgument(const AbstractMetaFunction *func, int argIndex)
-{
- if (argIndex < 0 || argIndex >= func->arguments().count())
- return false;
-
- const AbstractMetaArgument *arg = func->arguments().at(argIndex);
- if (isValueTypeWithCopyConstructorOnly(arg->type()))
- return true;
-
- // Argument type is not a pointer, a None rejection should not be
- // necessary because the type checking would handle that already.
- if (!isPointer(arg->type()))
- return false;
- if (func->argumentRemoved(argIndex + 1))
- return false;
- const FunctionModificationList &mods = func->modifications();
- for (const FunctionModification &funcMod : mods) {
- for (const ArgumentModification &argMod : funcMod.argument_mods) {
- if (argMod.index == argIndex + 1 && argMod.noNullPointers)
- return true;
- }
- }
- return false;
-}
-
-QString ShibokenGenerator::getFormatUnitString(const AbstractMetaFunction *func, bool incRef) const
-{
- QString result;
- const char objType = (incRef ? 'O' : 'N');
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- if (func->argumentRemoved(arg->argumentIndex() + 1))
- continue;
-
- if (!func->typeReplaced(arg->argumentIndex() + 1).isEmpty()) {
- result += QLatin1Char(objType);
- } else if (arg->type()->isObject()
- || arg->type()->isValue()
- || arg->type()->isValuePointer()
- || arg->type()->isNativePointer()
- || arg->type()->isEnum()
- || arg->type()->isFlags()
- || arg->type()->isContainer()
- || arg->type()->isSmartPointer()
- || arg->type()->referenceType() == LValueReference) {
- result += QLatin1Char(objType);
- } else if (arg->type()->isPrimitive()) {
- const auto *ptype =
- static_cast<const PrimitiveTypeEntry *>(arg->type()->typeEntry());
- if (ptype->basicReferencedTypeEntry())
- ptype = ptype->basicReferencedTypeEntry();
- if (m_formatUnits.contains(ptype->name()))
- result += m_formatUnits[ptype->name()];
- else
- result += QLatin1Char(objType);
- } else if (isCString(arg->type())) {
- result += QLatin1Char('z');
- } else {
- qCWarning(lcShiboken).noquote().nospace()
- << "Method: " << func->ownerClass()->qualifiedCppName()
- << "::" << func->signature() << " => Arg:"
- << arg->name() << "index: " << arg->argumentIndex()
- << " - cannot be handled properly. Use an inject-code to fix it!";
- result += QLatin1Char('?');
- }
- }
- return result;
-}
-
-QString ShibokenGenerator::cpythonBaseName(const AbstractMetaType *type)
-{
- if (isCString(type))
- return QLatin1String("PyString");
- return cpythonBaseName(type->typeEntry());
-}
-
-QString ShibokenGenerator::cpythonBaseName(const AbstractMetaClass *metaClass)
-{
- return cpythonBaseName(metaClass->typeEntry());
-}
-
-QString ShibokenGenerator::cpythonBaseName(const TypeEntry *type)
-{
- QString baseName;
- if (ShibokenGenerator::isWrapperType(type) || type->isNamespace()) { // && type->referenceType() == NoReference) {
- baseName = QLatin1String("Sbk_") + type->name();
- } else if (type->isPrimitive()) {
- const auto *ptype = static_cast<const PrimitiveTypeEntry *>(type);
- while (ptype->basicReferencedTypeEntry())
- ptype = ptype->basicReferencedTypeEntry();
- if (ptype->targetLangApiName() == ptype->name())
- baseName = pythonPrimitiveTypeName(ptype->name());
- else
- baseName = ptype->targetLangApiName();
- } else if (type->isEnum()) {
- baseName = cpythonEnumName(static_cast<const EnumTypeEntry *>(type));
- } else if (type->isFlags()) {
- baseName = cpythonFlagsName(static_cast<const FlagsTypeEntry *>(type));
- } else if (type->isContainer()) {
- const auto *ctype = static_cast<const ContainerTypeEntry *>(type);
- switch (ctype->containerKind()) {
- case ContainerTypeEntry::ListContainer:
- case ContainerTypeEntry::StringListContainer:
- case ContainerTypeEntry::LinkedListContainer:
- case ContainerTypeEntry::VectorContainer:
- case ContainerTypeEntry::StackContainer:
- case ContainerTypeEntry::QueueContainer:
- //baseName = "PyList";
- //break;
- case ContainerTypeEntry::PairContainer:
- //baseName = "PyTuple";
- baseName = QLatin1String("PySequence");
- break;
- case ContainerTypeEntry::SetContainer:
- baseName = QLatin1String("PySet");
- break;
- case ContainerTypeEntry::MapContainer:
- case ContainerTypeEntry::MultiMapContainer:
- case ContainerTypeEntry::HashContainer:
- case ContainerTypeEntry::MultiHashContainer:
- baseName = QLatin1String("PyDict");
- break;
- default:
- Q_ASSERT(false);
- }
- } else {
- baseName = QLatin1String("PyObject");
- }
- return baseName.replace(QLatin1String("::"), QLatin1String("_"));
-}
-
-QString ShibokenGenerator::cpythonTypeName(const AbstractMetaClass *metaClass)
-{
- return cpythonTypeName(metaClass->typeEntry());
-}
-
-QString ShibokenGenerator::cpythonTypeName(const TypeEntry *type)
-{
- return cpythonBaseName(type) + QLatin1String("_TypeF()");
-}
-
-QString ShibokenGenerator::cpythonTypeNameExt(const TypeEntry *type) const
-{
- return cppApiVariableName(type->targetLangPackage()) + QLatin1Char('[')
- + getTypeIndexVariableName(type) + QLatin1Char(']');
-}
-
-QString ShibokenGenerator::converterObject(const AbstractMetaType *type)
-{
- if (isCString(type))
- return QLatin1String("Shiboken::Conversions::PrimitiveTypeConverter<const char *>()");
- if (isVoidPointer(type))
- return QLatin1String("Shiboken::Conversions::PrimitiveTypeConverter<void *>()");
- const AbstractMetaTypeCList nestedArrayTypes = type->nestedArrayTypes();
- if (!nestedArrayTypes.isEmpty() && nestedArrayTypes.constLast()->isCppPrimitive()) {
- return QStringLiteral("Shiboken::Conversions::ArrayTypeConverter<")
- + nestedArrayTypes.constLast()->minimalSignature()
- + QLatin1String(">(") + QString::number(nestedArrayTypes.size())
- + QLatin1Char(')');
- }
- if (type->typeEntry()->isContainer()) {
- return convertersVariableName(type->typeEntry()->targetLangPackage())
- + QLatin1Char('[') + getTypeIndexVariableName(type) + QLatin1Char(']');
- }
- return converterObject(type->typeEntry());
-}
-
-QString ShibokenGenerator::converterObject(const TypeEntry *type)
-{
- if (isCppPrimitive(type))
- return QString::fromLatin1("Shiboken::Conversions::PrimitiveTypeConverter<%1>()").arg(type->qualifiedCppName());
- if (isWrapperType(type) || type->isEnum() || type->isFlags())
- return QString::fromLatin1("*PepType_SGTP(%1)->converter").arg(cpythonTypeNameExt(type));
-
- if (type->isArray()) {
- qDebug() << "Warning: no idea how to handle the Qt5 type " << type->qualifiedCppName();
- return QString();
- }
-
- /* the typedef'd primitive types case */
- const auto *pte = dynamic_cast<const PrimitiveTypeEntry *>(type);
- if (!pte) {
- qDebug() << "Warning: the Qt5 primitive type is unknown" << type->qualifiedCppName();
- return QString();
- }
- if (pte->basicReferencedTypeEntry())
- pte = pte->basicReferencedTypeEntry();
- if (pte->isPrimitive() && !pte->isCppPrimitive() && !pte->customConversion())
- return QString::fromLatin1("Shiboken::Conversions::PrimitiveTypeConverter<%1>()").arg(pte->qualifiedCppName());
-
- return convertersVariableName(type->targetLangPackage())
- + QLatin1Char('[') + getTypeIndexVariableName(type) + QLatin1Char(']');
-}
-
-QString ShibokenGenerator::cpythonTypeNameExt(const AbstractMetaType *type) const
-{
- return cppApiVariableName(type->typeEntry()->targetLangPackage()) + QLatin1Char('[')
- + getTypeIndexVariableName(type) + QLatin1Char(']');
-}
-
-static inline QString unknownOperator() { return QStringLiteral("__UNKNOWN_OPERATOR__"); }
-
-QString ShibokenGenerator::fixedCppTypeName(const CustomConversion::TargetToNativeConversion *toNative)
-{
- if (toNative->sourceType())
- return fixedCppTypeName(toNative->sourceType());
- return toNative->sourceTypeName();
-}
-QString ShibokenGenerator::fixedCppTypeName(const AbstractMetaType *type)
-{
- return fixedCppTypeName(type->typeEntry(), type->cppSignature());
-}
-
-static QString _fixedCppTypeName(QString typeName)
-{
- typeName.remove(QLatin1Char(' '));
- typeName.replace(QLatin1Char('.'), QLatin1Char('_'));
- typeName.replace(QLatin1Char(','), QLatin1Char('_'));
- typeName.replace(QLatin1Char('<'), QLatin1Char('_'));
- typeName.replace(QLatin1Char('>'), QLatin1Char('_'));
- typeName.replace(QLatin1String("::"), QLatin1String("_"));
- typeName.replace(QLatin1String("*"), QLatin1String("PTR"));
- typeName.replace(QLatin1String("&"), QLatin1String("REF"));
- return typeName;
-}
-QString ShibokenGenerator::fixedCppTypeName(const TypeEntry *type, QString typeName)
-{
- if (typeName.isEmpty())
- typeName = type->qualifiedCppName();
- if (!(type->codeGeneration() & TypeEntry::GenerateTargetLang)) {
- typeName.prepend(QLatin1Char('_'));
- typeName.prepend(type->targetLangPackage());
- }
- return _fixedCppTypeName(typeName);
-}
-
-QString ShibokenGenerator::pythonPrimitiveTypeName(const QString &cppTypeName)
-{
- QString rv = ShibokenGenerator::m_pythonPrimitiveTypeName.value(cppTypeName, QString());
- if (rv.isEmpty()) {
- // activate this when some primitive types are missing,
- // i.e. when shiboken itself fails to build.
- // In general, this is valid while just called by isNumeric()
- // used on Qt5, 2015-09-20
- if (false) {
- std::cerr << "primitive type not found: " << qPrintable(cppTypeName) << std::endl;
- abort();
- }
- }
- return rv;
-}
-
-QString ShibokenGenerator::pythonPrimitiveTypeName(const PrimitiveTypeEntry *type)
-{
- while (type->basicReferencedTypeEntry())
- type = type->basicReferencedTypeEntry();
- return pythonPrimitiveTypeName(type->name());
-}
-
-QString ShibokenGenerator::pythonOperatorFunctionName(const QString &cppOpFuncName)
-{
- QString value = m_pythonOperators.value(cppOpFuncName);
- if (value.isEmpty())
- return unknownOperator();
- value.prepend(QLatin1String("__"));
- value.append(QLatin1String("__"));
- return value;
-}
-
-QString ShibokenGenerator::pythonOperatorFunctionName(const AbstractMetaFunction *func)
-{
- QString op = pythonOperatorFunctionName(func->originalName());
- if (op == unknownOperator())
- qCWarning(lcShiboken).noquote().nospace() << msgUnknownOperator(func);
- if (func->arguments().isEmpty()) {
- if (op == QLatin1String("__sub__"))
- op = QLatin1String("__neg__");
- else if (op == QLatin1String("__add__"))
- op = QLatin1String("__pos__");
- } else if (func->isStatic() && func->arguments().size() == 2) {
- // If a operator overload function has 2 arguments and
- // is static we assume that it is a reverse operator.
- op = op.insert(2, QLatin1Char('r'));
- }
- return op;
-}
-
-QString ShibokenGenerator::pythonRichCompareOperatorId(const QString &cppOpFuncName)
-{
- return QLatin1String("Py_") + m_pythonOperators.value(cppOpFuncName).toUpper();
-}
-
-QString ShibokenGenerator::pythonRichCompareOperatorId(const AbstractMetaFunction *func)
-{
- return pythonRichCompareOperatorId(func->originalName());
-}
-
-bool ShibokenGenerator::isNumber(const QString &cpythonApiName)
-{
- return cpythonApiName == QLatin1String("PyInt")
- || cpythonApiName == QLatin1String("PyFloat")
- || cpythonApiName == QLatin1String("PyLong")
- || cpythonApiName == QLatin1String("PyBool");
-}
-
-bool ShibokenGenerator::isNumber(const TypeEntry *type)
-{
- if (!type->isPrimitive())
- return false;
- return isNumber(pythonPrimitiveTypeName(static_cast<const PrimitiveTypeEntry *>(type)));
-}
-
-bool ShibokenGenerator::isNumber(const AbstractMetaType *type)
-{
- return isNumber(type->typeEntry());
-}
-
-bool ShibokenGenerator::isPyInt(const TypeEntry *type)
-{
- if (!type->isPrimitive())
- return false;
- return pythonPrimitiveTypeName(static_cast<const PrimitiveTypeEntry *>(type))
- == QLatin1String("PyInt");
-}
-
-bool ShibokenGenerator::isPyInt(const AbstractMetaType *type)
-{
- return isPyInt(type->typeEntry());
-}
-
-bool ShibokenGenerator::isWrapperType(const TypeEntry *type)
-{
- if (type->isComplex())
- return ShibokenGenerator::isWrapperType(static_cast<const ComplexTypeEntry *>(type));
- return type->isObject() || type->isValue() || type->isSmartPointer();
-}
-bool ShibokenGenerator::isWrapperType(const ComplexTypeEntry *type)
-{
- return isObjectType(type) || type->isValue() || type->isSmartPointer();
-}
-bool ShibokenGenerator::isWrapperType(const AbstractMetaType *metaType)
-{
- return isObjectType(metaType)
- || metaType->typeEntry()->isValue()
- || metaType->typeEntry()->isSmartPointer();
-}
-
-bool ShibokenGenerator::isPointerToWrapperType(const AbstractMetaType *type)
-{
- return (isObjectType(type) && type->indirections() == 1) || type->isValuePointer();
-}
-
-bool ShibokenGenerator::isObjectTypeUsedAsValueType(const AbstractMetaType *type)
-{
- return type->typeEntry()->isObject() && type->referenceType() == NoReference && type->indirections() == 0;
-}
-
-bool ShibokenGenerator::isValueTypeWithCopyConstructorOnly(const AbstractMetaClass *metaClass)
-{
- if (!metaClass || !metaClass->typeEntry()->isValue())
- return false;
- if (metaClass->attributes().testFlag(AbstractMetaAttributes::HasRejectedDefaultConstructor))
- return false;
- const AbstractMetaFunctionList ctors =
- metaClass->queryFunctions(AbstractMetaClass::Constructors);
- bool copyConstructorFound = false;
- for (auto ctor : ctors) {
- switch (ctor->functionType()) {
- case AbstractMetaFunction::ConstructorFunction:
- return false;
- case AbstractMetaFunction::CopyConstructorFunction:
- copyConstructorFound = true;
- break;
- case AbstractMetaFunction::MoveConstructorFunction:
- break;
- default:
- Q_ASSERT(false);
- break;
- }
- }
- return copyConstructorFound;
-}
-
-bool ShibokenGenerator::isValueTypeWithCopyConstructorOnly(const TypeEntry *type) const
-{
- if (!type || !type->isValue())
- return false;
- return isValueTypeWithCopyConstructorOnly(AbstractMetaClass::findClass(classes(), type));
-}
-
-bool ShibokenGenerator::isValueTypeWithCopyConstructorOnly(const AbstractMetaType *type) const
-{
- if (!type || !type->typeEntry()->isValue())
- return false;
- return isValueTypeWithCopyConstructorOnly(type->typeEntry());
-}
-
-bool ShibokenGenerator::isUserPrimitive(const TypeEntry *type)
-{
- if (!type->isPrimitive())
- return false;
- const auto *trueType = static_cast<const PrimitiveTypeEntry *>(type);
- if (trueType->basicReferencedTypeEntry())
- trueType = trueType->basicReferencedTypeEntry();
- return trueType->isPrimitive() && !trueType->isCppPrimitive()
- && trueType->qualifiedCppName() != QLatin1String("std::string");
-}
-
-bool ShibokenGenerator::isUserPrimitive(const AbstractMetaType *type)
-{
- if (type->indirections() != 0)
- return false;
- return isUserPrimitive(type->typeEntry());
-}
-
-bool ShibokenGenerator::isCppPrimitive(const TypeEntry *type)
-{
- if (type->isCppPrimitive())
- return true;
- if (!type->isPrimitive())
- return false;
- const auto *trueType = static_cast<const PrimitiveTypeEntry *>(type);
- if (trueType->basicReferencedTypeEntry())
- trueType = trueType->basicReferencedTypeEntry();
- return trueType->qualifiedCppName() == QLatin1String("std::string");
-}
-
-bool ShibokenGenerator::isCppPrimitive(const AbstractMetaType *type)
-{
- if (isCString(type) || isVoidPointer(type))
- return true;
- if (type->indirections() != 0)
- return false;
- return isCppPrimitive(type->typeEntry());
-}
-
-bool ShibokenGenerator::shouldDereferenceArgumentPointer(const AbstractMetaArgument *arg)
-{
- return shouldDereferenceAbstractMetaTypePointer(arg->type());
-}
-
-bool ShibokenGenerator::shouldDereferenceAbstractMetaTypePointer(const AbstractMetaType *metaType)
-{
- return metaType->referenceType() == LValueReference && isWrapperType(metaType) && !isPointer(metaType);
-}
-
-bool ShibokenGenerator::visibilityModifiedToPrivate(const AbstractMetaFunction *func)
-{
- const FunctionModificationList &mods = func->modifications();
- for (const FunctionModification &mod : mods) {
- if (mod.modifiers & Modification::Private)
- return true;
- }
- return false;
-}
-
-QString ShibokenGenerator::cpythonCheckFunction(const AbstractMetaType *metaType, bool genericNumberType)
-{
- QString customCheck;
- if (metaType->typeEntry()->isCustom()) {
- AbstractMetaType *type;
- customCheck = guessCPythonCheckFunction(metaType->typeEntry()->name(), &type);
- if (type)
- metaType = type;
- if (!customCheck.isEmpty())
- return customCheck;
- }
-
- if (isCppPrimitive(metaType)) {
- if (isCString(metaType))
- return QLatin1String("Shiboken::String::check");
- if (isVoidPointer(metaType))
- return QLatin1String("PyObject_Check");
- return cpythonCheckFunction(metaType->typeEntry(), genericNumberType);
- }
- auto typeEntry = metaType->typeEntry();
- if (typeEntry->isContainer()) {
- QString typeCheck = QLatin1String("Shiboken::Conversions::");
- ContainerTypeEntry::ContainerKind type =
- static_cast<const ContainerTypeEntry *>(typeEntry)->containerKind();
- if (type == ContainerTypeEntry::ListContainer
- || type == ContainerTypeEntry::StringListContainer
- || type == ContainerTypeEntry::LinkedListContainer
- || type == ContainerTypeEntry::VectorContainer
- || type == ContainerTypeEntry::StackContainer
- || type == ContainerTypeEntry::SetContainer
- || type == ContainerTypeEntry::QueueContainer) {
- const AbstractMetaType *type = metaType->instantiations().constFirst();
- if (isPointerToWrapperType(type)) {
- typeCheck += QString::fromLatin1("checkSequenceTypes(%1, ").arg(cpythonTypeNameExt(type));
- } else if (isWrapperType(type)) {
- typeCheck += QLatin1String("convertibleSequenceTypes(reinterpret_cast<SbkObjectType *>(");
- typeCheck += cpythonTypeNameExt(type);
- typeCheck += QLatin1String("), ");
- } else {
- typeCheck += QString::fromLatin1("convertibleSequenceTypes(%1, ").arg(converterObject(type));
- }
- } else if (type == ContainerTypeEntry::MapContainer
- || type == ContainerTypeEntry::MultiMapContainer
- || type == ContainerTypeEntry::HashContainer
- || type == ContainerTypeEntry::MultiHashContainer
- || type == ContainerTypeEntry::PairContainer) {
- QString pyType = (type == ContainerTypeEntry::PairContainer) ? QLatin1String("Pair") : QLatin1String("Dict");
- const AbstractMetaType *firstType = metaType->instantiations().constFirst();
- const AbstractMetaType *secondType = metaType->instantiations().constLast();
- if (isPointerToWrapperType(firstType) && isPointerToWrapperType(secondType)) {
- typeCheck += QString::fromLatin1("check%1Types(%2, %3, ")
- .arg(pyType, cpythonTypeNameExt(firstType), cpythonTypeNameExt(secondType));
- } else {
- typeCheck += QString::fromLatin1("convertible%1Types(%2, %3, %4, %5, ")
- .arg(pyType, converterObject(firstType),
- isPointerToWrapperType(firstType) ? QLatin1String("true") : QLatin1String("false"),
- converterObject(secondType),
- isPointerToWrapperType(secondType) ? QLatin1String("true") : QLatin1String("false"));
- }
- }
- return typeCheck;
- }
- return cpythonCheckFunction(typeEntry, genericNumberType);
-}
-
-QString ShibokenGenerator::cpythonCheckFunction(const TypeEntry *type, bool genericNumberType)
-{
- QString customCheck;
- if (type->isCustom()) {
- AbstractMetaType *metaType;
- customCheck = guessCPythonCheckFunction(type->name(), &metaType);
- if (metaType)
- return cpythonCheckFunction(metaType, genericNumberType);
- return customCheck;
- }
-
- if (type->isEnum() || type->isFlags() || isWrapperType(type))
- return QString::fromLatin1("SbkObject_TypeCheck(%1, ").arg(cpythonTypeNameExt(type));
- if (isCppPrimitive(type)) {
- return pythonPrimitiveTypeName(static_cast<const PrimitiveTypeEntry *>(type))
- + QLatin1String("_Check");
- }
- QString typeCheck;
- if (type->targetLangApiName() == type->name())
- typeCheck = cpythonIsConvertibleFunction(type);
- else if (type->targetLangApiName() == QLatin1String("PyUnicode"))
- typeCheck = QLatin1String("Shiboken::String::check");
- else
- typeCheck = type->targetLangApiName() + QLatin1String("_Check");
- return typeCheck;
-}
-
-QString ShibokenGenerator::guessCPythonCheckFunction(const QString &type, AbstractMetaType **metaType)
-{
- *metaType = nullptr;
- // PYSIDE-795: We abuse PySequence for iterables.
- // This part handles the overrides in the XML files.
- if (type == QLatin1String("PySequence"))
- return QLatin1String("Shiboken::String::checkIterable");
-
- if (type == QLatin1String("PyTypeObject"))
- return QLatin1String("PyType_Check");
-
- if (type == QLatin1String("PyBuffer"))
- return QLatin1String("Shiboken::Buffer::checkType");
-
- if (type == QLatin1String("str"))
- return QLatin1String("Shiboken::String::check");
-
- *metaType = buildAbstractMetaTypeFromString(type);
- if (*metaType && !(*metaType)->typeEntry()->isCustom())
- return QString();
-
- return type + QLatin1String("_Check");
-}
-
-QString ShibokenGenerator::cpythonIsConvertibleFunction(const TypeEntry *type,
- bool /* genericNumberType */,
- bool /* checkExact */)
-{
- if (isWrapperType(type)) {
- QString result = QLatin1String("Shiboken::Conversions::");
- result += (type->isValue() && !isValueTypeWithCopyConstructorOnly(type))
- ? QLatin1String("isPythonToCppValueConvertible")
- : QLatin1String("isPythonToCppPointerConvertible");
- result += QLatin1String("(reinterpret_cast<SbkObjectType *>(")
- + cpythonTypeNameExt(type) + QLatin1String("), ");
- return result;
- }
- return QString::fromLatin1("Shiboken::Conversions::isPythonToCppConvertible(%1, ")
- .arg(converterObject(type));
-}
-QString ShibokenGenerator::cpythonIsConvertibleFunction(const AbstractMetaType *metaType,
- bool /* genericNumberType */)
-{
- QString customCheck;
- if (metaType->typeEntry()->isCustom()) {
- AbstractMetaType *type;
- customCheck = guessCPythonCheckFunction(metaType->typeEntry()->name(), &type);
- if (type)
- metaType = type;
- if (!customCheck.isEmpty())
- return customCheck;
- }
-
- QString result = QLatin1String("Shiboken::Conversions::");
- if (isWrapperType(metaType)) {
- if (isPointer(metaType) || isValueTypeWithCopyConstructorOnly(metaType))
- result += QLatin1String("isPythonToCppPointerConvertible");
- else if (metaType->referenceType() == LValueReference)
- result += QLatin1String("isPythonToCppReferenceConvertible");
- else
- result += QLatin1String("isPythonToCppValueConvertible");
- result += QLatin1String("(reinterpret_cast<SbkObjectType *>(")
- + cpythonTypeNameExt(metaType) + QLatin1String("), ");
- return result;
- }
- result += QLatin1String("isPythonToCppConvertible(") + converterObject(metaType);
- // Write out array sizes if known
- const AbstractMetaTypeCList nestedArrayTypes = metaType->nestedArrayTypes();
- if (!nestedArrayTypes.isEmpty() && nestedArrayTypes.constLast()->isCppPrimitive()) {
- const int dim1 = metaType->arrayElementCount();
- const int dim2 = nestedArrayTypes.constFirst()->isArray()
- ? nestedArrayTypes.constFirst()->arrayElementCount() : -1;
- result += QLatin1String(", ") + QString::number(dim1)
- + QLatin1String(", ") + QString::number(dim2);
- }
- result += QLatin1String(", ");
- return result;
-}
-
-QString ShibokenGenerator::cpythonIsConvertibleFunction(const AbstractMetaArgument *metaArg, bool genericNumberType)
-{
- return cpythonIsConvertibleFunction(metaArg->type(), genericNumberType);
-}
-
-QString ShibokenGenerator::cpythonToCppConversionFunction(const AbstractMetaClass *metaClass)
-{
- return QLatin1String("Shiboken::Conversions::pythonToCppPointer(reinterpret_cast<SbkObjectType *>(")
- + cpythonTypeNameExt(metaClass->typeEntry()) + QLatin1String("), ");
-}
-
-QString ShibokenGenerator::cpythonToCppConversionFunction(const AbstractMetaType *type,
- const AbstractMetaClass * /* context */)
-{
- if (isWrapperType(type)) {
- return QLatin1String("Shiboken::Conversions::pythonToCpp")
- + (isPointer(type) ? QLatin1String("Pointer") : QLatin1String("Copy"))
- + QLatin1String("(reinterpret_cast<SbkObjectType *>(")
- + cpythonTypeNameExt(type) + QLatin1String("), ");
- }
- return QStringLiteral("Shiboken::Conversions::pythonToCppCopy(%1, ")
- .arg(converterObject(type));
-}
-
-QString ShibokenGenerator::cpythonToPythonConversionFunction(const AbstractMetaType *type,
- const AbstractMetaClass * /* context */)
-{
- if (isWrapperType(type)) {
- QString conversion;
- if (type->referenceType() == LValueReference && !(type->isValue() && type->isConstant()) && !isPointer(type))
- conversion = QLatin1String("reference");
- else if (type->isValue() || type->isSmartPointer())
- conversion = QLatin1String("copy");
- else
- conversion = QLatin1String("pointer");
- QString result = QLatin1String("Shiboken::Conversions::") + conversion
- + QLatin1String("ToPython(reinterpret_cast<SbkObjectType *>(")
- + cpythonTypeNameExt(type) + QLatin1String("), ");
- if (conversion != QLatin1String("pointer"))
- result += QLatin1Char('&');
- return result;
- }
- return QStringLiteral("Shiboken::Conversions::copyToPython(%1, %2")
- .arg(converterObject(type),
- (isCString(type) || isVoidPointer(type)) ? QString() : QLatin1String("&"));
-}
-
-QString ShibokenGenerator::cpythonToPythonConversionFunction(const AbstractMetaClass *metaClass)
-{
- return cpythonToPythonConversionFunction(metaClass->typeEntry());
-}
-
-QString ShibokenGenerator::cpythonToPythonConversionFunction(const TypeEntry *type)
-{
- if (isWrapperType(type)) {
- const QString conversion = type->isValue() ? QLatin1String("copy") : QLatin1String("pointer");
- QString result = QLatin1String("Shiboken::Conversions::") + conversion
- + QLatin1String("ToPython(reinterpret_cast<SbkObjectType *>(") + cpythonTypeNameExt(type)
- + QLatin1String("), ");
- if (conversion != QLatin1String("pointer"))
- result += QLatin1Char('&');
- return result;
- }
-
- return QStringLiteral("Shiboken::Conversions::copyToPython(%1, &").arg(converterObject(type));
-}
-
-QString ShibokenGenerator::argumentString(const AbstractMetaFunction *func,
- const AbstractMetaArgument *argument,
- Options options) const
-{
- QString modified_type;
- if (!(options & OriginalTypeDescription))
- modified_type = func->typeReplaced(argument->argumentIndex() + 1);
- QString arg;
-
- if (modified_type.isEmpty())
- arg = translateType(argument->type(), func->implementingClass(), options);
- else
- arg = modified_type.replace(QLatin1Char('$'), QLatin1Char('.'));
-
- if (!(options & Generator::SkipName)) {
- // "int a", "int a[]"
- const int arrayPos = arg.indexOf(QLatin1Char('['));
- if (arrayPos != -1)
- arg.insert(arrayPos, QLatin1Char(' ') + argument->name());
- else
- arg.append(QLatin1Char(' ') + argument->name());
- }
-
- if ((options & Generator::SkipDefaultValues) != Generator::SkipDefaultValues &&
- !argument->originalDefaultValueExpression().isEmpty())
- {
- QString default_value = argument->originalDefaultValueExpression();
- if (default_value == QLatin1String("NULL"))
- default_value = QLatin1String(NULL_PTR);
-
- //WORKAROUND: fix this please
- if (default_value.startsWith(QLatin1String("new ")))
- default_value.remove(0, 4);
-
- arg += QLatin1String(" = ") + default_value;
- }
-
- return arg;
-}
-
-void ShibokenGenerator::writeArgument(QTextStream &s,
- const AbstractMetaFunction *func,
- const AbstractMetaArgument *argument,
- Options options) const
-{
- s << argumentString(func, argument, options);
-}
-
-void ShibokenGenerator::writeFunctionArguments(QTextStream &s,
- const AbstractMetaFunction *func,
- Options options) const
-{
- AbstractMetaArgumentList arguments = func->arguments();
-
- if (options & Generator::WriteSelf) {
- s << func->implementingClass()->name() << '&';
- if (!(options & SkipName))
- s << " self";
- }
-
- int argUsed = 0;
- for (int i = 0; i < arguments.size(); ++i) {
- if ((options & Generator::SkipRemovedArguments) && func->argumentRemoved(i+1))
- continue;
-
- if ((options & Generator::WriteSelf) || argUsed != 0)
- s << ", ";
- writeArgument(s, func, arguments[i], options);
- argUsed++;
- }
-}
-
-GeneratorContext ShibokenGenerator::contextForClass(const AbstractMetaClass *c) const
-{
- GeneratorContext result = Generator::contextForClass(c);
- if (shouldGenerateCppWrapper(c)) {
- result.m_type = GeneratorContext::WrappedClass;
- result.m_wrappername = wrapperName(c);
- }
- return result;
-}
-
-QString ShibokenGenerator::functionReturnType(const AbstractMetaFunction *func, Options options) const
-{
- QString modifiedReturnType = QString(func->typeReplaced(0));
- if (!modifiedReturnType.isEmpty() && !(options & OriginalTypeDescription))
- return modifiedReturnType;
- return translateType(func->type(), func->implementingClass(), options);
-}
-
-QString ShibokenGenerator::functionSignature(const AbstractMetaFunction *func,
- const QString &prepend,
- const QString &append,
- Options options,
- int /* argCount */) const
-{
- QString result;
- QTextStream s(&result);
- // The actual function
- if (!(func->isEmptyFunction() ||
- func->isNormal() ||
- func->isSignal())) {
- options |= Generator::SkipReturnType;
- } else {
- s << functionReturnType(func, options) << ' ';
- }
-
- // name
- QString name(func->originalName());
- if (func->isConstructor())
- name = wrapperName(func->ownerClass());
-
- s << prepend << name << append << '(';
- writeFunctionArguments(s, func, options);
- s << ')';
-
- if (func->isConstant() && !(options & Generator::ExcludeMethodConst))
- s << " const";
-
- if (func->exceptionSpecification() == ExceptionSpecification::NoExcept)
- s << " noexcept";
-
- return result;
-}
-
-void ShibokenGenerator::writeArgumentNames(QTextStream &s,
- const AbstractMetaFunction *func,
- Options options) const
-{
- const AbstractMetaArgumentList arguments = func->arguments();
- int argCount = 0;
- for (auto argument : arguments) {
- const int index = argument->argumentIndex() + 1;
- if ((options & Generator::SkipRemovedArguments) && (func->argumentRemoved(index)))
- continue;
-
- s << ((argCount > 0) ? ", " : "") << argument->name();
-
- if (((options & Generator::VirtualCall) == 0)
- && (!func->conversionRule(TypeSystem::NativeCode, index).isEmpty()
- || !func->conversionRule(TypeSystem::TargetLangCode, index).isEmpty())
- && !func->isConstructor()) {
- s << CONV_RULE_OUT_VAR_SUFFIX;
- }
-
- argCount++;
- }
-}
-
-void ShibokenGenerator::writeFunctionCall(QTextStream &s,
- const AbstractMetaFunction *func,
- Options options) const
-{
- if (!(options & Generator::SkipName))
- s << (func->isConstructor() ? func->ownerClass()->qualifiedCppName() : func->originalName());
- s << '(';
- writeArgumentNames(s, func, options);
- s << ')';
-}
-
-void ShibokenGenerator::writeUnusedVariableCast(QTextStream &s, const QString &variableName)
-{
- s << INDENT << "SBK_UNUSED(" << variableName<< ")\n";
-}
-
-static bool filterFunction(const AbstractMetaFunction *func, bool avoidProtectedHack)
-{
- switch (func->functionType()) {
- case AbstractMetaFunction::DestructorFunction:
- case AbstractMetaFunction::SignalFunction:
- case AbstractMetaFunction::GetAttroFunction:
- case AbstractMetaFunction::SetAttroFunction:
- return false;
- default:
- break;
- }
- if (func->usesRValueReferences())
- return false;
- if (func->isModifiedRemoved() && !func->isAbstract()
- && (!avoidProtectedHack || !func->isProtected())) {
- return false;
- }
- return true;
-}
-
-AbstractMetaFunctionList ShibokenGenerator::filterFunctions(const AbstractMetaClass *metaClass)
-{
- AbstractMetaFunctionList result;
- const AbstractMetaFunctionList &funcs = metaClass->functions();
- result.reserve(funcs.size());
- for (AbstractMetaFunction *func : funcs) {
- if (filterFunction(func, avoidProtectedHack()))
- result.append(func);
- }
- return result;
-}
-
-ShibokenGenerator::ExtendedConverterData ShibokenGenerator::getExtendedConverters() const
-{
- ExtendedConverterData extConvs;
- const AbstractMetaClassList &classList = classes();
- for (const AbstractMetaClass *metaClass : classList) {
- // Use only the classes for the current module.
- if (!shouldGenerate(metaClass))
- continue;
- const AbstractMetaFunctionList &overloads = metaClass->operatorOverloads(AbstractMetaClass::ConversionOp);
- for (AbstractMetaFunction *convOp : overloads) {
- // Get only the conversion operators that return a type from another module,
- // that are value-types and were not removed in the type system.
- const TypeEntry *convType = convOp->type()->typeEntry();
- if ((convType->codeGeneration() & TypeEntry::GenerateTargetLang)
- || !convType->isValue()
- || convOp->isModifiedRemoved())
- continue;
- extConvs[convType].append(convOp->ownerClass());
- }
- }
- return extConvs;
-}
-
-QVector<const CustomConversion *> ShibokenGenerator::getPrimitiveCustomConversions()
-{
- QVector<const CustomConversion *> conversions;
- const PrimitiveTypeEntryList &primitiveTypeList = primitiveTypes();
- for (const PrimitiveTypeEntry *type : primitiveTypeList) {
- if (!shouldGenerateTypeEntry(type) || !isUserPrimitive(type) || !type->customConversion())
- continue;
-
- conversions << type->customConversion();
- }
- return conversions;
-}
-
-static QString getArgumentsFromMethodCall(const QString &str)
-{
- // It would be way nicer to be able to use a Perl like
- // regular expression that accepts temporary variables
- // to count the parenthesis.
- // For more information check this:
- // http://perl.plover.com/yak/regex/samples/slide083.html
- static QLatin1String funcCall("%CPPSELF.%FUNCTION_NAME");
- int pos = str.indexOf(funcCall);
- if (pos == -1)
- return QString();
- pos = pos + funcCall.size();
- while (str.at(pos) == QLatin1Char(' ') || str.at(pos) == QLatin1Char('\t'))
- ++pos;
- if (str.at(pos) == QLatin1Char('('))
- ++pos;
- int begin = pos;
- int counter = 1;
- while (counter != 0) {
- if (str.at(pos) == QLatin1Char('('))
- ++counter;
- else if (str.at(pos) == QLatin1Char(')'))
- --counter;
- ++pos;
- }
- return str.mid(begin, pos-begin-1);
-}
-
-QString ShibokenGenerator::getCodeSnippets(const CodeSnipList &codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language)
-{
- QString code;
- QTextStream c(&code);
- for (const CodeSnip &snip : codeSnips) {
- if ((position != TypeSystem::CodeSnipPositionAny && snip.position != position) || !(snip.language & language))
- continue;
- QString snipCode;
- QTextStream sc(&snipCode);
- formatCode(sc, snip.code(), INDENT);
- c << snipCode;
- }
- return code;
-}
-
-void ShibokenGenerator::processClassCodeSnip(QString &code, const GeneratorContext &context)
-{
- auto metaClass = context.metaClass();
- // Replace template variable by the Python Type object
- // for the class context in which the variable is used.
- code.replace(QLatin1String("%PYTHONTYPEOBJECT"),
- cpythonTypeName(metaClass) + QLatin1String("->type"));
- const QString className = context.useWrapper()
- ? context.wrapperName() : metaClass->qualifiedCppName();
- code.replace(QLatin1String("%TYPE"), className);
- code.replace(QLatin1String("%CPPTYPE"), metaClass->name());
-
- processCodeSnip(code);
-}
-
-void ShibokenGenerator::processCodeSnip(QString &code)
-{
- // replace "toPython" converters
- replaceConvertToPythonTypeSystemVariable(code);
-
- // replace "toCpp" converters
- replaceConvertToCppTypeSystemVariable(code);
-
- // replace "isConvertible" check
- replaceIsConvertibleToCppTypeSystemVariable(code);
-
- // replace "checkType" check
- replaceTypeCheckTypeSystemVariable(code);
-}
-
-ShibokenGenerator::ArgumentVarReplacementList ShibokenGenerator::getArgumentReplacement(const AbstractMetaFunction *func,
- bool usePyArgs, TypeSystem::Language language,
- const AbstractMetaArgument *lastArg)
-{
- ArgumentVarReplacementList argReplacements;
- TypeSystem::Language convLang = (language == TypeSystem::TargetLangCode)
- ? TypeSystem::NativeCode : TypeSystem::TargetLangCode;
- int removed = 0;
- for (int i = 0; i < func->arguments().size(); ++i) {
- const AbstractMetaArgument *arg = func->arguments().at(i);
- QString argValue;
- if (language == TypeSystem::TargetLangCode) {
- bool hasConversionRule = !func->conversionRule(convLang, i+1).isEmpty();
- const bool argRemoved = func->argumentRemoved(i+1);
- if (argRemoved)
- ++removed;
- if (argRemoved && hasConversionRule)
- argValue = arg->name() + QLatin1String(CONV_RULE_OUT_VAR_SUFFIX);
- else if (argRemoved || (lastArg && arg->argumentIndex() > lastArg->argumentIndex()))
- argValue = QLatin1String(CPP_ARG_REMOVED) + QString::number(i);
- if (!argRemoved && argValue.isEmpty()) {
- int argPos = i - removed;
- const AbstractMetaType *type = arg->type();
- QString typeReplaced = func->typeReplaced(arg->argumentIndex() + 1);
- if (!typeReplaced.isEmpty()) {
- AbstractMetaType *builtType = buildAbstractMetaTypeFromString(typeReplaced);
- if (builtType)
- type = builtType;
- }
- if (type->typeEntry()->isCustom()) {
- argValue = usePyArgs
- ? pythonArgsAt(argPos) : QLatin1String(PYTHON_ARG);
- } else {
- argValue = hasConversionRule
- ? arg->name() + QLatin1String(CONV_RULE_OUT_VAR_SUFFIX)
- : QLatin1String(CPP_ARG) + QString::number(argPos);
- if (isWrapperType(type)) {
- if (type->referenceType() == LValueReference && !isPointer(type))
- argValue.prepend(QLatin1Char('*'));
- }
- }
- }
- } else {
- argValue = arg->name();
- }
- if (!argValue.isEmpty())
- argReplacements << ArgumentVarReplacementPair(arg, argValue);
-
- }
- return argReplacements;
-}
-
-void ShibokenGenerator::writeClassCodeSnips(QTextStream &s,
- const CodeSnipList &codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language,
- const GeneratorContext &context)
-{
- QString code = getCodeSnippets(codeSnips, position, language);
- if (code.isEmpty())
- return;
- processClassCodeSnip(code, context);
- s << INDENT << "// Begin code injection\n";
- s << code;
- s << INDENT << "// End of code injection\n";
-}
-
-void ShibokenGenerator::writeCodeSnips(QTextStream &s,
- const CodeSnipList &codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language)
-{
- QString code = getCodeSnippets(codeSnips, position, language);
- if (code.isEmpty())
- return;
- processCodeSnip(code);
- s << INDENT << "// Begin code injection\n";
- s << code;
- s << INDENT << "// End of code injection\n";
-}
-
-void ShibokenGenerator::writeCodeSnips(QTextStream &s,
- const CodeSnipList &codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language,
- const AbstractMetaFunction *func,
- const AbstractMetaArgument *lastArg)
-{
- QString code = getCodeSnippets(codeSnips, position, language);
- if (code.isEmpty())
- return;
-
- // Calculate the real number of arguments.
- int argsRemoved = 0;
- for (int i = 0; i < func->arguments().size(); i++) {
- if (func->argumentRemoved(i+1))
- argsRemoved++;
- }
-
- const auto &groups = func->implementingClass()
- ? getFunctionGroups(func->implementingClass())
- : getGlobalFunctionGroups();
- OverloadData od(groups[func->name()], this);
- bool usePyArgs = pythonFunctionWrapperUsesListOfArguments(od);
-
- // Replace %PYARG_# variables.
- code.replace(QLatin1String("%PYARG_0"), QLatin1String(PYTHON_RETURN_VAR));
-
- static const QRegularExpression pyArgsRegex(QStringLiteral("%PYARG_(\\d+)"));
- Q_ASSERT(pyArgsRegex.isValid());
- if (language == TypeSystem::TargetLangCode) {
- if (usePyArgs) {
- code.replace(pyArgsRegex, QLatin1String(PYTHON_ARGS) + QLatin1String("[\\1-1]"));
- } else {
- static const QRegularExpression pyArgsRegexCheck(QStringLiteral("%PYARG_([2-9]+)"));
- Q_ASSERT(pyArgsRegexCheck.isValid());
- const QRegularExpressionMatch match = pyArgsRegexCheck.match(code);
- if (match.hasMatch()) {
- qCWarning(lcShiboken).noquote().nospace()
- << msgWrongIndex("%PYARG", match.captured(1), func);
- return;
- }
- code.replace(QLatin1String("%PYARG_1"), QLatin1String(PYTHON_ARG));
- }
- } else {
- // Replaces the simplest case of attribution to a
- // Python argument on the binding virtual method.
- static const QRegularExpression pyArgsAttributionRegex(QStringLiteral("%PYARG_(\\d+)\\s*=[^=]\\s*([^;]+)"));
- Q_ASSERT(pyArgsAttributionRegex.isValid());
- code.replace(pyArgsAttributionRegex, QLatin1String("PyTuple_SET_ITEM(")
- + QLatin1String(PYTHON_ARGS) + QLatin1String(", \\1-1, \\2)"));
- code.replace(pyArgsRegex, QLatin1String("PyTuple_GET_ITEM(")
- + QLatin1String(PYTHON_ARGS) + QLatin1String(", \\1-1)"));
- }
-
- // Replace %ARG#_TYPE variables.
- const AbstractMetaArgumentList &arguments = func->arguments();
- for (const AbstractMetaArgument *arg : arguments) {
- QString argTypeVar = QStringLiteral("%ARG%1_TYPE").arg(arg->argumentIndex() + 1);
- QString argTypeVal = arg->type()->cppSignature();
- code.replace(argTypeVar, argTypeVal);
- }
-
- static const QRegularExpression cppArgTypeRegexCheck(QStringLiteral("%ARG(\\d+)_TYPE"));
- Q_ASSERT(cppArgTypeRegexCheck.isValid());
- QRegularExpressionMatchIterator rit = cppArgTypeRegexCheck.globalMatch(code);
- while (rit.hasNext()) {
- QRegularExpressionMatch match = rit.next();
- qCWarning(lcShiboken).noquote().nospace()
- << msgWrongIndex("%ARG#_TYPE", match.captured(1), func);
- }
-
- // Replace template variable for return variable name.
- if (func->isConstructor()) {
- code.replace(QLatin1String("%0."), QLatin1String("cptr->"));
- code.replace(QLatin1String("%0"), QLatin1String("cptr"));
- } else if (func->type()) {
- QString returnValueOp = isPointerToWrapperType(func->type())
- ? QLatin1String("%1->") : QLatin1String("%1.");
- if (ShibokenGenerator::isWrapperType(func->type()))
- code.replace(QLatin1String("%0."), returnValueOp.arg(QLatin1String(CPP_RETURN_VAR)));
- code.replace(QLatin1String("%0"), QLatin1String(CPP_RETURN_VAR));
- }
-
- // Replace template variable for self Python object.
- QString pySelf = language == TypeSystem::NativeCode
- ? QLatin1String("pySelf") : QLatin1String("self");
- code.replace(QLatin1String("%PYSELF"), pySelf);
-
- // Replace template variable for a pointer to C++ of this object.
- if (func->implementingClass()) {
- QString replacement = func->isStatic() ? QLatin1String("%1::") : QLatin1String("%1->");
- QString cppSelf;
- if (func->isStatic())
- cppSelf = func->ownerClass()->qualifiedCppName();
- else if (language == TypeSystem::NativeCode)
- cppSelf = QLatin1String("this");
- else
- cppSelf = QLatin1String(CPP_SELF_VAR);
-
- // On comparison operator CPP_SELF_VAR is always a reference.
- if (func->isComparisonOperator())
- replacement = QLatin1String("%1.");
-
- if (func->isVirtual() && !func->isAbstract() && (!avoidProtectedHack() || !func->isProtected())) {
- QString methodCallArgs = getArgumentsFromMethodCall(code);
- if (!methodCallArgs.isEmpty()) {
- const QString pattern = QStringLiteral("%CPPSELF.%FUNCTION_NAME(%1)").arg(methodCallArgs);
- if (func->name() == QLatin1String("metaObject")) {
- QString wrapperClassName = wrapperName(func->ownerClass());
- QString cppSelfVar = avoidProtectedHack()
- ? QLatin1String("%CPPSELF")
- : QStringLiteral("reinterpret_cast<%1 *>(%CPPSELF)").arg(wrapperClassName);
- code.replace(pattern,
- QString::fromLatin1("(Shiboken::Object::hasCppWrapper(reinterpret_cast<SbkObject *>(%1))"
- " ? %2->::%3::%FUNCTION_NAME(%4)"
- " : %CPPSELF.%FUNCTION_NAME(%4))").arg(pySelf, cppSelfVar, wrapperClassName, methodCallArgs));
- } else {
- code.replace(pattern,
- QString::fromLatin1("(Shiboken::Object::hasCppWrapper(reinterpret_cast<SbkObject *>(%1))"
- " ? %CPPSELF->::%TYPE::%FUNCTION_NAME(%2)"
- " : %CPPSELF.%FUNCTION_NAME(%2))").arg(pySelf, methodCallArgs));
- }
- }
- }
-
- code.replace(QLatin1String("%CPPSELF."), replacement.arg(cppSelf));
- code.replace(QLatin1String("%CPPSELF"), cppSelf);
-
- if (code.indexOf(QLatin1String("%BEGIN_ALLOW_THREADS")) > -1) {
- if (code.count(QLatin1String("%BEGIN_ALLOW_THREADS")) == code.count(QLatin1String("%END_ALLOW_THREADS"))) {
- code.replace(QLatin1String("%BEGIN_ALLOW_THREADS"), QLatin1String(BEGIN_ALLOW_THREADS));
- code.replace(QLatin1String("%END_ALLOW_THREADS"), QLatin1String(END_ALLOW_THREADS));
- } else {
- qCWarning(lcShiboken) << "%BEGIN_ALLOW_THREADS and %END_ALLOW_THREADS mismatch";
- }
- }
-
- // replace template variable for the Python Type object for the
- // class implementing the method in which the code snip is written
- if (func->isStatic()) {
- code.replace(QLatin1String("%PYTHONTYPEOBJECT"),
- cpythonTypeName(func->implementingClass()) + QLatin1String("->type"));
- } else {
- code.replace(QLatin1String("%PYTHONTYPEOBJECT."), pySelf + QLatin1String("->ob_type->"));
- code.replace(QLatin1String("%PYTHONTYPEOBJECT"), pySelf + QLatin1String("->ob_type"));
- }
- }
-
- // Replaces template %ARGUMENT_NAMES and %# variables by argument variables and values.
- // Replaces template variables %# for individual arguments.
- const ArgumentVarReplacementList &argReplacements = getArgumentReplacement(func, usePyArgs, language, lastArg);
-
- QStringList args;
- for (const ArgumentVarReplacementPair &pair : argReplacements) {
- if (pair.second.startsWith(QLatin1String(CPP_ARG_REMOVED)))
- continue;
- args << pair.second;
- }
- code.replace(QLatin1String("%ARGUMENT_NAMES"), args.join(QLatin1String(", ")));
-
- for (const ArgumentVarReplacementPair &pair : argReplacements) {
- const AbstractMetaArgument *arg = pair.first;
- int idx = arg->argumentIndex() + 1;
- AbstractMetaType *type = arg->type();
- QString typeReplaced = func->typeReplaced(arg->argumentIndex() + 1);
- if (!typeReplaced.isEmpty()) {
- AbstractMetaType *builtType = buildAbstractMetaTypeFromString(typeReplaced);
- if (builtType)
- type = builtType;
- }
- if (isWrapperType(type)) {
- QString replacement = pair.second;
- if (type->referenceType() == LValueReference && !isPointer(type))
- replacement.remove(0, 1);
- if (type->referenceType() == LValueReference || isPointer(type))
- code.replace(QString::fromLatin1("%%1.").arg(idx), replacement + QLatin1String("->"));
- }
- code.replace(placeHolderRegex(idx), pair.second);
- }
-
- if (language == TypeSystem::NativeCode) {
- // Replaces template %PYTHON_ARGUMENTS variable with a pointer to the Python tuple
- // containing the converted virtual method arguments received from C++ to be passed
- // to the Python override.
- code.replace(QLatin1String("%PYTHON_ARGUMENTS"), QLatin1String(PYTHON_ARGS));
-
- // replace variable %PYTHON_METHOD_OVERRIDE for a pointer to the Python method
- // override for the C++ virtual method in which this piece of code was inserted
- code.replace(QLatin1String("%PYTHON_METHOD_OVERRIDE"), QLatin1String(PYTHON_OVERRIDE_VAR));
- }
-
- if (avoidProtectedHack()) {
- // If the function being processed was added by the user via type system,
- // Shiboken needs to find out if there are other overloads for the same method
- // name and if any of them is of the protected visibility. This is used to replace
- // calls to %FUNCTION_NAME on user written custom code for calls to the protected
- // dispatcher.
- bool hasProtectedOverload = false;
- if (func->isUserAdded()) {
- const AbstractMetaFunctionList &funcs = getFunctionOverloads(func->ownerClass(), func->name());
- for (const AbstractMetaFunction *f : funcs)
- hasProtectedOverload |= f->isProtected();
- }
-
- if (func->isProtected() || hasProtectedOverload) {
- code.replace(QLatin1String("%TYPE::%FUNCTION_NAME"),
- QStringLiteral("%1::%2_protected")
- .arg(wrapperName(func->ownerClass()), func->originalName()));
- code.replace(QLatin1String("%FUNCTION_NAME"),
- func->originalName() + QLatin1String("_protected"));
- }
- }
-
- if (func->isConstructor() && shouldGenerateCppWrapper(func->ownerClass()))
- code.replace(QLatin1String("%TYPE"), wrapperName(func->ownerClass()));
-
- if (func->ownerClass())
- code.replace(QLatin1String("%CPPTYPE"), func->ownerClass()->name());
-
- replaceTemplateVariables(code, func);
-
- processCodeSnip(code);
- s << INDENT << "// Begin code injection\n";
- s << code;
- s << INDENT << "// End of code injection\n";
-}
-
-// Returns true if the string is an expression,
-// and false if it is a variable.
-static bool isVariable(const QString &code)
-{
- static const QRegularExpression expr(QStringLiteral("^\\s*\\*?\\s*[A-Za-z_][A-Za-z_0-9.]*\\s*(?:\\[[^\\[]+\\])*$"));
- Q_ASSERT(expr.isValid());
- return expr.match(code.trimmed()).hasMatch();
-}
-
-// A miniature normalizer that puts a type string into a format
-// suitable for comparison with AbstractMetaType::cppSignature()
-// result.
-static QString miniNormalizer(const QString &varType)
-{
- QString normalized = varType.trimmed();
- if (normalized.isEmpty())
- return normalized;
- if (normalized.startsWith(QLatin1String("::")))
- normalized.remove(0, 2);
- QString suffix;
- while (normalized.endsWith(QLatin1Char('*')) || normalized.endsWith(QLatin1Char('&'))) {
- suffix.prepend(normalized.at(normalized.count() - 1));
- normalized.chop(1);
- normalized = normalized.trimmed();
- }
- const QString result = normalized + QLatin1Char(' ') + suffix;
- return result.trimmed();
-}
-// The position must indicate the first character after the opening '('.
-// ATTENTION: do not modify this function to trim any resulting string!
-// This must be done elsewhere.
-static QString getConverterTypeSystemVariableArgument(const QString &code, int pos)
-{
- QString arg;
- int parenthesisDepth = 0;
- int count = 0;
- while (pos + count < code.count()) {
- char c = code.at(pos+count).toLatin1(); // toAscii is gone
- if (c == '(') {
- ++parenthesisDepth;
- } else if (c == ')') {
- if (parenthesisDepth == 0) {
- arg = code.mid(pos, count).trimmed();
- break;
- }
- --parenthesisDepth;
- }
- ++count;
- }
- if (parenthesisDepth != 0)
- qFatal("Unbalanced parenthesis on type system converter variable call.");
- return arg;
-}
-using StringPair = QPair<QString, QString>;
-
-void ShibokenGenerator::replaceConverterTypeSystemVariable(TypeSystemConverterVariable converterVariable, QString &code)
-{
- QVector<StringPair> replacements;
- QRegularExpressionMatchIterator rit = m_typeSystemConvRegEx[converterVariable].globalMatch(code);
- while (rit.hasNext()) {
- const QRegularExpressionMatch match = rit.next();
- const QStringList list = match.capturedTexts();
- QString conversionString = list.constFirst();
- const QString &conversionTypeName = list.constLast();
- QString message;
- const AbstractMetaType *conversionType = buildAbstractMetaTypeFromString(conversionTypeName, &message);
- if (!conversionType) {
- qFatal("%s", qPrintable(msgCannotFindType(conversionTypeName,
- m_typeSystemConvName[converterVariable],
- message)));
- }
- QString conversion;
- QTextStream c(&conversion);
- switch (converterVariable) {
- case TypeSystemToCppFunction: {
- int end = match.capturedStart();
- int start = end;
- while (start > 0 && code.at(start) != QLatin1Char('\n'))
- --start;
- while (code.at(start).isSpace())
- ++start;
- QString varType = code.mid(start, end - start);
- conversionString = varType + list.constFirst();
- varType = miniNormalizer(varType);
- QString varName = list.at(1).trimmed();
- if (!varType.isEmpty()) {
- const QString conversionSignature = conversionType->cppSignature();
- if (varType != QLatin1String("auto") && varType != conversionSignature)
- qFatal("%s", qPrintable(msgConversionTypesDiffer(varType, conversionSignature)));
- c << getFullTypeName(conversionType) << ' ' << varName;
- writeMinimalConstructorExpression(c, conversionType);
- c << ";\n";
- Indentation indent(INDENT);
- c << INDENT;
- }
- c << cpythonToCppConversionFunction(conversionType);
- QString prefix;
- if (varName.startsWith(QLatin1Char('*'))) {
- varName.remove(0, 1);
- varName = varName.trimmed();
- } else {
- prefix = QLatin1Char('&');
- }
- QString arg = getConverterTypeSystemVariableArgument(code, match.capturedEnd());
- conversionString += arg;
- c << arg << ", " << prefix << '(' << varName << ')';
- break;
- }
- case TypeSystemCheckFunction:
- conversion = cpythonCheckFunction(conversionType);
- if (conversionType->typeEntry()->isPrimitive()
- && (conversionType->typeEntry()->name() == QLatin1String("PyObject")
- || !conversion.endsWith(QLatin1Char(' ')))) {
- c << '(';
- break;
- }
- Q_FALLTHROUGH();
- case TypeSystemIsConvertibleFunction:
- if (conversion.isEmpty())
- conversion = cpythonIsConvertibleFunction(conversionType);
- Q_FALLTHROUGH();
- case TypeSystemToPythonFunction:
- if (conversion.isEmpty())
- conversion = cpythonToPythonConversionFunction(conversionType);
- Q_FALLTHROUGH();
- default: {
- QString arg = getConverterTypeSystemVariableArgument(code, match.capturedEnd());
- conversionString += arg;
- if (converterVariable == TypeSystemToPythonFunction && !isVariable(arg)) {
- qFatal("Only variables are acceptable as argument to %%CONVERTTOPYTHON type system variable on code snippet: '%s'",
- qPrintable(code));
- }
- if (conversion.contains(QLatin1String("%in"))) {
- conversion.prepend(QLatin1Char('('));
- conversion.replace(QLatin1String("%in"), arg);
- } else {
- c << arg;
- }
- }
- }
- replacements.append(qMakePair(conversionString, conversion));
- }
- for (const StringPair &rep : qAsConst(replacements))
- code.replace(rep.first, rep.second);
-}
-
-bool ShibokenGenerator::injectedCodeUsesPySelf(const AbstractMetaFunction *func)
-{
- CodeSnipList snips = func->injectedCodeSnips(TypeSystem::CodeSnipPositionAny, TypeSystem::NativeCode);
- for (const CodeSnip &snip : qAsConst(snips)) {
- if (snip.code().contains(QLatin1String("%PYSELF")))
- return true;
- }
- return false;
-}
-
-bool ShibokenGenerator::injectedCodeCallsCppFunction(const GeneratorContext &context,
- const AbstractMetaFunction *func)
-{
- QString funcCall = func->originalName() + QLatin1Char('(');
- QString wrappedCtorCall;
- if (func->isConstructor()) {
- funcCall.prepend(QLatin1String("new "));
- const auto owner = func->ownerClass();
- const QString className = context.useWrapper()
- ? context.wrapperName() : owner->qualifiedCppName();
- wrappedCtorCall = QLatin1String("new ") + className + QLatin1Char('(');
- }
- CodeSnipList snips = func->injectedCodeSnips(TypeSystem::CodeSnipPositionAny, TypeSystem::TargetLangCode);
- for (const CodeSnip &snip : qAsConst(snips)) {
- if (snip.code().contains(QLatin1String("%FUNCTION_NAME(")) || snip.code().contains(funcCall)
- || (func->isConstructor()
- && ((func->ownerClass()->isPolymorphic() && snip.code().contains(wrappedCtorCall))
- || snip.code().contains(QLatin1String("new %TYPE("))))
- )
- return true;
- }
- return false;
-}
-
-bool ShibokenGenerator::injectedCodeCallsPythonOverride(const AbstractMetaFunction *func)
-{
- static const QRegularExpression overrideCallRegexCheck(QStringLiteral("PyObject_Call\\s*\\(\\s*%PYTHON_METHOD_OVERRIDE\\s*,"));
- Q_ASSERT(overrideCallRegexCheck.isValid());
- CodeSnipList snips = func->injectedCodeSnips(TypeSystem::CodeSnipPositionAny, TypeSystem::NativeCode);
- for (const CodeSnip &snip : qAsConst(snips)) {
- if (snip.code().contains(overrideCallRegexCheck))
- return true;
- }
- return false;
-}
-
-bool ShibokenGenerator::injectedCodeHasReturnValueAttribution(const AbstractMetaFunction *func, TypeSystem::Language language)
-{
- static const QRegularExpression retValAttributionRegexCheck_native(QStringLiteral("%0\\s*=[^=]\\s*.+"));
- Q_ASSERT(retValAttributionRegexCheck_native.isValid());
- static const QRegularExpression retValAttributionRegexCheck_target(QStringLiteral("%PYARG_0\\s*=[^=]\\s*.+"));
- Q_ASSERT(retValAttributionRegexCheck_target.isValid());
- CodeSnipList snips = func->injectedCodeSnips(TypeSystem::CodeSnipPositionAny, language);
- for (const CodeSnip &snip : qAsConst(snips)) {
- if (language == TypeSystem::TargetLangCode) {
- if (snip.code().contains(retValAttributionRegexCheck_target))
- return true;
- } else {
- if (snip.code().contains(retValAttributionRegexCheck_native))
- return true;
- }
- }
- return false;
-}
-
-bool ShibokenGenerator::injectedCodeUsesArgument(const AbstractMetaFunction *func, int argumentIndex)
-{
- CodeSnipList snips = func->injectedCodeSnips(TypeSystem::CodeSnipPositionAny);
- const QRegularExpression argRegEx = placeHolderRegex(argumentIndex + 1);
- for (const CodeSnip &snip : qAsConst(snips)) {
- QString code = snip.code();
- if (code.contains(QLatin1String("%ARGUMENT_NAMES")) || code.contains(argRegEx))
- return true;
- }
- return false;
-}
-
-bool ShibokenGenerator::useOverrideCaching(const AbstractMetaClass *metaClass)
-{
- return metaClass->isPolymorphic();
-}
-
-ShibokenGenerator::AttroCheck ShibokenGenerator::checkAttroFunctionNeeds(const AbstractMetaClass *metaClass) const
-{
- AttroCheck result;
- if (metaClass->typeEntry()->isSmartPointer()) {
- result |= AttroCheckFlag::GetattroSmartPointer | AttroCheckFlag::SetattroSmartPointer;
- } else {
- if (getGeneratorClassInfo(metaClass).needsGetattroFunction)
- result |= AttroCheckFlag::GetattroOverloads;
- if (metaClass->queryFirstFunction(metaClass->functions(),
- AbstractMetaClass::GetAttroFunction)) {
- result |= AttroCheckFlag::GetattroUser;
- }
- if (usePySideExtensions() && metaClass->qualifiedCppName() == QLatin1String("QObject"))
- result |= AttroCheckFlag::SetattroQObject;
- if (useOverrideCaching(metaClass))
- result |= AttroCheckFlag::SetattroMethodOverride;
- if (metaClass->queryFirstFunction(metaClass->functions(),
- AbstractMetaClass::SetAttroFunction)) {
- result |= AttroCheckFlag::SetattroUser;
- }
- // PYSIDE-1255: If setattro is generated for a class inheriting
- // QObject, the property code needs to be generated, too.
- if ((result & AttroCheckFlag::SetattroMask) != 0
- && !result.testFlag(AttroCheckFlag::SetattroQObject)
- && metaClass->isQObject()) {
- result |= AttroCheckFlag::SetattroQObject;
- }
- }
- return result;
-}
-
-bool ShibokenGenerator::classNeedsGetattroFunctionImpl(const AbstractMetaClass *metaClass)
-{
- if (!metaClass)
- return false;
- if (metaClass->typeEntry()->isSmartPointer())
- return true;
- const auto &functionGroup = getFunctionGroups(metaClass);
- for (auto it = functionGroup.cbegin(), end = functionGroup.cend(); it != end; ++it) {
- AbstractMetaFunctionList overloads;
- for (AbstractMetaFunction *func : qAsConst(it.value())) {
- if (func->isAssignmentOperator() || func->isCastOperator() || func->isModifiedRemoved()
- || func->isPrivate() || func->ownerClass() != func->implementingClass()
- || func->isConstructor() || func->isOperatorOverload())
- continue;
- overloads.append(func);
- }
- if (overloads.isEmpty())
- continue;
- if (OverloadData::hasStaticAndInstanceFunctions(overloads))
- return true;
- }
- return false;
-}
-
-AbstractMetaFunctionList ShibokenGenerator::getMethodsWithBothStaticAndNonStaticMethods(const AbstractMetaClass *metaClass)
-{
- AbstractMetaFunctionList methods;
- if (metaClass) {
- const auto &functionGroups = getFunctionGroups(metaClass);
- for (auto it = functionGroups.cbegin(), end = functionGroups.cend(); it != end; ++it) {
- AbstractMetaFunctionList overloads;
- for (AbstractMetaFunction *func : qAsConst(it.value())) {
- if (func->isAssignmentOperator() || func->isCastOperator() || func->isModifiedRemoved()
- || func->isPrivate() || func->ownerClass() != func->implementingClass()
- || func->isConstructor() || func->isOperatorOverload())
- continue;
- overloads.append(func);
- }
- if (overloads.isEmpty())
- continue;
- if (OverloadData::hasStaticAndInstanceFunctions(overloads))
- methods.append(overloads.constFirst());
- }
- }
- return methods;
-}
-
-AbstractMetaClassList ShibokenGenerator::getBaseClasses(const AbstractMetaClass *metaClass) const
-{
- AbstractMetaClassList baseClasses;
- if (metaClass) {
- QStringList baseClassNames(metaClass->baseClassNames());
- const QString defaultSuperclass = metaClass->typeEntry()->defaultSuperclass();
- if (!defaultSuperclass.isEmpty()) {
- int index = baseClassNames.indexOf(defaultSuperclass);
- if (index >= 0)
- baseClassNames.move(index, 0);
- }
- for (const QString &parent : baseClassNames) {
- AbstractMetaClass *clazz = AbstractMetaClass::findClass(classes(), parent);
- if (clazz)
- baseClasses << clazz;
- }
- }
- return baseClasses;
-}
-
-const AbstractMetaClass *ShibokenGenerator::getMultipleInheritingClass(const AbstractMetaClass *metaClass)
-{
- if (!metaClass || metaClass->baseClassNames().isEmpty())
- return nullptr;
- if (metaClass->baseClassNames().size() > 1)
- return metaClass;
- return getMultipleInheritingClass(metaClass->baseClass());
-}
-
-AbstractMetaClassList ShibokenGenerator::getAllAncestors(const AbstractMetaClass *metaClass) const
-{
- AbstractMetaClassList result;
- if (metaClass) {
- AbstractMetaClassList baseClasses = getBaseClasses(metaClass);
- for (AbstractMetaClass *base : qAsConst(baseClasses)) {
- result.append(base);
- result.append(getAllAncestors(base));
- }
- }
- return result;
-}
-
-QString ShibokenGenerator::getModuleHeaderFileName(const QString &moduleName) const
-{
- return moduleCppPrefix(moduleName).toLower() + QLatin1String("_python.h");
-}
-
-bool ShibokenGenerator::isCopyable(const AbstractMetaClass *metaClass)
-
-{
- if (metaClass->isNamespace() || isObjectType(metaClass))
- return false;
- if (metaClass->typeEntry()->copyable() == ComplexTypeEntry::Unknown)
- return metaClass->hasCloneOperator();
-
- return metaClass->typeEntry()->copyable() == ComplexTypeEntry::CopyableSet;
-}
-
-AbstractMetaType *ShibokenGenerator::buildAbstractMetaTypeFromString(QString typeSignature,
- QString *errorMessage)
-{
- typeSignature = typeSignature.trimmed();
- if (typeSignature.startsWith(QLatin1String("::")))
- typeSignature.remove(0, 2);
-
- auto it = m_metaTypeFromStringCache.find(typeSignature);
- if (it == m_metaTypeFromStringCache.end()) {
- AbstractMetaType *metaType =
- AbstractMetaBuilder::translateType(typeSignature, nullptr, {}, errorMessage);
- if (Q_UNLIKELY(!metaType)) {
- if (errorMessage)
- errorMessage->prepend(msgCannotBuildMetaType(typeSignature));
- return nullptr;
- }
- it = m_metaTypeFromStringCache.insert(typeSignature, metaType);
- }
- return it.value();
-}
-
-AbstractMetaType *ShibokenGenerator::buildAbstractMetaTypeFromTypeEntry(const TypeEntry *typeEntry)
-{
- QString typeName = typeEntry->qualifiedCppName();
- if (typeName.startsWith(QLatin1String("::")))
- typeName.remove(0, 2);
- if (m_metaTypeFromStringCache.contains(typeName))
- return m_metaTypeFromStringCache.value(typeName);
- auto *metaType = new AbstractMetaType;
- metaType->setTypeEntry(typeEntry);
- metaType->clearIndirections();
- metaType->setReferenceType(NoReference);
- metaType->setConstant(false);
- metaType->decideUsagePattern();
- m_metaTypeFromStringCache.insert(typeName, metaType);
- return metaType;
-}
-AbstractMetaType *ShibokenGenerator::buildAbstractMetaTypeFromAbstractMetaClass(const AbstractMetaClass *metaClass)
-{
- return ShibokenGenerator::buildAbstractMetaTypeFromTypeEntry(metaClass->typeEntry());
-}
-
-/*
-static void dumpFunction(AbstractMetaFunctionList lst)
-{
- qDebug() << "DUMP FUNCTIONS: ";
- for (AbstractMetaFunction *func : qAsConst(lst))
- qDebug() << "*" << func->ownerClass()->name()
- << func->signature()
- << "Private: " << func->isPrivate()
- << "Empty: " << func->isEmptyFunction()
- << "Static:" << func->isStatic()
- << "Signal:" << func->isSignal()
- << "ClassImplements: " << (func->ownerClass() != func->implementingClass())
- << "is operator:" << func->isOperatorOverload()
- << "is global:" << func->isInGlobalScope();
-}
-*/
-
-static bool isGroupable(const AbstractMetaFunction *func)
-{
- switch (func->functionType()) {
- case AbstractMetaFunction::DestructorFunction:
- case AbstractMetaFunction::SignalFunction:
- case AbstractMetaFunction::GetAttroFunction:
- case AbstractMetaFunction::SetAttroFunction:
- return false;
- default:
- break;
- }
- if (func->isModifiedRemoved() && !func->isAbstract())
- return false;
- // weird operator overloads
- if (func->name() == QLatin1String("operator[]") || func->name() == QLatin1String("operator->")) // FIXME: what about cast operators?
- return false;
- return true;
-}
-
-ShibokenGenerator::FunctionGroups ShibokenGenerator::getGlobalFunctionGroups() const
-{
- const AbstractMetaFunctionList &lst = globalFunctions();
- FunctionGroups results;
- for (AbstractMetaFunction *func : lst) {
- if (isGroupable(func))
- results[func->name()].append(func);
- }
- return results;
-}
-
-const GeneratorClassInfoCacheEntry &ShibokenGenerator::getGeneratorClassInfo(const AbstractMetaClass *scope)
-{
- auto cache = generatorClassInfoCache();
- auto it = cache->find(scope);
- if (it == cache->end()) {
- it = cache->insert(scope, {});
- it.value().functionGroups = getFunctionGroupsImpl(scope);
- it.value().needsGetattroFunction = classNeedsGetattroFunctionImpl(scope);
- }
- return it.value();
-}
-
-ShibokenGenerator::FunctionGroups ShibokenGenerator::getFunctionGroups(const AbstractMetaClass *scope)
-{
- Q_ASSERT(scope);
- return getGeneratorClassInfo(scope).functionGroups;
-}
-
-ShibokenGenerator::FunctionGroups ShibokenGenerator::getFunctionGroupsImpl(const AbstractMetaClass *scope)
-{
- const AbstractMetaFunctionList &lst = scope->functions();
-
- FunctionGroups results;
- for (AbstractMetaFunction *func : lst) {
- if (isGroupable(func)) {
- auto it = results.find(func->name());
- if (it == results.end()) {
- results.insert(func->name(), AbstractMetaFunctionList(1, func));
- } else {
- // If there are virtuals methods in the mix (PYSIDE-570,
- // QFileSystemModel::index(QString,int) and
- // QFileSystemModel::index(int,int,QModelIndex)) override, make sure
- // the overriding method of the most-derived class is seen first
- // and inserted into the "seenSignatures" set.
- if (func->isVirtual())
- it.value().prepend(func);
- else
- it.value().append(func);
- }
- }
- }
- return results;
-}
-
-AbstractMetaFunctionList ShibokenGenerator::getInheritedOverloads(const AbstractMetaFunction *func, QSet<QString> *seen)
-{
- AbstractMetaFunctionList results;
- AbstractMetaClass *basis;
- if (func->ownerClass() && (basis = func->ownerClass()->baseClass())) {
- for (; basis; basis = basis->baseClass()) {
- const AbstractMetaFunction *inFunc = basis->findFunction(func->name());
- if (inFunc && !seen->contains(inFunc->minimalSignature())) {
- seen->insert(inFunc->minimalSignature());
- AbstractMetaFunction *newFunc = inFunc->copy();
- newFunc->setImplementingClass(func->implementingClass());
- results << newFunc;
- }
- }
- }
- return results;
-}
-
-AbstractMetaFunctionList ShibokenGenerator::getFunctionAndInheritedOverloads(const AbstractMetaFunction *func, QSet<QString> *seen)
-{
- AbstractMetaFunctionList results;
- seen->insert(func->minimalSignature());
- results << const_cast<AbstractMetaFunction *>(func) << getInheritedOverloads(func, seen);
- return results;
-}
-
-AbstractMetaFunctionList ShibokenGenerator::getFunctionOverloads(const AbstractMetaClass *scope, const QString &functionName)
-{
- AbstractMetaFunctionList lst = scope ? scope->functions() : globalFunctions();
-
- AbstractMetaFunctionList results;
- QSet<QString> seenSignatures;
- for (AbstractMetaFunction *func : qAsConst(lst)) {
- if (func->name() != functionName)
- continue;
- if (isGroupable(func)) {
- // PYSIDE-331: look also into base classes.
- results << getFunctionAndInheritedOverloads(func, &seenSignatures);
- }
- }
- return results;
-}
-
-Generator::OptionDescriptions ShibokenGenerator::options() const
-{
- return OptionDescriptions()
- << qMakePair(QLatin1String(AVOID_PROTECTED_HACK),
- QLatin1String("Avoid the use of the '#define protected public' hack."))
- << qMakePair(QLatin1String(DISABLE_VERBOSE_ERROR_MESSAGES),
- QLatin1String("Disable verbose error messages. Turn the python code hard to debug\n"
- "but safe few kB on the generated bindings."))
- << qMakePair(QLatin1String(PARENT_CTOR_HEURISTIC),
- QLatin1String("Enable heuristics to detect parent relationship on constructors."))
- << qMakePair(QLatin1String(ENABLE_PYSIDE_EXTENSIONS),
- QLatin1String("Enable PySide extensions, such as support for signal/slots,\n"
- "use this if you are creating a binding for a Qt-based library."))
- << qMakePair(QLatin1String(RETURN_VALUE_HEURISTIC),
- QLatin1String("Enable heuristics to detect parent relationship on return values\n"
- "(USE WITH CAUTION!)"))
- << qMakePair(QLatin1String(USE_ISNULL_AS_NB_NONZERO),
- QLatin1String("If a class have an isNull() const method, it will be used to compute\n"
- "the value of boolean casts"))
- << qMakePair(QLatin1String(WRAPPER_DIAGNOSTICS),
- QLatin1String("Generate diagnostic code around wrappers"));
-}
-
-bool ShibokenGenerator::handleOption(const QString &key, const QString & /* value */)
-{
- if (key == QLatin1String(PARENT_CTOR_HEURISTIC))
- return (m_useCtorHeuristic = true);
- if (key == QLatin1String(ENABLE_PYSIDE_EXTENSIONS))
- return (m_usePySideExtensions = true);
- if (key == QLatin1String(RETURN_VALUE_HEURISTIC))
- return (m_userReturnValueHeuristic = true);
- if (key == QLatin1String(DISABLE_VERBOSE_ERROR_MESSAGES))
- return (m_verboseErrorMessagesDisabled = true);
- if (key == QLatin1String(USE_ISNULL_AS_NB_NONZERO))
- return (m_useIsNullAsNbNonZero = true);
- if (key == QLatin1String(AVOID_PROTECTED_HACK))
- return (m_avoidProtectedHack = true);
- if (key == QLatin1String(WRAPPER_DIAGNOSTICS))
- return (m_wrapperDiagnostics = true);
- return false;
-}
-
-static void getCode(QStringList &code, const CodeSnipList &codeSnips)
-{
- for (const CodeSnip &snip : qAsConst(codeSnips))
- code.append(snip.code());
-}
-
-static void getCode(QStringList &code, const TypeEntry *type)
-{
- getCode(code, type->codeSnips());
-
- CustomConversion *customConversion = type->customConversion();
- if (!customConversion)
- return;
-
- if (!customConversion->nativeToTargetConversion().isEmpty())
- code.append(customConversion->nativeToTargetConversion());
-
- const CustomConversion::TargetToNativeConversions &toCppConversions = customConversion->targetToNativeConversions();
- if (toCppConversions.isEmpty())
- return;
-
- for (CustomConversion::TargetToNativeConversion *toNative : qAsConst(toCppConversions))
- code.append(toNative->conversion());
-}
-
-bool ShibokenGenerator::doSetup()
-{
- QStringList snips;
- const PrimitiveTypeEntryList &primitiveTypeList = primitiveTypes();
- for (const PrimitiveTypeEntry *type : primitiveTypeList)
- getCode(snips, type);
- const ContainerTypeEntryList &containerTypeList = containerTypes();
- for (const ContainerTypeEntry *type : containerTypeList)
- getCode(snips, type);
- const AbstractMetaClassList &classList = classes();
- for (const AbstractMetaClass *metaClass : classList)
- getCode(snips, metaClass->typeEntry());
-
- const TypeSystemTypeEntry *moduleEntry = TypeDatabase::instance()->defaultTypeSystemType();
- Q_ASSERT(moduleEntry);
- getCode(snips, moduleEntry);
-
- const auto &functionGroups = getGlobalFunctionGroups();
- for (auto it = functionGroups.cbegin(), end = functionGroups.cend(); it != end; ++it) {
- for (AbstractMetaFunction *func : it.value())
- getCode(snips, func->injectedCodeSnips());
- }
-
- for (const QString &code : qAsConst(snips)) {
- collectContainerTypesFromConverterMacros(code, true);
- collectContainerTypesFromConverterMacros(code, false);
- }
-
- return true;
-}
-
-void ShibokenGenerator::collectContainerTypesFromConverterMacros(const QString &code, bool toPythonMacro)
-{
- QString convMacro = toPythonMacro ? QLatin1String("%CONVERTTOPYTHON[") : QLatin1String("%CONVERTTOCPP[");
- int offset = toPythonMacro ? sizeof("%CONVERTTOPYTHON") : sizeof("%CONVERTTOCPP");
- int start = 0;
- QString errorMessage;
- while ((start = code.indexOf(convMacro, start)) != -1) {
- int end = code.indexOf(QLatin1Char(']'), start);
- start += offset;
- if (code.at(start) != QLatin1Char('%')) {
- QString typeString = code.mid(start, end - start);
- if (AbstractMetaType *type =
- buildAbstractMetaTypeFromString(typeString, &errorMessage)) {
- addInstantiatedContainersAndSmartPointers(type, type->originalTypeDescription());
- } else {
- qFatal("%s: Cannot translate type \"%s\": %s", __FUNCTION__,
- qPrintable(typeString), qPrintable(errorMessage));
- }
- }
- start = end;
- }
-}
-
-bool ShibokenGenerator::useCtorHeuristic() const
-{
- return m_useCtorHeuristic;
-}
-
-bool ShibokenGenerator::useReturnValueHeuristic() const
-{
- return m_userReturnValueHeuristic;
-}
-
-bool ShibokenGenerator::usePySideExtensions() const
-{
- return m_usePySideExtensions;
-}
-
-bool ShibokenGenerator::useIsNullAsNbNonZero() const
-{
- return m_useIsNullAsNbNonZero;
-}
-
-bool ShibokenGenerator::avoidProtectedHack() const
-{
- return m_avoidProtectedHack;
-}
-
-QString ShibokenGenerator::moduleCppPrefix(const QString &moduleName) const
- {
- QString result = moduleName.isEmpty() ? packageName() : moduleName;
- result.replace(QLatin1Char('.'), QLatin1Char('_'));
- return result;
-}
-
-QString ShibokenGenerator::cppApiVariableName(const QString &moduleName) const
-{
- return QLatin1String("Sbk") + moduleCppPrefix(moduleName)
- + QLatin1String("Types");
-}
-
-QString ShibokenGenerator::pythonModuleObjectName(const QString &moduleName) const
-{
- return QLatin1String("Sbk") + moduleCppPrefix(moduleName)
- + QLatin1String("ModuleObject");
-}
-
-QString ShibokenGenerator::convertersVariableName(const QString &moduleName) const
-{
- QString result = cppApiVariableName(moduleName);
- result.chop(1);
- result.append(QLatin1String("Converters"));
- return result;
-}
-
-static QString processInstantiationsVariableName(const AbstractMetaType *type)
-{
- QString res = QLatin1Char('_') + _fixedCppTypeName(type->typeEntry()->qualifiedCppName()).toUpper();
- const AbstractMetaTypeList &instantiations = type->instantiations();
- for (const AbstractMetaType *instantiation : instantiations) {
- res += instantiation->isContainer()
- ? processInstantiationsVariableName(instantiation)
- : QLatin1Char('_') + _fixedCppTypeName(instantiation->cppSignature()).toUpper();
- }
- return res;
-}
-
-static void appendIndexSuffix(QString *s)
-{
- if (!s->endsWith(QLatin1Char('_')))
- s->append(QLatin1Char('_'));
- s->append(QStringLiteral("IDX"));
-}
-
-QString ShibokenGenerator::getTypeIndexVariableName(const AbstractMetaClass *metaClass,
- bool alternativeTemplateName) const
-{
- if (alternativeTemplateName) {
- const AbstractMetaClass *templateBaseClass = metaClass->templateBaseClass();
- if (!templateBaseClass)
- return QString();
- QString result = QLatin1String("SBK_")
- + _fixedCppTypeName(templateBaseClass->typeEntry()->qualifiedCppName()).toUpper();
- const AbstractMetaTypeList &templateBaseClassInstantiations = metaClass->templateBaseClassInstantiations();
- for (const AbstractMetaType *instantiation : templateBaseClassInstantiations)
- result += processInstantiationsVariableName(instantiation);
- appendIndexSuffix(&result);
- return result;
- }
- return getTypeIndexVariableName(metaClass->typeEntry());
-}
-QString ShibokenGenerator::getTypeIndexVariableName(const TypeEntry *type) const
-{
- if (type->isCppPrimitive()) {
- const auto *trueType = static_cast<const PrimitiveTypeEntry *>(type);
- if (trueType->basicReferencedTypeEntry())
- type = trueType->basicReferencedTypeEntry();
- }
- QString result = QLatin1String("SBK_");
- // Disambiguate namespaces per module to allow for extending them.
- if (type->isNamespace()) {
- QString package = type->targetLangPackage();
- const int dot = package.lastIndexOf(QLatin1Char('.'));
- result += package.rightRef(package.size() - (dot + 1));
- }
- result += _fixedCppTypeName(type->qualifiedCppName()).toUpper();
- appendIndexSuffix(&result);
- return result;
-}
-QString ShibokenGenerator::getTypeIndexVariableName(const AbstractMetaType *type) const
-{
- QString result = QLatin1String("SBK");
- if (type->typeEntry()->isContainer())
- result += QLatin1Char('_') + moduleName().toUpper();
- result += processInstantiationsVariableName(type);
- appendIndexSuffix(&result);
- return result;
-}
-
-bool ShibokenGenerator::verboseErrorMessagesDisabled() const
-{
- return m_verboseErrorMessagesDisabled;
-}
-
-bool ShibokenGenerator::pythonFunctionWrapperUsesListOfArguments(const OverloadData &overloadData)
-{
- if (overloadData.referenceFunction()->isCallOperator())
- return true;
- if (overloadData.referenceFunction()->isOperatorOverload())
- return false;
- int maxArgs = overloadData.maxArgs();
- int minArgs = overloadData.minArgs();
- return (minArgs != maxArgs)
- || (maxArgs > 1)
- || overloadData.referenceFunction()->isConstructor()
- || overloadData.hasArgumentWithDefaultValue();
-}
-
-void ShibokenGenerator::writeMinimalConstructorExpression(QTextStream &s, const AbstractMetaType *type, const QString &defaultCtor)
-{
- if (!defaultCtor.isEmpty()) {
- s << " = " << defaultCtor;
- return;
- }
- if (isCppPrimitive(type) || type->isSmartPointer())
- return;
- const auto ctor = minimalConstructor(type);
- if (ctor.isValid()) {
- s << ctor.initialization();
- } else {
- const QString message = msgCouldNotFindMinimalConstructor(QLatin1String(__FUNCTION__), type->cppSignature());
- qCWarning(lcShiboken()).noquote() << message;
- s << ";\n#error " << message << '\n';
- }
-}
-
-void ShibokenGenerator::writeMinimalConstructorExpression(QTextStream &s, const TypeEntry *type, const QString &defaultCtor)
-{
- if (!defaultCtor.isEmpty()) {
- s << " = " << defaultCtor;
- return;
- }
- if (isCppPrimitive(type))
- return;
- const auto ctor = minimalConstructor(type);
- if (ctor.isValid()) {
- s << ctor.initialization();
- } else {
- const QString message = msgCouldNotFindMinimalConstructor(QLatin1String(__FUNCTION__), type->qualifiedCppName());
- qCWarning(lcShiboken()).noquote() << message;
- s << ";\n#error " << message << Qt::endl;
- }
-}
-
-bool ShibokenGenerator::isCppIntegralPrimitive(const TypeEntry *type)
-{
- if (!type->isCppPrimitive())
- return false;
- const auto *trueType = static_cast<const PrimitiveTypeEntry *>(type);
- if (trueType->basicReferencedTypeEntry())
- trueType = trueType->basicReferencedTypeEntry();
- QString typeName = trueType->qualifiedCppName();
- return !typeName.contains(QLatin1String("double"))
- && !typeName.contains(QLatin1String("float"))
- && !typeName.contains(QLatin1String("wchar"));
-}
-bool ShibokenGenerator::isCppIntegralPrimitive(const AbstractMetaType *type)
-{
- return isCppIntegralPrimitive(type->typeEntry());
-}
-
-QString ShibokenGenerator::pythonArgsAt(int i)
-{
- return QLatin1String(PYTHON_ARGS) + QLatin1Char('[')
- + QString::number(i) + QLatin1Char(']');
-}
diff --git a/sources/shiboken2/generator/shiboken2/shibokengenerator.h b/sources/shiboken2/generator/shiboken2/shibokengenerator.h
deleted file mode 100644
index d8259d245..000000000
--- a/sources/shiboken2/generator/shiboken2/shibokengenerator.h
+++ /dev/null
@@ -1,573 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SHIBOKENGENERATOR_H
-#define SHIBOKENGENERATOR_H
-
-extern const char *CPP_ARG;
-extern const char *CPP_ARG_REMOVED;
-extern const char *CPP_RETURN_VAR;
-extern const char *CPP_SELF_VAR;
-extern const char *NULL_PTR;
-extern const char *PYTHON_ARG;
-extern const char *PYTHON_ARGS;
-extern const char *PYTHON_OVERRIDE_VAR;
-extern const char *PYTHON_RETURN_VAR;
-extern const char *PYTHON_TO_CPP_VAR;
-extern const char *SMART_POINTER_GETTER;
-
-extern const char *CONV_RULE_OUT_VAR_SUFFIX;
-extern const char *BEGIN_ALLOW_THREADS;
-extern const char *END_ALLOW_THREADS;
-
-#include <generator.h>
-
-#include "typesystem.h"
-
-#include <QtCore/QRegularExpression>
-
-class DocParser;
-class CodeSnip;
-class OverloadData;
-struct GeneratorClassInfoCacheEntry;
-
-QT_FORWARD_DECLARE_CLASS(QTextStream)
-
-/**
- * Abstract generator that contains common methods used in CppGenerator and HeaderGenerator.
- */
-class ShibokenGenerator : public Generator
-{
-public:
- enum class AttroCheckFlag
- {
- None = 0x0,
- GetattroOverloads = 0x01,
- GetattroSmartPointer = 0x02,
- GetattroUser = 0x04, // Injected code
- GetattroMask = 0x0F,
- SetattroQObject = 0x10,
- SetattroSmartPointer = 0x20,
- SetattroMethodOverride = 0x40,
- SetattroUser = 0x80, // Injected code
- SetattroMask = 0xF0,
- };
- Q_DECLARE_FLAGS(AttroCheck, AttroCheckFlag);
-
- using FunctionGroups = QMap<QString, AbstractMetaFunctionList>; // Sorted
-
- ShibokenGenerator();
- ~ShibokenGenerator() override;
-
- const char *name() const override { return "Shiboken"; }
-
- /// Returns a list of all ancestor classes for the given class.
- AbstractMetaClassList getAllAncestors(const AbstractMetaClass *metaClass) const;
-
-protected:
- bool doSetup() override;
-
- void writeArgumentNames(QTextStream &s,
- const AbstractMetaFunction *func,
- Options options = NoOption) const override;
-
- /**
- * Function used to write the fucntion arguments on the class buffer.
- * \param s the class output buffer
- * \param func the pointer to metafunction information
- * \param count the number of function arguments
- * \param options some extra options used during the parser
- */
- void writeFunctionArguments(QTextStream &s,
- const AbstractMetaFunction *func,
- Options options = NoOption) const override;
-
- GeneratorContext contextForClass(const AbstractMetaClass *c) const override;
-
- /**
- * Returns a map with all functions grouped, the function name is used as key.
- * Example of return value: { "foo" -> ["foo(int)", "foo(int, long)], "bar" -> "bar(double)"}
- * \param scope Where to search for functions, null means all global functions.
- */
- FunctionGroups getGlobalFunctionGroups() const;
- static FunctionGroups getFunctionGroups(const AbstractMetaClass *scope);
-
- /**
- * Returns all different inherited overloads of func, and includes func as well.
- * The function can be called multiple times without duplication.
- * \param func the metafunction to be searched in subclasses.
- * \param seen the function's minimal signatures already seen.
- */
- AbstractMetaFunctionList getFunctionAndInheritedOverloads(const AbstractMetaFunction *func, QSet<QString> *seen);
-
- /// Write user's custom code snippets at class or module level.
- void writeClassCodeSnips(QTextStream &s,
- const QVector<CodeSnip> & codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language,
- const GeneratorContext &context);
- void writeCodeSnips(QTextStream &s,
- const QVector<CodeSnip> & codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language);
- /// Write user's custom code snippets at function level.
- void writeCodeSnips(QTextStream &s,
- const QVector<CodeSnip> & codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language,
- const AbstractMetaFunction *func,
- const AbstractMetaArgument *lastArg = nullptr);
-
- /// Replaces variables for the user's custom code at global or class level.
- void processCodeSnip(QString &code);
- void processClassCodeSnip(QString &code, const GeneratorContext &context);
-
- /**
- * Verifies if any of the function's code injections of the "native"
- * type needs the type system variable "%PYSELF".
- * \param func the function to check
- * \return true if the function's native code snippets use "%PYSELF"
- */
- bool injectedCodeUsesPySelf(const AbstractMetaFunction *func);
-
- /**
- * Verifies if any of the function's code injections makes a call
- * to the C++ method. This is used by the generator to avoid writing calls
- * to C++ when the user custom code already does this.
- * \param func the function to check
- * \return true if the function's code snippets call the wrapped C++ function
- */
- bool injectedCodeCallsCppFunction(const GeneratorContext &context,
- const AbstractMetaFunction *func);
-
- /**
- * Verifies if any of the function's code injections of the "native" class makes a
- * call to the C++ method. This is used by the generator to avoid writing calls to
- * Python overrides of C++ virtual methods when the user custom code already does this.
- * \param func the function to check
- * \return true if the function's code snippets call the Python override for a C++ virtual method
- */
- bool injectedCodeCallsPythonOverride(const AbstractMetaFunction *func);
-
- /**
- * Verifies if any of the function's code injections attributes values to
- * the return variable (%0 or %PYARG_0).
- * \param func the function to check
- * \param language the kind of code snip
- * \return true if the function's code attributes values to "%0" or "%PYARG_0"
- */
- bool injectedCodeHasReturnValueAttribution(const AbstractMetaFunction *func, TypeSystem::Language language = TypeSystem::TargetLangCode);
-
- /**
- * Verifies if any of the function's code injections uses the type system variable
- * for function arguments of a given index.
- */
- bool injectedCodeUsesArgument(const AbstractMetaFunction *func, int argumentIndex);
-
- /**
- * Function which parse the metafunction information
- * \param func the function witch will be parserd
- * \param option some extra options
- * \param arg_count the number of function arguments
- */
- QString functionSignature(const AbstractMetaFunction *func,
- const QString &prepend = QString(),
- const QString &append = QString(),
- Options options = NoOption,
- int arg_count = -1) const;
-
- /// Returns the top-most class that has multiple inheritance in the ancestry.
- static const AbstractMetaClass *getMultipleInheritingClass(const AbstractMetaClass *metaClass);
-
- static bool useOverrideCaching(const AbstractMetaClass *metaClass);
- AttroCheck checkAttroFunctionNeeds(const AbstractMetaClass *metaClass) const;
-
- /// Returns a list of methods of the given class where each one is part of a different overload with both static and non-static method.
- AbstractMetaFunctionList getMethodsWithBothStaticAndNonStaticMethods(const AbstractMetaClass *metaClass);
-
- /// Returns a list of parent classes for a given class.
- AbstractMetaClassList getBaseClasses(const AbstractMetaClass *metaClass) const;
-
- void writeToPythonConversion(QTextStream &s, const AbstractMetaType *type,
- const AbstractMetaClass *context, const QString &argumentName);
- void writeToCppConversion(QTextStream &s, const AbstractMetaType *type, const AbstractMetaClass *context, const QString &inArgName, const QString &outArgName);
- void writeToCppConversion(QTextStream &s, const AbstractMetaClass *metaClass, const QString &inArgName, const QString &outArgName);
-
- /// Returns true if the argument is a pointer that rejects nullptr values.
- bool shouldRejectNullPointerArgument(const AbstractMetaFunction *func, int argIndex);
-
- /// Verifies if the class should have a C++ wrapper generated for it, instead of only a Python wrapper.
- bool shouldGenerateCppWrapper(const AbstractMetaClass *metaClass) const;
-
- /// Condition to call WriteVirtualMethodNative. Was extracted because also used to count these calls.
- bool shouldWriteVirtualMethodNative(const AbstractMetaFunction *func);
-
- /// Adds enums eligible for generation from classes/namespaces marked not to be generated.
- static void lookForEnumsInClassesNotToBeGenerated(AbstractMetaEnumList &enumList, const AbstractMetaClass *metaClass);
-
- QString wrapperName(const AbstractMetaClass *metaClass) const;
-
- QString fullPythonClassName(const AbstractMetaClass *metaClass);
- QString fullPythonFunctionName(const AbstractMetaFunction *func);
-
- bool wrapperDiagnostics() const { return m_wrapperDiagnostics; }
-
- static QString protectedEnumSurrogateName(const AbstractMetaEnum *metaEnum);
- static QString protectedFieldGetterName(const AbstractMetaField *field);
- static QString protectedFieldSetterName(const AbstractMetaField *field);
-
- static QString pythonPrimitiveTypeName(const QString &cppTypeName);
- static QString pythonPrimitiveTypeName(const PrimitiveTypeEntry *type);
-
- static QString pythonOperatorFunctionName(const QString &cppOpFuncName);
- static QString pythonOperatorFunctionName(const AbstractMetaFunction *func);
- static QString pythonRichCompareOperatorId(const QString &cppOpFuncName);
- static QString pythonRichCompareOperatorId(const AbstractMetaFunction *func);
-
- static QString fixedCppTypeName(const CustomConversion::TargetToNativeConversion *toNative);
- static QString fixedCppTypeName(const AbstractMetaType *type);
- static QString fixedCppTypeName(const TypeEntry *type, QString typeName = QString());
-
- static bool isNumber(const QString &cpythonApiName);
- static bool isNumber(const TypeEntry *type);
- static bool isNumber(const AbstractMetaType *type);
- static bool isPyInt(const TypeEntry *type);
- static bool isPyInt(const AbstractMetaType *type);
-
- /**
- * Returns true if the type passed has a Python wrapper for it.
- * Although namespace has a Python wrapper, it's not considered a type.
- */
- static bool isWrapperType(const TypeEntry *type);
- static bool isWrapperType(const ComplexTypeEntry *type);
- static bool isWrapperType(const AbstractMetaType *metaType);
-
- /**
- * Checks if the type is an Object/QObject or pointer to Value Type.
- * In other words, tells if the type is "T*" and T has a Python wrapper.
- */
- static bool isPointerToWrapperType(const AbstractMetaType *type);
-
- /**
- * Returns true if \p type is an Object Type used as a value.
- */
- static bool isObjectTypeUsedAsValueType(const AbstractMetaType *type);
-
- static bool isValueTypeWithCopyConstructorOnly(const AbstractMetaClass *metaClass);
- bool isValueTypeWithCopyConstructorOnly(const TypeEntry *type) const;
- bool isValueTypeWithCopyConstructorOnly(const AbstractMetaType *type) const;
-
- /// Returns true if the type is a primitive but not a C++ primitive.
- static bool isUserPrimitive(const TypeEntry *type);
- static bool isUserPrimitive(const AbstractMetaType *type);
-
- /// Returns true if the type is a C++ primitive, a void*, a const char*, or a std::string.
- static bool isCppPrimitive(const TypeEntry *type);
- static bool isCppPrimitive(const AbstractMetaType *type);
-
- /// Returns true if the type is a C++ integral primitive, i.e. bool, char, int, long, and their unsigned counterparts.
- static bool isCppIntegralPrimitive(const TypeEntry *type);
- static bool isCppIntegralPrimitive(const AbstractMetaType *type);
-
- /// Checks if an argument type should be dereferenced by the Python method wrapper before calling the C++ method.
- static bool shouldDereferenceArgumentPointer(const AbstractMetaArgument *arg);
- /// Checks if a meta type should be dereferenced by the Python method wrapper passing it to C++.
- static bool shouldDereferenceAbstractMetaTypePointer(const AbstractMetaType *metaType);
-
- static bool visibilityModifiedToPrivate(const AbstractMetaFunction *func);
-
- QString converterObject(const AbstractMetaType *type);
- QString converterObject(const TypeEntry *type);
-
- static QString cpythonBaseName(const AbstractMetaClass *metaClass);
- static QString cpythonBaseName(const TypeEntry *type);
- QString cpythonBaseName(const AbstractMetaType *type);
- QString cpythonTypeName(const AbstractMetaClass *metaClass);
- QString cpythonTypeName(const TypeEntry *type);
- QString cpythonTypeNameExt(const TypeEntry *type) const;
- QString cpythonTypeNameExt(const AbstractMetaType *type) const;
- QString cpythonCheckFunction(const TypeEntry *type, bool genericNumberType = false);
- QString cpythonCheckFunction(const AbstractMetaType *metaType, bool genericNumberType = false);
- /**
- * Receives the argument \p type and tries to find the appropriate AbstractMetaType for it
- * or a custom type check.
- * \param type A string representing the type to be discovered.
- * \param metaType A pointer to an AbstractMetaType pointer, to where write a new meta type object
- * if one is produced from the \p type string. This object must be deallocated by
- * the caller. It will set the target variable to nullptr, is \p type is a Python type.
- * \return A custom check if \p type is a custom type, or an empty string if \p metaType
- * receives an existing type object.
- */
- QString guessCPythonCheckFunction(const QString &type, AbstractMetaType **metaType);
- QString cpythonIsConvertibleFunction(const TypeEntry *type, bool genericNumberType = false, bool checkExact = false);
- QString cpythonIsConvertibleFunction(const AbstractMetaType *metaType, bool genericNumberType = false);
- QString cpythonIsConvertibleFunction(const AbstractMetaArgument *metaArg, bool genericNumberType = false);
-
- QString cpythonToCppConversionFunction(const AbstractMetaClass *metaClass);
- QString cpythonToCppConversionFunction(const AbstractMetaType *type, const AbstractMetaClass *context = nullptr);
- QString cpythonToPythonConversionFunction(const AbstractMetaType *type, const AbstractMetaClass *context = nullptr);
- QString cpythonToPythonConversionFunction(const AbstractMetaClass *metaClass);
- QString cpythonToPythonConversionFunction(const TypeEntry *type);
-
- QString cpythonFunctionName(const AbstractMetaFunction *func);
- QString cpythonMethodDefinitionName(const AbstractMetaFunction *func);
- QString cpythonGettersSettersDefinitionName(const AbstractMetaClass *metaClass);
- static QString cpythonGetattroFunctionName(const AbstractMetaClass *metaClass);
- static QString cpythonSetattroFunctionName(const AbstractMetaClass *metaClass);
- QString cpythonGetterFunctionName(const AbstractMetaField *metaField);
- QString cpythonSetterFunctionName(const AbstractMetaField *metaField);
- QString cpythonWrapperCPtr(const AbstractMetaClass *metaClass,
- const QString &argName = QLatin1String("self")) const;
- QString cpythonWrapperCPtr(const AbstractMetaType *metaType, const QString &argName) const;
- QString cpythonWrapperCPtr(const TypeEntry *type, const QString &argName) const;
-
- /// Guesses the scope to where belongs an argument's default value.
- QString guessScopeForDefaultValue(const AbstractMetaFunction *func,
- const AbstractMetaArgument *arg) const;
- QString guessScopeForDefaultFlagsValue(const AbstractMetaFunction *func,
- const AbstractMetaArgument *arg,
- const QString &value) const;
-
- static QString cpythonEnumName(const EnumTypeEntry *enumEntry);
- static QString cpythonEnumName(const AbstractMetaEnum *metaEnum);
-
- static QString cpythonFlagsName(const FlagsTypeEntry *flagsEntry);
- static QString cpythonFlagsName(const AbstractMetaEnum *metaEnum);
- /// Returns the special cast function name, the function used to proper cast class with multiple inheritance.
- static QString cpythonSpecialCastFunctionName(const AbstractMetaClass *metaClass);
-
- QString getFormatUnitString(const AbstractMetaFunction *func, bool incRef = false) const;
-
- /// Returns the file name for the module global header. If no module name is provided the current will be used.
- QString getModuleHeaderFileName(const QString &moduleName = QString()) const;
-
- OptionDescriptions options() const override;
- bool handleOption(const QString &key, const QString &value) override;
-
- /// Returns true if the user enabled the so called "parent constructor heuristic".
- bool useCtorHeuristic() const;
- /// Returns true if the user enabled the so called "return value heuristic".
- bool useReturnValueHeuristic() const;
- /// Returns true if the user enabled PySide extensions.
- bool usePySideExtensions() const;
- /// Returns true if the generator should use the result of isNull()const to compute boolean casts.
- bool useIsNullAsNbNonZero() const;
- /// Returns true if the generated code should use the "#define protected public" hack.
- bool avoidProtectedHack() const;
- QString cppApiVariableName(const QString &moduleName = QString()) const;
- QString pythonModuleObjectName(const QString &moduleName = QString()) const;
- QString convertersVariableName(const QString &moduleName = QString()) const;
- /**
- * Returns the type index variable name for a given class. If \p alternativeTemplateName is true
- * and the class is a typedef for a template class instantiation, it will return an alternative name
- * made of the template class and the instantiation values, or an empty string if the class isn't
- * derived from a template class at all.
- */
- QString getTypeIndexVariableName(const AbstractMetaClass *metaClass, bool alternativeTemplateName = false) const;
- QString getTypeIndexVariableName(const TypeEntry *type) const;
- QString getTypeIndexVariableName(const AbstractMetaType *type) const;
-
- /// Returns true if the user don't want verbose error messages on the generated bindings.
- bool verboseErrorMessagesDisabled() const;
-
- /**
- * Builds an AbstractMetaType object from a QString.
- * Returns nullptr if no type could be built from the string.
- * \param typeSignature The string describing the type to be built.
- * \return A new AbstractMetaType object that must be deleted by the caller,
- * or a nullptr pointer in case of failure.
- */
- AbstractMetaType *buildAbstractMetaTypeFromString(QString typeSignature,
- QString *errorMessage = nullptr);
-
- /// Creates an AbstractMetaType object from a TypeEntry.
- AbstractMetaType *buildAbstractMetaTypeFromTypeEntry(const TypeEntry *typeEntry);
- /// Creates an AbstractMetaType object from an AbstractMetaClass.
- AbstractMetaType *buildAbstractMetaTypeFromAbstractMetaClass(const AbstractMetaClass *metaClass);
-
- void writeMinimalConstructorExpression(QTextStream &s, const AbstractMetaType *type, const QString &defaultCtor = QString());
- void writeMinimalConstructorExpression(QTextStream &s, const TypeEntry *type, const QString &defaultCtor = QString());
-
- void collectContainerTypesFromConverterMacros(const QString &code, bool toPythonMacro);
- // verify whether the class is copyable
- bool isCopyable(const AbstractMetaClass *metaClass);
-
- void clearTpFuncs();
-
-
- /// Initializes correspondences between primitive and Python types.
- static void initPrimitiveTypesCorrespondences();
- /// Initializes a list of Python known type names.
- static void initKnownPythonTypes();
-
- void writeFunctionCall(QTextStream &s,
- const AbstractMetaFunction *metaFunc,
- Options options = NoOption) const;
-
- void writeUnusedVariableCast(QTextStream &s, const QString &variableName);
-
- AbstractMetaFunctionList filterFunctions(const AbstractMetaClass *metaClass);
-
- // All data about extended converters: the type entries of the target type, and a
- // list of AbstractMetaClasses accepted as argument for the conversion.
- using ExtendedConverterData = QHash<const TypeEntry *, QVector<const AbstractMetaClass *> >;
- /// Returns all extended conversions for the current module.
- ExtendedConverterData getExtendedConverters() const;
-
- /// Returns a list of converters for the non wrapper types of the current module.
- QVector<const CustomConversion *> getPrimitiveCustomConversions();
-
- /// Returns true if the Python wrapper for the received OverloadData must accept a list of arguments.
- static bool pythonFunctionWrapperUsesListOfArguments(const OverloadData &overloadData);
-
- Indentor INDENT;
-
- const QRegularExpression &convertToCppRegEx() const
- { return m_typeSystemConvRegEx[TypeSystemToCppFunction]; }
-
- static QString pythonArgsAt(int i);
-
- static QHash<QString, QString> m_pythonPrimitiveTypeName;
- static QHash<QString, QString> m_pythonOperators;
- static QHash<QString, QString> m_formatUnits;
- static QHash<QString, QString> m_tpFuncs;
- static QStringList m_knownPythonTypes;
-
-private:
- static const GeneratorClassInfoCacheEntry &getGeneratorClassInfo(const AbstractMetaClass *scope);
- static FunctionGroups getFunctionGroupsImpl(const AbstractMetaClass *scope);
- static bool classNeedsGetattroFunctionImpl(const AbstractMetaClass *metaClass);
-
- QString translateTypeForWrapperMethod(const AbstractMetaType *cType,
- const AbstractMetaClass *context,
- Options opt = NoOption) const;
-
- /**
- * Returns all different inherited overloads of func.
- * The function can be called multiple times without duplication.
- * \param func the metafunction to be searched in subclasses.
- * \param seen the function's minimal signatures already seen.
- */
- AbstractMetaFunctionList getInheritedOverloads(const AbstractMetaFunction *func,
- QSet<QString> *seen);
-
- /**
- * Returns all overloads for a function named \p functionName.
- * \param scope scope used to search for overloads.
- * \param functionName the function name.
- */
- AbstractMetaFunctionList getFunctionOverloads(const AbstractMetaClass *scope,
- const QString &functionName);
- /**
- * Write a function argument in the C++ in the text stream \p s.
- * This function just call \code s << argumentString(); \endcode
- * \param s text stream used to write the output.
- * \param func the current metafunction.
- * \param argument metaargument information to be parsed.
- * \param options some extra options.
- */
- void writeArgument(QTextStream &s,
- const AbstractMetaFunction *func,
- const AbstractMetaArgument *argument,
- Options options = NoOption) const;
- /**
- * Create a QString in the C++ format to an function argument.
- * \param func the current metafunction.
- * \param argument metaargument information to be parsed.
- * \param options some extra options.
- */
- QString argumentString(const AbstractMetaFunction *func,
- const AbstractMetaArgument *argument,
- Options options = NoOption) const;
-
- QString functionReturnType(const AbstractMetaFunction *func, Options options = NoOption) const;
-
- /// Utility function for writeCodeSnips.
- using ArgumentVarReplacementPair = QPair<const AbstractMetaArgument *, QString>;
- using ArgumentVarReplacementList = QVector<ArgumentVarReplacementPair>;
- ArgumentVarReplacementList getArgumentReplacement(const AbstractMetaFunction* func,
- bool usePyArgs, TypeSystem::Language language,
- const AbstractMetaArgument *lastArg);
-
- /// Returns a string with the user's custom code snippets that comply with \p position and \p language.
- QString getCodeSnippets(const QVector<CodeSnip> & codeSnips,
- TypeSystem::CodeSnipPosition position,
- TypeSystem::Language language);
-
- enum TypeSystemConverterVariable {
- TypeSystemCheckFunction = 0,
- TypeSystemIsConvertibleFunction,
- TypeSystemToCppFunction,
- TypeSystemToPythonFunction,
- TypeSystemConverterVariables
- };
- void replaceConverterTypeSystemVariable(TypeSystemConverterVariable converterVariable, QString &code);
-
- /// Replaces the %CONVERTTOPYTHON type system variable.
- inline void replaceConvertToPythonTypeSystemVariable(QString &code)
- {
- replaceConverterTypeSystemVariable(TypeSystemToPythonFunction, code);
- }
- /// Replaces the %CONVERTTOCPP type system variable.
- inline void replaceConvertToCppTypeSystemVariable(QString &code)
- {
- replaceConverterTypeSystemVariable(TypeSystemToCppFunction, code);
- }
- /// Replaces the %ISCONVERTIBLE type system variable.
- inline void replaceIsConvertibleToCppTypeSystemVariable(QString &code)
- {
- replaceConverterTypeSystemVariable(TypeSystemIsConvertibleFunction, code);
- }
- /// Replaces the %CHECKTYPE type system variable.
- inline void replaceTypeCheckTypeSystemVariable(QString &code)
- {
- replaceConverterTypeSystemVariable(TypeSystemCheckFunction, code);
- }
-
- /// Return a prefix with '_' suitable for names in C++
- QString moduleCppPrefix(const QString &moduleName = QString()) const;
-
- bool m_useCtorHeuristic = false;
- bool m_userReturnValueHeuristic = false;
- bool m_usePySideExtensions = false;
- bool m_verboseErrorMessagesDisabled = false;
- bool m_useIsNullAsNbNonZero = false;
- bool m_avoidProtectedHack = false;
- bool m_wrapperDiagnostics = false;
-
- using AbstractMetaTypeCache = QHash<QString, AbstractMetaType *>;
- AbstractMetaTypeCache m_metaTypeFromStringCache;
-
- /// Type system converter variable replacement names and regular expressions.
- QString m_typeSystemConvName[TypeSystemConverterVariables];
- QRegularExpression m_typeSystemConvRegEx[TypeSystemConverterVariables];
-};
-
-Q_DECLARE_OPERATORS_FOR_FLAGS(ShibokenGenerator::AttroCheck);
-
-#endif // SHIBOKENGENERATOR_H
diff --git a/sources/shiboken2/generator/shibokenconfig.h.in b/sources/shiboken2/generator/shibokenconfig.h.in
deleted file mode 100644
index 2c86a4a3c..000000000
--- a/sources/shiboken2/generator/shibokenconfig.h.in
+++ /dev/null
@@ -1,6 +0,0 @@
-#ifndef SHIBOKENCONFIG_H
-#define SHIBOKENCONFIG_H
-
-#define SHIBOKEN_VERSION "@shiboken2_VERSION@"
-
-#endif
diff --git a/sources/shiboken2/generatorrunnerconfig.h.in b/sources/shiboken2/generatorrunnerconfig.h.in
deleted file mode 100644
index d291fcc53..000000000
--- a/sources/shiboken2/generatorrunnerconfig.h.in
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifndef GENERATORRUNNERCONFIG_H
-#define GENERATORRUNNERCONFIG_H
-
-// generatorrunner version
-#define GENERATORRUNNER_VERSION "@generator_VERSION@"
-
-// generatorrunner plugin dir
-#define GENERATORRUNNER_PLUGIN_DIR "@generator_plugin_DIR@"
-
-// module extension
-#define MODULE_EXTENSION "@CMAKE_SHARED_LIBRARY_SUFFIX@"
-
-#endif
diff --git a/sources/shiboken2/generatorrunnermacros.h b/sources/shiboken2/generatorrunnermacros.h
deleted file mode 100644
index 1f1119dfa..000000000
--- a/sources/shiboken2/generatorrunnermacros.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef GENERATORRUNNERMACROS_H
-#define GENERATORRUNNERMACROS_H
-
-// GENRUNNER_API is used for the public API symbols.
-#if defined _WIN32
- #define GENRUNNER_EXPORT __declspec(dllexport)
- #if GENRUNNER_EXPORTS
- #define GENRUNNER_API GENRUNNER_EXPORT
- #endif
-#elif __GNUC__ >= 4
- #define GENRUNNER_EXPORT __attribute__ ((visibility("default")))
- #define GENRUNNER_API GENRUNNER_EXPORT
-#elif __GNUC__ < 4
- #define GENRUNNER_EXPORT
-#endif
-
-#ifndef GENRUNNER_API
- #define GENRUNNER_API
-#endif
-#endif
diff --git a/sources/shiboken2/generators/shiboken/shiboken.cpp b/sources/shiboken2/generators/shiboken/shiboken.cpp
deleted file mode 100644
index a047c15f1..000000000
--- a/sources/shiboken2/generators/shiboken/shiboken.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "cppgenerator.h"
-#include "headergenerator.h"
-
-EXPORT_GENERATOR_PLUGIN(new CppGenerator << new HeaderGenerator)
diff --git a/sources/shiboken2/icecc.cmake b/sources/shiboken2/icecc.cmake
deleted file mode 100644
index b2bf071aa..000000000
--- a/sources/shiboken2/icecc.cmake
+++ /dev/null
@@ -1,11 +0,0 @@
-include (CMakeForceCompiler)
-option(ENABLE_ICECC "Enable icecc checking, for distributed compilation")
-if (ENABLE_ICECC)
- find_program(ICECC icecc)
- if (ICECC)
- message(STATUS "icecc found! Distributed compilation for all!! huhuhu.")
- cmake_force_cxx_compiler(${ICECC} icecc)
- else(ICECC)
- message(FATAL_ERROR "icecc NOT found! re-run cmake without -DENABLE_ICECC")
- endif(ICECC)
-endif(ENABLE_ICECC)
diff --git a/sources/shiboken2/libshiboken/CMakeLists.txt b/sources/shiboken2/libshiboken/CMakeLists.txt
deleted file mode 100644
index a38da8d89..000000000
--- a/sources/shiboken2/libshiboken/CMakeLists.txt
+++ /dev/null
@@ -1,152 +0,0 @@
-project(libshiboken)
-
-macro(get_numpy_location)
- execute_process(
- COMMAND ${PYTHON_EXECUTABLE} -c "if True:
- import sys
- import os
- numpy = ''
- for p in sys.path:
- if 'site-' in p:
- numpy = os.path.join(p, 'numpy')
- if os.path.exists(numpy):
- print(os.path.realpath(numpy))
- break"
- OUTPUT_VARIABLE PYTHON_NUMPY_LOCATION
- OUTPUT_STRIP_TRAILING_WHITESPACE)
- message("PYTHON_NUMPY_LOCATION: " ${PYTHON_NUMPY_LOCATION})
-endmacro()
-
-option(ENABLE_VERSION_SUFFIX "Used to use current version in suffix to generated files. This is used to allow multiples versions installed simultaneous." FALSE)
-if(ENABLE_VERSION_SUFFIX)
- set(shiboken2_SUFFIX "-${shiboken_MAJOR_VERSION}.${shiboken_MINOR_VERSION}")
-else()
- set(shiboken2_SUFFIX "")
-endif()
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/sbkversion.h.in"
- "${CMAKE_CURRENT_BINARY_DIR}/sbkversion.h" @ONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/embed/signature_bootstrap.py"
- "${CMAKE_CURRENT_BINARY_DIR}/embed/signature_bootstrap.py" @ONLY)
-
-add_custom_command(
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/embed/signature_bootstrap_inc.h"
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/embed/signature_inc.h"
- COMMAND ${PYTHON_EXECUTABLE} -E
- "${CMAKE_CURRENT_SOURCE_DIR}/embed/embedding_generator.py"
- --cmake-dir "${CMAKE_CURRENT_BINARY_DIR}/embed"
- --limited-api ${PYTHON_LIMITED_API})
-
-set(libshiboken_MAJOR_VERSION ${shiboken_MAJOR_VERSION})
-set(libshiboken_MINOR_VERSION ${shiboken_MINOR_VERSION})
-set(libshiboken_MICRO_VERSION ${shiboken_MICRO_VERSION})
-set(libshiboken_VERSION "${libshiboken_MAJOR_VERSION}.${libshiboken_MINOR_VERSION}.${libshiboken_MICRO_VERSION}")
-set(libshiboken_SOVERSION "${shiboken2_library_so_version}")
-
-set(libshiboken_SRC
-basewrapper.cpp
-debugfreehook.cpp
-gilstate.cpp
-helper.cpp
-sbkarrayconverter.cpp
-sbkconverter.cpp
-sbkenum.cpp
-sbkmodule.cpp
-sbkstring.cpp
-sbkstaticstrings.cpp
-bindingmanager.cpp
-threadstatesaver.cpp
-shibokenbuffer.cpp
-signature.cpp
-qapp_macro.cpp
-pep384impl.cpp
-voidptr.cpp
-typespec.cpp
-bufferprocs_py37.cpp
-embed/signature_bootstrap_inc.h
-embed/signature_inc.h
-)
-
-get_numpy_location()
-
-if (NOT "${PYTHON_NUMPY_LOCATION}" STREQUAL "")
- list(APPEND libshiboken_SRC sbknumpyarrayconverter.cpp)
-endif()
-
-set(APIEXTRACTOR_EXTRA_INCLUDES ${APIEXTRACTOR_EXTRA_INCLUDES} ${LIBXSLT_INCLUDE_DIR} ${LIBXML2_INCLUDE_DIR})
-
-add_library(libshiboken SHARED ${libshiboken_SRC})
-add_library(Shiboken2::libshiboken ALIAS libshiboken)
-
-target_include_directories(libshiboken PUBLIC
- $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
- $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
- $<INSTALL_INTERFACE:include/shiboken2>
-)
-
-if (NOT "${PYTHON_NUMPY_LOCATION}" STREQUAL "")
- target_include_directories(libshiboken PRIVATE ${PYTHON_NUMPY_LOCATION}/core/include)
- target_compile_definitions(libshiboken PRIVATE -DHAVE_NUMPY
- PRIVATE -DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION)
-
-endif()
-
-shiboken_compute_python_includes()
-# On Windows we need to link against the python.lib import library.
-# On macOS and Linux we don't link against the python shared / static library,
-# the dynamic linker will pick up the python symbols at runtime automatically.
-shiboken_compute_python_libraries()
-
-if(PYTHON_LIMITED_API)
- target_compile_definitions(libshiboken PUBLIC "-DPy_LIMITED_API=0x03050000")
-endif()
-
-if(CMAKE_BUILD_TYPE STREQUAL "Debug")
- if(PYTHON_WITH_DEBUG)
- target_compile_definitions(libshiboken PUBLIC "-DPy_DEBUG")
- endif()
- if (PYTHON_WITH_COUNT_ALLOCS)
- target_compile_definitions(libshiboken PUBLIC "-DCOUNT_ALLOCS")
- endif()
-elseif(CMAKE_BUILD_TYPE STREQUAL "Release")
- target_compile_definitions(libshiboken PUBLIC "-DNDEBUG")
-endif()
-
-set_target_properties(libshiboken PROPERTIES OUTPUT_NAME "shiboken2${shiboken2_SUFFIX}${PYTHON_SHARED_LIBRARY_SUFFIX}"
- VERSION ${libshiboken_VERSION}
- SOVERSION ${libshiboken_SOVERSION}
- DEFINE_SYMBOL LIBSHIBOKEN_EXPORTS)
-
-install(FILES
- autodecref.h
- basewrapper.h
- bindingmanager.h
- gilstate.h
- helper.h
- sbkarrayconverter.h
- sbkconverter.h
- sbkenum.h
- sbkmodule.h
- python25compat.h
- sbkdbg.h
- sbkstring.h
- sbkstaticstrings.h
- shiboken.h
- shibokenmacros.h
- threadstatesaver.h
- shibokenbuffer.h
- sbkpython.h
- pep384impl.h
- signature.h
- qapp_macro.h
- voidptr.h
- typespec.h
- bufferprocs_py37.h
- "${CMAKE_CURRENT_BINARY_DIR}/sbkversion.h"
- DESTINATION include/shiboken2${shiboken2_SUFFIX})
-install(TARGETS libshiboken EXPORT Shiboken2Targets
- LIBRARY DESTINATION "${LIB_INSTALL_DIR}"
- ARCHIVE DESTINATION "${LIB_INSTALL_DIR}"
- RUNTIME DESTINATION bin)
-install(EXPORT Shiboken2Targets NAMESPACE Shiboken2::
- DESTINATION ${LIB_INSTALL_DIR}/cmake/Shiboken2-${shiboken2_VERSION})
diff --git a/sources/shiboken2/libshiboken/autodecref.h b/sources/shiboken2/libshiboken/autodecref.h
deleted file mode 100644
index 498b1aec4..000000000
--- a/sources/shiboken2/libshiboken/autodecref.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef AUTODECREF_H
-#define AUTODECREF_H
-
-#include "sbkpython.h"
-#include "basewrapper.h"
-
-struct SbkObject;
-namespace Shiboken
-{
-
-/**
- * AutoDecRef holds a PyObject pointer and decrement its reference counter when destroyed.
- */
-struct LIBSHIBOKEN_API AutoDecRef
-{
-public:
- AutoDecRef(const AutoDecRef &) = delete;
- AutoDecRef(AutoDecRef &&) = delete;
- AutoDecRef &operator=(const AutoDecRef &) = delete;
- AutoDecRef &operator=(AutoDecRef &&) = delete;
-
- /**
- * AutoDecRef constructor.
- * \param pyobj A borrowed reference to a Python object
- */
- explicit AutoDecRef(PyObject *pyObj) : m_pyObj(pyObj) {}
- /**
- * AutoDecRef constructor.
- * \param pyobj A borrowed reference to a Python object
- */
- explicit AutoDecRef(SbkObject *pyObj) : m_pyObj(reinterpret_cast<PyObject *>(pyObj)) {}
-
- /// Decref the borrowed python reference
- ~AutoDecRef()
- {
- Py_XDECREF(m_pyObj);
- }
-
- inline bool isNull() const { return m_pyObj == nullptr; }
- /// Returns the pointer of the Python object being held.
- inline PyObject *object() { return m_pyObj; }
- inline operator PyObject *() { return m_pyObj; }
-#ifndef Py_LIMITED_API
- inline operator PyTupleObject *() { return reinterpret_cast<PyTupleObject *>(m_pyObj); }
-#endif
- inline operator bool() const { return m_pyObj != nullptr; }
- inline PyObject *operator->() { return m_pyObj; }
-
- template<typename T>
- T cast()
- {
- return reinterpret_cast<T>(m_pyObj);
- }
-
- /**
- * Decref the current borrowed python reference and borrow \p other.
- */
- void reset(PyObject *other)
- {
- // Safely decref m_pyObj. See Py_XSETREF in object.h .
- PyObject *_py_tmp = m_pyObj;
- m_pyObj = other;
- Py_XDECREF(_py_tmp);
- }
-private:
- PyObject *m_pyObj;
-};
-
-} // namespace Shiboken
-
-#endif // AUTODECREF_H
-
diff --git a/sources/shiboken2/libshiboken/basewrapper.cpp b/sources/shiboken2/libshiboken/basewrapper.cpp
deleted file mode 100644
index 443d25cdf..000000000
--- a/sources/shiboken2/libshiboken/basewrapper.cpp
+++ /dev/null
@@ -1,1755 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "basewrapper.h"
-#include "basewrapper_p.h"
-#include "bindingmanager.h"
-#include "helper.h"
-#include "sbkconverter.h"
-#include "sbkenum.h"
-#include "sbkstring.h"
-#include "sbkstaticstrings.h"
-#include "sbkstaticstrings_p.h"
-#include "autodecref.h"
-#include "gilstate.h"
-#include <string>
-#include <cstring>
-#include <cstddef>
-#include <set>
-#include <sstream>
-#include <algorithm>
-#include "threadstatesaver.h"
-#include "signature.h"
-#include "qapp_macro.h"
-#include "voidptr.h"
-
-#include <iostream>
-
-#if defined(__APPLE__)
-#include <dlfcn.h>
-#endif
-
-namespace {
- void _destroyParentInfo(SbkObject *obj, bool keepReference);
-}
-
-static void callDestructor(const Shiboken::DtorAccumulatorVisitor::DestructorEntries &dts)
-{
- for (const auto &e : dts) {
- Shiboken::ThreadStateSaver threadSaver;
- threadSaver.save();
- e.destructor(e.cppInstance);
- }
-}
-
-extern "C"
-{
-
-// PYSIDE-939: A general replacement for object_dealloc.
-void Sbk_object_dealloc(PyObject *self)
-{
- if (PepRuntime_38_flag) {
- // PYSIDE-939: Handling references correctly.
- // This was not needed before Python 3.8 (Python issue 35810)
- Py_DECREF(Py_TYPE(self));
- }
- Py_TYPE(self)->tp_free(self);
-}
-
-static void SbkObjectTypeDealloc(PyObject *pyObj);
-static PyObject *SbkObjectTypeTpNew(PyTypeObject *metatype, PyObject *args, PyObject *kwds);
-
-// PYSIDE-908: The function PyType_Modified does not work in PySide, so we need to
-// explicitly pass __doc__. For __signature__ it _did_ actually work, because
-// it was not existing before. We add them both for clarity.
-static PyGetSetDef SbkObjectType_Type_getsetlist[] = {
- {const_cast<char *>("__signature__"), (getter)Sbk_TypeGet___signature__},
- {const_cast<char *>("__doc__"), (getter)Sbk_TypeGet___doc__},
- {nullptr} // Sentinel
-};
-
-#if PY_VERSION_HEX < 0x03000000
-
-static PyObject *SbkObjectType_repr(PyObject *type)
-{
- Shiboken::AutoDecRef mod(PyObject_GetAttr(type, Shiboken::PyMagicName::module()));
- if (mod.isNull())
- return nullptr;
- Shiboken::AutoDecRef name(PyObject_GetAttr(type, Shiboken::PyMagicName::qualname()));
- if (name.isNull())
- return nullptr;
- return PyString_FromFormat("<class '%s.%s'>",
- PyString_AS_STRING(mod.object()),
- PyString_AS_STRING(name.object()));
-}
-
-#endif // PY_VERSION_HEX < 0x03000000
-
-static PyType_Slot SbkObjectType_Type_slots[] = {
- {Py_tp_dealloc, reinterpret_cast<void *>(SbkObjectTypeDealloc)},
- {Py_tp_setattro, reinterpret_cast<void *>(PyObject_GenericSetAttr)},
- {Py_tp_base, static_cast<void *>(&PyType_Type)},
- {Py_tp_alloc, reinterpret_cast<void *>(PyType_GenericAlloc)},
- {Py_tp_new, reinterpret_cast<void *>(SbkObjectTypeTpNew)},
- {Py_tp_free, reinterpret_cast<void *>(PyObject_GC_Del)},
- {Py_tp_getset, reinterpret_cast<void *>(SbkObjectType_Type_getsetlist)},
-#if PY_VERSION_HEX < 0x03000000
- {Py_tp_repr, reinterpret_cast<void *>(SbkObjectType_repr)},
-#endif
- {0, nullptr}
-};
-static PyType_Spec SbkObjectType_Type_spec = {
- "1:Shiboken.ObjectType",
- 0, // basicsize (inserted later)
- sizeof(PyMemberDef),
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
- SbkObjectType_Type_slots,
-};
-
-
-#if PY_VERSION_HEX < 0x03000000
-/*****************************************************************************
- *
- * PYSIDE-816: Workaround for Python 2.7 for SbkObjectType_TypeF().
- *
- * This is an add-on for function typeobject.c:tp_new_wrapper from Python 2.7 .
- * Problem:
- * In Python 3.X, tp_new_wrapper uses this check:
-
- while (staticbase && (staticbase->tp_new == slot_tp_new))
-
- * In Python 2.7, it uses this, instead:
-
- while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
-
- * The problem is that heap types have this unwanted dependency.
- * But we cannot get at static slot_tp_new, and so we have to use
- * the original function and patch Py_TPFLAGS_HEAPTYPE away during the call.
- *
- * PYSIDE-1051: The same problem holds for all dynamic metatypes generated by
- * SbkObjectTypeTpNew() and all types generated by
- * introduceWrapperType() .
- *
- * This led to a drastic overhaul of patch_tp_new_wrapper() which now adds
- * the new wrapper to exactly those types which have the old wrapper.
- */
-
-ternaryfunc old_tp_new_wrapper = nullptr;
-
-static PyObject *
-tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
-{
- PyTypeObject *type = reinterpret_cast<PyTypeObject *>(self);
- Py_ssize_t orig_flags = type->tp_flags;
- type->tp_flags &= ~Py_TPFLAGS_HEAPTYPE;
- PyObject *ret = reinterpret_cast<ternaryfunc>(old_tp_new_wrapper)(self, args, kwds);
- type->tp_flags = orig_flags;
- return ret;
-}
-
-// This is intentionally the __new__ docstring of Python 3.7 .
-static struct PyMethodDef tp_new_methoddef[] = {
- {"__new__", reinterpret_cast<PyCFunction>(tp_new_wrapper), METH_VARARGS|METH_KEYWORDS,
- PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n"
- "Create and return a new object. "
- "See help(type) for accurate signature.")},
- {0}
-};
-
-static int
-patch_tp_new_wrapper(PyTypeObject *type)
-{
- /*
- * The old tp_new_wrapper is added to all types that have tp_new.
- * We patch that with a version that ignores the heaptype flag.
- */
- auto newMethod = Shiboken::PyMagicName::new_();
- if (old_tp_new_wrapper == nullptr) {
- PyObject *func = PyDict_GetItem(PyType_Type.tp_dict, newMethod);
- assert(func);
- PyCFunctionObject *pycf_ob = reinterpret_cast<PyCFunctionObject *>(func);
- old_tp_new_wrapper = reinterpret_cast<ternaryfunc>(pycf_ob->m_ml->ml_meth);
- }
- PyObject *mro = type->tp_mro;
- Py_ssize_t i, n = PyTuple_GET_SIZE(mro);
- for (i = 0; i < n; i++) {
- type = reinterpret_cast<PyTypeObject *>(PyTuple_GET_ITEM(mro, i));
- PyObject *existing = PyDict_GetItem(type->tp_dict, newMethod);
- if (existing && PyCFunction_Check(existing)
- && type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
- auto *pycf_ob = reinterpret_cast<PyCFunctionObject *>(existing);
- auto existing_wrapper = reinterpret_cast<ternaryfunc>(pycf_ob->m_ml->ml_meth);
- if (existing_wrapper == tp_new_wrapper)
- break;
- if (existing_wrapper == old_tp_new_wrapper) {
- PyObject *ob_type = reinterpret_cast<PyObject *>(type);
- Shiboken::AutoDecRef func(PyCFunction_New(tp_new_methoddef, ob_type));
- if (func.isNull() || PyDict_SetItem(type->tp_dict, newMethod, func))
- return -1;
- }
- }
- }
- return 0;
-}
-/*****************************************************************************/
-#endif // PY_VERSION_HEX < 0x03000000
-
-
-PyTypeObject *SbkObjectType_TypeF(void)
-{
- static PyTypeObject *type = nullptr;
- if (!type) {
- SbkObjectType_Type_spec.basicsize =
- PepHeapType_SIZE + sizeof(SbkObjectTypePrivate);
- type = reinterpret_cast<PyTypeObject *>(SbkType_FromSpec(&SbkObjectType_Type_spec));
-#if PY_VERSION_HEX < 0x03000000
- if (patch_tp_new_wrapper(type) < 0)
- return nullptr;
-#endif
- }
- return type;
-}
-
-static PyObject *SbkObjectGetDict(PyObject *pObj, void *)
-{
- auto *obj = reinterpret_cast<SbkObject *>(pObj);
- if (!obj->ob_dict)
- obj->ob_dict = PyDict_New();
- if (!obj->ob_dict)
- return nullptr;
- Py_INCREF(obj->ob_dict);
- return obj->ob_dict;
-}
-
-static PyGetSetDef SbkObjectGetSetList[] = {
- {const_cast<char *>("__dict__"), SbkObjectGetDict, nullptr, nullptr, nullptr},
- {nullptr, nullptr, nullptr, nullptr, nullptr} // Sentinel
-};
-
-static int SbkObject_traverse(PyObject *self, visitproc visit, void *arg)
-{
- auto *sbkSelf = reinterpret_cast<SbkObject *>(self);
-
- //Visit children
- Shiboken::ParentInfo *pInfo = sbkSelf->d->parentInfo;
- if (pInfo) {
- for (SbkObject *c : pInfo->children)
- Py_VISIT(c);
- }
-
- //Visit refs
- Shiboken::RefCountMap *rInfo = sbkSelf->d->referredObjects;
- if (rInfo) {
- for (auto it = rInfo->begin(), end = rInfo->end(); it != end; ++it)
- Py_VISIT(it->second);
- }
-
- if (sbkSelf->ob_dict)
- Py_VISIT(sbkSelf->ob_dict);
- return 0;
-}
-
-static int SbkObject_clear(PyObject *self)
-{
- auto *sbkSelf = reinterpret_cast<SbkObject *>(self);
-
- Shiboken::Object::removeParent(sbkSelf);
-
- if (sbkSelf->d->parentInfo)
- _destroyParentInfo(sbkSelf, true);
-
- Shiboken::Object::clearReferences(sbkSelf);
-
- if (sbkSelf->ob_dict)
- Py_CLEAR(sbkSelf->ob_dict);
- return 0;
-}
-
-static PyType_Slot SbkObject_Type_slots[] = {
- {Py_tp_dealloc, reinterpret_cast<void *>(SbkDeallocWrapperWithPrivateDtor)},
- {Py_tp_traverse, reinterpret_cast<void *>(SbkObject_traverse)},
- {Py_tp_clear, reinterpret_cast<void *>(SbkObject_clear)},
- // unsupported: {Py_tp_weaklistoffset, (void *)offsetof(SbkObject, weakreflist)},
- {Py_tp_getset, reinterpret_cast<void *>(SbkObjectGetSetList)},
- // unsupported: {Py_tp_dictoffset, (void *)offsetof(SbkObject, ob_dict)},
- {0, nullptr}
-};
-static PyType_Spec SbkObject_Type_spec = {
- "1:Shiboken.Object",
- sizeof(SbkObject),
- 0,
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC,
- SbkObject_Type_slots,
-};
-
-
-SbkObjectType *SbkObject_TypeF(void)
-{
- static PyTypeObject *type = nullptr;
- if (!type) {
- type = reinterpret_cast<PyTypeObject *>(SbkType_FromSpec(&SbkObject_Type_spec));
- Py_TYPE(type) = SbkObjectType_TypeF();
- Py_INCREF(Py_TYPE(type));
- type->tp_weaklistoffset = offsetof(SbkObject, weakreflist);
- type->tp_dictoffset = offsetof(SbkObject, ob_dict);
- }
- return reinterpret_cast<SbkObjectType *>(type);
-}
-
-static int mainThreadDeletionHandler(void *)
-{
- if (Py_IsInitialized())
- Shiboken::BindingManager::instance().runDeletionInMainThread();
- return 0;
-}
-
-static void SbkDeallocWrapperCommon(PyObject *pyObj, bool canDelete)
-{
- auto *sbkObj = reinterpret_cast<SbkObject *>(pyObj);
- PyTypeObject *pyType = Py_TYPE(pyObj);
-
- // Need to decref the type if this is the dealloc func; if type
- // is subclassed, that dealloc func will decref (see subtype_dealloc
- // in typeobject.c in the python sources)
- bool needTypeDecref = (false
- || PyType_GetSlot(pyType, Py_tp_dealloc) == SbkDeallocWrapper
- || PyType_GetSlot(pyType, Py_tp_dealloc) == SbkDeallocWrapperWithPrivateDtor);
- if (PepRuntime_38_flag) {
- // PYSIDE-939: Additional rule: Also when a subtype is heap allocated,
- // then the subtype_dealloc deref will be suppressed, and we need again
- // to supply a decref.
- needTypeDecref |= (pyType->tp_base->tp_flags & Py_TPFLAGS_HEAPTYPE) != 0;
- }
-
-#if defined(__APPLE__)
- // Just checking once that our assumptions are right.
- if (false) {
- void *p = PyType_GetSlot(pyType, Py_tp_dealloc);
- Dl_info dl_info;
- dladdr(p, &dl_info);
- fprintf(stderr, "tp_dealloc is %s\n", dl_info.dli_sname);
- }
- // Gives one of our functions
- // "Sbk_object_dealloc"
- // "SbkDeallocWrapperWithPrivateDtor"
- // "SbkDeallocQAppWrapper"
- // "SbkDeallocWrapper"
- // but for typedealloc_test.py we get
- // "subtype_dealloc"
-#endif
-
- // Ensure that the GC is no longer tracking this object to avoid a
- // possible reentrancy problem. Since there are multiple steps involved
- // in deallocating a SbkObject it is possible for the garbage collector to
- // be invoked and it trying to delete this object while it is still in
- // progress from the first time around, resulting in a double delete and a
- // crash.
- // PYSIDE-571: Some objects do not use GC, so check this!
- if (PyObject_IS_GC(pyObj))
- PyObject_GC_UnTrack(pyObj);
-
- // Check that Python is still initialized as sometimes this is called by a static destructor
- // after Python interpeter is shutdown.
- if (sbkObj->weakreflist && Py_IsInitialized())
- PyObject_ClearWeakRefs(pyObj);
-
- // If I have ownership and is valid delete C++ pointer
- SbkObjectTypePrivate *sotp{nullptr};
- canDelete &= sbkObj->d->hasOwnership && sbkObj->d->validCppObject;
- if (canDelete) {
- sotp = PepType_SOTP(pyType);
- if (sotp->delete_in_main_thread && Shiboken::currentThreadId() != Shiboken::mainThreadId()) {
- auto &bindingManager = Shiboken::BindingManager::instance();
- if (sotp->is_multicpp) {
- Shiboken::DtorAccumulatorVisitor visitor(sbkObj);
- Shiboken::walkThroughClassHierarchy(Py_TYPE(pyObj), &visitor);
- for (const auto &e : visitor.entries())
- bindingManager.addToDeletionInMainThread(e);
- } else {
- Shiboken::DestructorEntry e{sotp->cpp_dtor, sbkObj->d->cptr[0]};
- bindingManager.addToDeletionInMainThread(e);
- }
- Py_AddPendingCall(mainThreadDeletionHandler, nullptr);
- canDelete = false;
- }
- }
-
- if (canDelete) {
- if (sotp->is_multicpp) {
- Shiboken::DtorAccumulatorVisitor visitor(sbkObj);
- Shiboken::walkThroughClassHierarchy(Py_TYPE(pyObj), &visitor);
- Shiboken::Object::deallocData(sbkObj, true);
- callDestructor(visitor.entries());
- } else {
- void *cptr = sbkObj->d->cptr[0];
- Shiboken::Object::deallocData(sbkObj, true);
-
- Shiboken::ThreadStateSaver threadSaver;
- if (Py_IsInitialized())
- threadSaver.save();
- sotp->cpp_dtor(cptr);
- }
- } else {
- Shiboken::Object::deallocData(sbkObj, true);
- }
-
- if (needTypeDecref)
- Py_DECREF(pyType);
- if (PepRuntime_38_flag) {
- // PYSIDE-939: Handling references correctly.
- // This was not needed before Python 3.8 (Python issue 35810)
- Py_DECREF(pyType);
- }
-}
-
-void SbkDeallocWrapper(PyObject *pyObj)
-{
- SbkDeallocWrapperCommon(pyObj, true);
-}
-
-void SbkDeallocQAppWrapper(PyObject *pyObj)
-{
- SbkDeallocWrapper(pyObj);
- // PYSIDE-571: make sure to create a singleton deleted qApp.
- Py_DECREF(MakeQAppWrapper(nullptr));
-}
-
-void SbkDeallocWrapperWithPrivateDtor(PyObject *self)
-{
- SbkDeallocWrapperCommon(self, false);
-}
-
-void SbkObjectTypeDealloc(PyObject *pyObj)
-{
- SbkObjectTypePrivate *sotp = PepType_SOTP(pyObj);
- auto type = reinterpret_cast<PyTypeObject *>(pyObj);
-
- PyObject_GC_UnTrack(pyObj);
-#ifndef Py_LIMITED_API
- Py_TRASHCAN_SAFE_BEGIN(pyObj);
-#endif
- if (sotp) {
- if (sotp->user_data && sotp->d_func) {
- sotp->d_func(sotp->user_data);
- sotp->user_data = nullptr;
- }
- free(sotp->original_name);
- sotp->original_name = nullptr;
- if (!Shiboken::ObjectType::isUserType(type))
- Shiboken::Conversions::deleteConverter(sotp->converter);
- delete sotp;
- sotp = nullptr;
- }
-#ifndef Py_LIMITED_API
- Py_TRASHCAN_SAFE_END(pyObj);
-#endif
- if (PepRuntime_38_flag) {
- // PYSIDE-939: Handling references correctly.
- // This was not needed before Python 3.8 (Python issue 35810)
- Py_DECREF(Py_TYPE(pyObj));
- }
-}
-
-PyObject *SbkObjectTypeTpNew(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
-{
- // Check if all bases are new style before calling type.tp_new
- // Was causing gc assert errors in test_bug704.py when
- // this check happened after creating the type object.
- // Argument parsing take from type.tp_new code.
-
- // PYSIDE-595: Also check if all bases allow inheritance.
- // Before we changed to heap types, it was sufficient to remove the
- // Py_TPFLAGS_BASETYPE flag. That does not work, because PySide does
- // not respect this flag itself!
- PyObject *name;
- PyObject *pyBases;
- PyObject *dict;
- static const char *kwlist[] = { "name", "bases", "dict", nullptr};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "sO!O!:sbktype", const_cast<char **>(kwlist),
- &name,
- &PyTuple_Type, &pyBases,
- &PyDict_Type, &dict))
- return nullptr;
-
- for (int i=0, i_max=PyTuple_GET_SIZE(pyBases); i < i_max; i++) {
- PyObject *baseType = PyTuple_GET_ITEM(pyBases, i);
-#ifndef IS_PY3K
- if (PyClass_Check(baseType)) {
- PyErr_Format(PyExc_TypeError, "Invalid base class used in type %s. "
- "PySide only support multiple inheritance from python new style class.", metatype->tp_name);
- return 0;
- }
-#endif
- if (reinterpret_cast<PyTypeObject *>(baseType)->tp_new == SbkDummyNew) {
- // PYSIDE-595: A base class does not allow inheritance.
- return SbkDummyNew(metatype, args, kwds);
- }
- }
-
- // The meta type creates a new type when the Python programmer extends a wrapped C++ class.
- auto type_new = reinterpret_cast<newfunc>(PyType_Type.tp_new);
-
- // PYSIDE-939: This is a temporary patch that circumvents the problem
- // with Py_TPFLAGS_METHOD_DESCRIPTOR until this is finally solved.
- // PyType_Ready uses mro(). We need to temporarily remove the flag from it's type.
- // We cannot use PyMethodDescr_Type since it is not exported by Python 2.7 .
- static PyTypeObject *PyMethodDescr_TypePtr = Py_TYPE(
- PyObject_GetAttr(reinterpret_cast<PyObject *>(&PyType_Type), Shiboken::PyName::mro()));
- auto hold = PyMethodDescr_TypePtr->tp_flags;
- PyMethodDescr_TypePtr->tp_flags &= ~Py_TPFLAGS_METHOD_DESCRIPTOR;
- auto *newType = reinterpret_cast<SbkObjectType *>(type_new(metatype, args, kwds));
- PyMethodDescr_TypePtr->tp_flags = hold;
-
- if (!newType)
- return nullptr;
-#if PY_VERSION_HEX < 0x03000000
- // PYSIDE-1051: The newly created metatype needs the PYSIDE-816 wrapper, too.
- if (patch_tp_new_wrapper(&newType->type) < 0)
- return nullptr;
-#endif
-
- Shiboken::ObjectType::initPrivateData(newType);
- SbkObjectTypePrivate *sotp = PepType_SOTP(newType);
-
- const auto bases = Shiboken::getCppBaseClasses(reinterpret_cast<PyTypeObject *>(newType));
- if (bases.size() == 1) {
- SbkObjectTypePrivate *parentType = PepType_SOTP(bases.front());
- sotp->mi_offsets = parentType->mi_offsets;
- sotp->mi_init = parentType->mi_init;
- sotp->mi_specialcast = parentType->mi_specialcast;
- sotp->type_discovery = parentType->type_discovery;
- sotp->cpp_dtor = parentType->cpp_dtor;
- sotp->is_multicpp = 0;
- sotp->converter = parentType->converter;
- } else {
- sotp->mi_offsets = nullptr;
- sotp->mi_init = nullptr;
- sotp->mi_specialcast = nullptr;
- sotp->type_discovery = nullptr;
- sotp->cpp_dtor = nullptr;
- sotp->is_multicpp = 1;
- sotp->converter = nullptr;
- }
- if (bases.size() == 1)
- sotp->original_name = strdup(PepType_SOTP(bases.front())->original_name);
- else
- sotp->original_name = strdup("object");
- sotp->user_data = nullptr;
- sotp->d_func = nullptr;
- sotp->is_user_type = 1;
-
- for (SbkObjectType *base : bases) {
- if (PepType_SOTP(base)->subtype_init)
- PepType_SOTP(base)->subtype_init(newType, args, kwds);
- }
-
- return reinterpret_cast<PyObject *>(newType);
-}
-
-static PyObject *_setupNew(SbkObject *self, PyTypeObject *subtype)
-{
- Py_INCREF(reinterpret_cast<PyObject *>(subtype));
- auto d = new SbkObjectPrivate;
-
- SbkObjectTypePrivate *sotp = PepType_SOTP(subtype);
- int numBases = ((sotp && sotp->is_multicpp) ?
- Shiboken::getNumberOfCppBaseClasses(subtype) : 1);
- d->cptr = new void *[numBases];
- std::memset(d->cptr, 0, sizeof(void *) *size_t(numBases));
- d->hasOwnership = 1;
- d->containsCppWrapper = 0;
- d->validCppObject = 0;
- d->parentInfo = nullptr;
- d->referredObjects = nullptr;
- d->cppObjectCreated = 0;
- self->ob_dict = nullptr;
- self->weakreflist = nullptr;
- self->d = d;
- return reinterpret_cast<PyObject *>(self);
-}
-
-PyObject *SbkObjectTpNew(PyTypeObject *subtype, PyObject *, PyObject *)
-{
- SbkObject *self = PyObject_GC_New(SbkObject, subtype);
- PyObject *res = _setupNew(self, subtype);
- PyObject_GC_Track(reinterpret_cast<PyObject *>(self));
- return res;
-}
-
-PyObject *SbkQAppTpNew(PyTypeObject *subtype, PyObject *, PyObject *)
-{
- // PYSIDE-571:
- // For qApp, we need to create a singleton Python object.
- // We cannot track this with the GC, because it is a static variable!
-
- // Python 2 has a weird handling of flags in derived classes that Python 3
- // does not have. Observed with bug_307.py.
- // But it could theoretically also happen with Python3.
- // Therefore we enforce that there is no GC flag, ever!
-
- // PYSIDE-560:
- // We avoid to use this in Python 3, because we have a hard time to get
- // write access to these flags
-#ifndef IS_PY3K
- if (PyType_HasFeature(subtype, Py_TPFLAGS_HAVE_GC)) {
- subtype->tp_flags &= ~Py_TPFLAGS_HAVE_GC;
- subtype->tp_free = PyObject_Del;
- }
-#endif
- auto self = reinterpret_cast<SbkObject *>(MakeQAppWrapper(subtype));
- return self == nullptr ? nullptr : _setupNew(self, subtype);
-}
-
-PyObject *SbkDummyNew(PyTypeObject *type, PyObject *, PyObject *)
-{
- // PYSIDE-595: Give the same error as type_call does when tp_new is NULL.
- PyErr_Format(PyExc_TypeError,
- "cannot create '%.100s' instances ¯\\_(ツ)_/¯",
- type->tp_name);
- return nullptr;
-}
-
-PyObject *SbkType_FromSpec(PyType_Spec *spec)
-{
- return SbkType_FromSpecWithBases(spec, nullptr);
-}
-
-PyObject *SbkType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
-{
- // PYSIDE-1286: Generate correct __module__ and __qualname__
- // The name field can now be extended by an "n:" prefix which is
- // the number of modules in the name. The default is 1.
- //
- // Example:
- // "2:mainmod.submod.mainclass.subclass"
- // results in
- // __module__ : "mainmod.submod"
- // __qualname__ : "mainclass.subclass"
- // __name__ : "subclass"
-
- PyType_Spec new_spec = *spec;
- const char *colon = strchr(spec->name, ':');
- assert(colon);
- int package_level = atoi(spec->name);
- const char *mod = new_spec.name = colon + 1;
-
- PyObject *type = PyType_FromSpecWithBases(&new_spec, bases);
- if (type == nullptr)
- return nullptr;
-
- const char *qual = mod;
- for (int idx = package_level; idx > 0; --idx) {
- const char *dot = strchr(qual, '.');
- if (!dot)
- break;
- qual = dot + 1;
- }
- int mlen = qual - mod - 1;
- Shiboken::AutoDecRef module(Shiboken::String::fromCString(mod, mlen));
- Shiboken::AutoDecRef qualname(Shiboken::String::fromCString(qual));
- if (PyObject_SetAttr(type, Shiboken::PyMagicName::module(), module) < 0)
- return nullptr;
- if (PyObject_SetAttr(type, Shiboken::PyMagicName::qualname(), qualname) < 0)
- return nullptr;
- return type;
-}
-
-} //extern "C"
-
-
-namespace
-{
-
-void _destroyParentInfo(SbkObject *obj, bool keepReference)
-{
- Shiboken::ParentInfo *pInfo = obj->d->parentInfo;
- if (pInfo) {
- while(!pInfo->children.empty()) {
- SbkObject *first = *pInfo->children.begin();
- // Mark child as invalid
- Shiboken::Object::invalidate(first);
- Shiboken::Object::removeParent(first, false, keepReference);
- }
- Shiboken::Object::removeParent(obj, false);
- }
-}
-
-}
-
-namespace Shiboken
-{
-bool walkThroughClassHierarchy(PyTypeObject *currentType, HierarchyVisitor *visitor)
-{
- PyObject *bases = currentType->tp_bases;
- Py_ssize_t numBases = PyTuple_GET_SIZE(bases);
- bool result = false;
- for (int i = 0; !result && i < numBases; ++i) {
- auto type = reinterpret_cast<PyTypeObject *>(PyTuple_GET_ITEM(bases, i));
- if (PyType_IsSubtype(type, reinterpret_cast<PyTypeObject *>(SbkObject_TypeF()))) {
- auto sbkType = reinterpret_cast<SbkObjectType *>(type);
- result = PepType_SOTP(sbkType)->is_user_type
- ? walkThroughClassHierarchy(type, visitor) : visitor->visit(sbkType);
- }
- }
- return result;
-}
-
-// Wrapper metatype and base type ----------------------------------------------------------
-
-HierarchyVisitor::HierarchyVisitor() = default;
-HierarchyVisitor::~HierarchyVisitor() = default;
-
-bool BaseCountVisitor::visit(SbkObjectType *)
-{
- m_count++;
- return false;
-}
-
-bool BaseAccumulatorVisitor::visit(SbkObjectType *node)
-{
- m_bases.push_back(node);
- return false;
-}
-
-bool GetIndexVisitor::visit(SbkObjectType *node)
-{
- m_index++;
- return PyType_IsSubtype(reinterpret_cast<PyTypeObject *>(node), m_desiredType);
-}
-
-bool DtorAccumulatorVisitor::visit(SbkObjectType *node)
-{
- m_entries.push_back(DestructorEntry{PepType_SOTP(node)->cpp_dtor,
- m_pyObject->d->cptr[m_entries.size()]});
- return false;
-}
-
-void _initMainThreadId(); // helper.cpp
-
-namespace Conversions { void init(); }
-
-void init()
-{
- static bool shibokenAlreadInitialised = false;
- if (shibokenAlreadInitialised)
- return;
-
- _initMainThreadId();
-
- Conversions::init();
-
- PyEval_InitThreads();
-
- //Init private data
- Pep384_Init();
-
- Shiboken::ObjectType::initPrivateData(SbkObject_TypeF());
-
- if (PyType_Ready(SbkEnumType_TypeF()) < 0)
- Py_FatalError("[libshiboken] Failed to initialize Shiboken.SbkEnumType metatype.");
-
- if (PyType_Ready(SbkObjectType_TypeF()) < 0)
- Py_FatalError("[libshiboken] Failed to initialize Shiboken.BaseWrapperType metatype.");
-
- if (PyType_Ready(reinterpret_cast<PyTypeObject *>(SbkObject_TypeF())) < 0)
- Py_FatalError("[libshiboken] Failed to initialize Shiboken.BaseWrapper type.");
-
- VoidPtr::init();
-
- shibokenAlreadInitialised = true;
-}
-
-// setErrorAboutWrongArguments now gets overload info from the signature module.
-void setErrorAboutWrongArguments(PyObject *args, const char *funcName)
-{
- SetError_Argument(args, funcName);
-}
-
-class FindBaseTypeVisitor : public HierarchyVisitor
-{
-public:
- explicit FindBaseTypeVisitor(PyTypeObject *typeToFind) : m_typeToFind(typeToFind) {}
-
- bool visit(SbkObjectType *node) override
- {
- return reinterpret_cast<PyTypeObject *>(node) == m_typeToFind;
- }
-
-private:
- PyTypeObject *m_typeToFind;
-};
-
-std::vector<SbkObject *> splitPyObject(PyObject *pyObj)
-{
- std::vector<SbkObject *> result;
- if (PySequence_Check(pyObj)) {
- AutoDecRef lst(PySequence_Fast(pyObj, "Invalid keep reference object."));
- if (!lst.isNull()) {
- for (Py_ssize_t i = 0, i_max = PySequence_Fast_GET_SIZE(lst.object()); i < i_max; ++i) {
- PyObject *item = PySequence_Fast_GET_ITEM(lst.object(), i);
- if (Object::checkType(item))
- result.push_back(reinterpret_cast<SbkObject *>(item));
- }
- }
- } else {
- result.push_back(reinterpret_cast<SbkObject *>(pyObj));
- }
- return result;
-}
-
-template <class Iterator>
-inline void decRefPyObjectList(Iterator i1, Iterator i2)
-{
- for (; i1 != i2; ++i1)
- Py_DECREF(i1->second);
-}
-
-namespace ObjectType
-{
-
-bool checkType(PyTypeObject *type)
-{
- return PyType_IsSubtype(type, reinterpret_cast<PyTypeObject *>(SbkObject_TypeF())) != 0;
-}
-
-bool isUserType(PyTypeObject *type)
-{
- return checkType(type) && PepType_SOTP(type)->is_user_type;
-}
-
-bool canCallConstructor(PyTypeObject *myType, PyTypeObject *ctorType)
-{
- FindBaseTypeVisitor visitor(ctorType);
- if (!walkThroughClassHierarchy(myType, &visitor)) {
- PyErr_Format(PyExc_TypeError, "%s isn't a direct base class of %s", ctorType->tp_name, myType->tp_name);
- return false;
- }
- return true;
-}
-
-bool hasCast(SbkObjectType *type)
-{
- return PepType_SOTP(type)->mi_specialcast != nullptr;
-}
-
-void *cast(SbkObjectType *sourceType, SbkObject *obj, PyTypeObject *targetType)
-{
- return PepType_SOTP(sourceType)->mi_specialcast(Object::cppPointer(obj, targetType),
- reinterpret_cast<SbkObjectType *>(targetType));
-}
-
-void setCastFunction(SbkObjectType *type, SpecialCastFunction func)
-{
- PepType_SOTP(type)->mi_specialcast = func;
-}
-
-void setOriginalName(SbkObjectType *type, const char *name)
-{
- SbkObjectTypePrivate *sotp = PepType_SOTP(type);
- if (sotp->original_name)
- free(sotp->original_name);
- sotp->original_name = strdup(name);
-}
-
-const char *getOriginalName(SbkObjectType *type)
-{
- return PepType_SOTP(type)->original_name;
-}
-
-void setTypeDiscoveryFunctionV2(SbkObjectType *type, TypeDiscoveryFuncV2 func)
-{
- PepType_SOTP(type)->type_discovery = func;
-}
-
-void copyMultipleInheritance(SbkObjectType *type, SbkObjectType *other)
-{
- PepType_SOTP(type)->mi_init = PepType_SOTP(other)->mi_init;
- PepType_SOTP(type)->mi_offsets = PepType_SOTP(other)->mi_offsets;
- PepType_SOTP(type)->mi_specialcast = PepType_SOTP(other)->mi_specialcast;
-}
-
-void setMultipleInheritanceFunction(SbkObjectType *type, MultipleInheritanceInitFunction function)
-{
- PepType_SOTP(type)->mi_init = function;
-}
-
-MultipleInheritanceInitFunction getMultipleInheritanceFunction(SbkObjectType *type)
-{
- return PepType_SOTP(type)->mi_init;
-}
-
-void setDestructorFunction(SbkObjectType *type, ObjectDestructor func)
-{
- PepType_SOTP(type)->cpp_dtor = func;
-}
-
-void initPrivateData(SbkObjectType *type)
-{
- PepType_SOTP(type) = new SbkObjectTypePrivate;
- memset(PepType_SOTP(type), 0, sizeof(SbkObjectTypePrivate));
-}
-
-SbkObjectType *
-introduceWrapperType(PyObject *enclosingObject,
- const char *typeName,
- const char *originalName,
- PyType_Spec *typeSpec,
- const char *signatureStrings[],
- ObjectDestructor cppObjDtor,
- SbkObjectType *baseType,
- PyObject *baseTypes,
- unsigned wrapperFlags)
-{
- typeSpec->slots[0].pfunc = reinterpret_cast<void *>(baseType ? baseType : SbkObject_TypeF());
-
- PyObject *heaptype = SbkType_FromSpecWithBases(typeSpec, baseTypes);
- Py_TYPE(heaptype) = SbkObjectType_TypeF();
- Py_INCREF(Py_TYPE(heaptype));
- auto *type = reinterpret_cast<SbkObjectType *>(heaptype);
-#if PY_VERSION_HEX < 0x03000000
- // PYSIDE-1051: The newly created type needs the PYSIDE-816 wrapper, too.
- if (patch_tp_new_wrapper(&type->type) < 0)
- return nullptr;
-#endif
- if (baseType) {
- if (baseTypes) {
- for (int i = 0; i < PySequence_Fast_GET_SIZE(baseTypes); ++i)
- BindingManager::instance().addClassInheritance(reinterpret_cast<SbkObjectType *>(PySequence_Fast_GET_ITEM(baseTypes, i)), type);
- } else {
- BindingManager::instance().addClassInheritance(baseType, type);
- }
- }
- // PYSIDE-510: Here is the single change to support signatures.
- if (SbkSpecial_Type_Ready(enclosingObject, reinterpret_cast<PyTypeObject *>(type), signatureStrings) < 0) {
- std::cerr << "Warning: " << __FUNCTION__ << " returns nullptr for "
- << typeName << '/' << originalName << " due to SbkSpecial_Type_Ready() failing\n";
- return nullptr;
- }
-
- initPrivateData(type);
- auto sotp = PepType_SOTP(type);
- if (wrapperFlags & DeleteInMainThread)
- sotp->delete_in_main_thread = 1;
-
- setOriginalName(type, originalName);
- setDestructorFunction(type, cppObjDtor);
- auto *ob_type = reinterpret_cast<PyObject *>(type);
-
- if (wrapperFlags & InnerClass)
- return PyDict_SetItemString(enclosingObject, typeName, ob_type) == 0 ? type : nullptr;
-
- // PyModule_AddObject steals type's reference.
- Py_INCREF(ob_type);
- if (PyModule_AddObject(enclosingObject, typeName, ob_type) != 0) {
- std::cerr << "Warning: " << __FUNCTION__ << " returns nullptr for "
- << typeName << '/' << originalName << " due to PyModule_AddObject(enclosingObject="
- << enclosingObject << ",ob_type=" << ob_type << ") failing\n";
- return nullptr;
- }
- return type;
-}
-
-void setSubTypeInitHook(SbkObjectType *type, SubTypeInitHook func)
-{
- PepType_SOTP(type)->subtype_init = func;
-}
-
-void *getTypeUserData(SbkObjectType *type)
-{
- return PepType_SOTP(type)->user_data;
-}
-
-void setTypeUserData(SbkObjectType *type, void *userData, DeleteUserDataFunc d_func)
-{
- SbkObjectTypePrivate *sotp = PepType_SOTP(type);
- sotp->user_data = userData;
- sotp->d_func = d_func;
-}
-
-// Try to find the exact type of cptr.
-SbkObjectType *typeForTypeName(const char *typeName)
-{
- SbkObjectType *result{};
- if (typeName) {
- if (PyTypeObject *pyType = Shiboken::Conversions::getPythonTypeObject(typeName))
- result = reinterpret_cast<SbkObjectType *>(pyType);
- }
- return result;
-}
-
-bool hasSpecialCastFunction(SbkObjectType *sbkType)
-{
- const SbkObjectTypePrivate *d = PepType_SOTP(sbkType);
- return d != nullptr && d->mi_specialcast != nullptr;
-}
-
-} // namespace ObjectType
-
-
-namespace Object
-{
-
-static void recursive_invalidate(SbkObject *self, std::set<SbkObject *>& seen);
-
-bool checkType(PyObject *pyObj)
-{
- return ObjectType::checkType(Py_TYPE(pyObj));
-}
-
-bool isUserType(PyObject *pyObj)
-{
- return ObjectType::isUserType(Py_TYPE(pyObj));
-}
-
-Py_hash_t hash(PyObject *pyObj)
-{
- assert(Shiboken::Object::checkType(pyObj));
- return reinterpret_cast<Py_hash_t>(pyObj);
-}
-
-static void setSequenceOwnership(PyObject *pyObj, bool owner)
-{
-
- bool has_length = true;
-
- if (!pyObj)
- return;
-
- if (PySequence_Size(pyObj) < 0) {
- PyErr_Clear();
- has_length = false;
- }
-
- if (PySequence_Check(pyObj) && has_length) {
- Py_ssize_t size = PySequence_Size(pyObj);
- if (size > 0) {
- const auto objs = splitPyObject(pyObj);
- if (owner) {
- for (SbkObject *o : objs)
- getOwnership(o);
- } else {
- for (SbkObject *o : objs)
- releaseOwnership(o);
- }
- }
- } else if (Object::checkType(pyObj)) {
- if (owner)
- getOwnership(reinterpret_cast<SbkObject *>(pyObj));
- else
- releaseOwnership(reinterpret_cast<SbkObject *>(pyObj));
- }
-}
-
-void setValidCpp(SbkObject *pyObj, bool value)
-{
- pyObj->d->validCppObject = value;
-}
-
-void setHasCppWrapper(SbkObject *pyObj, bool value)
-{
- pyObj->d->containsCppWrapper = value;
-}
-
-bool hasCppWrapper(SbkObject *pyObj)
-{
- return pyObj->d->containsCppWrapper;
-}
-
-bool wasCreatedByPython(SbkObject *pyObj)
-{
- return pyObj->d->cppObjectCreated;
-}
-
-void callCppDestructors(SbkObject *pyObj)
-{
- PyTypeObject *type = Py_TYPE(pyObj);
- SbkObjectTypePrivate *sotp = PepType_SOTP(type);
- if (sotp->is_multicpp) {
- Shiboken::DtorAccumulatorVisitor visitor(pyObj);
- Shiboken::walkThroughClassHierarchy(type, &visitor);
- callDestructor(visitor.entries());
- } else {
- Shiboken::ThreadStateSaver threadSaver;
- threadSaver.save();
- sotp->cpp_dtor(pyObj->d->cptr[0]);
- }
-
- /* invalidate needs to be called before deleting pointer array because
- it needs to delete entries for them from the BindingManager hash table;
- also release wrapper explicitly if object contains C++ wrapper because
- invalidate doesn't */
- invalidate(pyObj);
- if (pyObj->d->validCppObject && pyObj->d->containsCppWrapper) {
- BindingManager::instance().releaseWrapper(pyObj);
- }
-
- delete[] pyObj->d->cptr;
- pyObj->d->cptr = nullptr;
- pyObj->d->validCppObject = false;
-}
-
-bool hasOwnership(SbkObject *pyObj)
-{
- return pyObj->d->hasOwnership;
-}
-
-void getOwnership(SbkObject *self)
-{
- // skip if already have the ownership
- if (self->d->hasOwnership)
- return;
-
- // skip if this object has parent
- if (self->d->parentInfo && self->d->parentInfo->parent)
- return;
-
- // Get back the ownership
- self->d->hasOwnership = true;
-
- if (self->d->containsCppWrapper)
- Py_DECREF(reinterpret_cast<PyObject *>(self)); // Remove extra ref
- else
- makeValid(self); // Make the object valid again
-}
-
-void getOwnership(PyObject *pyObj)
-{
- if (pyObj)
- setSequenceOwnership(pyObj, true);
-}
-
-void releaseOwnership(SbkObject *self)
-{
- // skip if the ownership have already moved to c++
- auto *selfType = reinterpret_cast<SbkObjectType *>(Py_TYPE(self));
- if (!self->d->hasOwnership || Shiboken::Conversions::pythonTypeIsValueType(PepType_SOTP(selfType)->converter))
- return;
-
- // remove object ownership
- self->d->hasOwnership = false;
-
- // If We have control over object life
- if (self->d->containsCppWrapper)
- Py_INCREF(reinterpret_cast<PyObject *>(self)); // keep the python object alive until the wrapper destructor call
- else
- invalidate(self); // If I do not know when this object will die We need to invalidate this to avoid use after
-}
-
-void releaseOwnership(PyObject *self)
-{
- setSequenceOwnership(self, false);
-}
-
-/* Needed forward declarations */
-static void recursive_invalidate(PyObject *pyobj, std::set<SbkObject *>& seen);
-static void recursive_invalidate(SbkObject *self, std::set<SbkObject *> &seen);
-
-void invalidate(PyObject *pyobj)
-{
- std::set<SbkObject *> seen;
- recursive_invalidate(pyobj, seen);
-}
-
-void invalidate(SbkObject *self)
-{
- std::set<SbkObject *> seen;
- recursive_invalidate(self, seen);
-}
-
-static void recursive_invalidate(PyObject *pyobj, std::set<SbkObject *> &seen)
-{
- const auto objs = splitPyObject(pyobj);
- for (SbkObject *o : objs)
- recursive_invalidate(o, seen);
-}
-
-static void recursive_invalidate(SbkObject *self, std::set<SbkObject *> &seen)
-{
- // Skip if this object not is a valid object or if it's already been seen
- if (!self || reinterpret_cast<PyObject *>(self) == Py_None || seen.find(self) != seen.end())
- return;
- seen.insert(self);
-
- if (!self->d->containsCppWrapper) {
- self->d->validCppObject = false; // Mark object as invalid only if this is not a wrapper class
- BindingManager::instance().releaseWrapper(self);
- }
-
- // If it is a parent invalidate all children.
- if (self->d->parentInfo) {
- // Create a copy because this list can be changed during the process
- ChildrenList copy = self->d->parentInfo->children;
-
- for (SbkObject *child : copy) {
- // invalidate the child
- recursive_invalidate(child, seen);
-
- // if the parent not is a wrapper class, then remove children from him, because We do not know when this object will be destroyed
- if (!self->d->validCppObject)
- removeParent(child, true, true);
- }
- }
-
- // If has ref to other objects invalidate all
- if (self->d->referredObjects) {
- RefCountMap &refCountMap = *(self->d->referredObjects);
- for (auto it = refCountMap.begin(), end = refCountMap.end(); it != end; ++it)
- recursive_invalidate(it->second, seen);
- }
-}
-
-void makeValid(SbkObject *self)
-{
- // Skip if this object not is a valid object
- if (!self || reinterpret_cast<PyObject *>(self) == Py_None || self->d->validCppObject)
- return;
-
- // Mark object as invalid only if this is not a wrapper class
- self->d->validCppObject = true;
-
- // If it is a parent make all children valid
- if (self->d->parentInfo) {
- for (SbkObject *child : self->d->parentInfo->children)
- makeValid(child);
- }
-
- // If has ref to other objects make all valid again
- if (self->d->referredObjects) {
- RefCountMap &refCountMap = *(self->d->referredObjects);
- RefCountMap::iterator iter;
- for (auto it = refCountMap.begin(), end = refCountMap.end(); it != end; ++it) {
- if (Shiboken::Object::checkType(it->second))
- makeValid(reinterpret_cast<SbkObject *>(it->second));
- }
- }
-}
-
-void *cppPointer(SbkObject *pyObj, PyTypeObject *desiredType)
-{
- PyTypeObject *type = Py_TYPE(pyObj);
- int idx = 0;
- if (PepType_SOTP(reinterpret_cast<SbkObjectType *>(type))->is_multicpp)
- idx = getTypeIndexOnHierarchy(type, desiredType);
- if (pyObj->d->cptr)
- return pyObj->d->cptr[idx];
- return nullptr;
-}
-
-std::vector<void *> cppPointers(SbkObject *pyObj)
-{
- int n = getNumberOfCppBaseClasses(Py_TYPE(pyObj));
- std::vector<void *> ptrs(n);
- for (int i = 0; i < n; ++i)
- ptrs[i] = pyObj->d->cptr[i];
- return ptrs;
-}
-
-
-bool setCppPointer(SbkObject *sbkObj, PyTypeObject *desiredType, void *cptr)
-{
- int idx = 0;
- PyTypeObject *type = Py_TYPE(sbkObj);
- if (PepType_SOTP(type)->is_multicpp)
- idx = getTypeIndexOnHierarchy(type, desiredType);
-
- const bool alreadyInitialized = sbkObj->d->cptr[idx] != nullptr;
- if (alreadyInitialized)
- PyErr_SetString(PyExc_RuntimeError, "You can't initialize an object twice!");
- else
- sbkObj->d->cptr[idx] = cptr;
-
- sbkObj->d->cppObjectCreated = true;
- return !alreadyInitialized;
-}
-
-bool isValid(PyObject *pyObj)
-{
- if (!pyObj || pyObj == Py_None
- || Py_TYPE(Py_TYPE(pyObj)) != SbkObjectType_TypeF()) {
- return true;
- }
-
- auto priv = reinterpret_cast<SbkObject *>(pyObj)->d;
-
- if (!priv->cppObjectCreated && isUserType(pyObj)) {
- PyErr_Format(PyExc_RuntimeError, "'__init__' method of object's base class (%s) not called.",
- Py_TYPE(pyObj)->tp_name);
- return false;
- }
-
- if (!priv->validCppObject) {
- PyErr_Format(PyExc_RuntimeError, "Internal C++ object (%s) already deleted.",
- Py_TYPE(pyObj)->tp_name);
- return false;
- }
-
- return true;
-}
-
-bool isValid(SbkObject *pyObj, bool throwPyError)
-{
- if (!pyObj)
- return false;
-
- SbkObjectPrivate *priv = pyObj->d;
- if (!priv->cppObjectCreated && isUserType(reinterpret_cast<PyObject *>(pyObj))) {
- if (throwPyError)
- PyErr_Format(PyExc_RuntimeError, "Base constructor of the object (%s) not called.",
- Py_TYPE(pyObj)->tp_name);
- return false;
- }
-
- if (!priv->validCppObject) {
- if (throwPyError)
- PyErr_Format(PyExc_RuntimeError, "Internal C++ object (%s) already deleted.",
- (Py_TYPE(pyObj))->tp_name);
- return false;
- }
-
- return true;
-}
-
-bool isValid(PyObject *pyObj, bool throwPyError)
-{
- if (!pyObj || pyObj == Py_None ||
- !PyType_IsSubtype(Py_TYPE(pyObj), reinterpret_cast<PyTypeObject *>(SbkObject_TypeF()))) {
- return true;
- }
- return isValid(reinterpret_cast<SbkObject *>(pyObj), throwPyError);
-}
-
-SbkObject *findColocatedChild(SbkObject *wrapper,
- const SbkObjectType *instanceType)
-{
- // Degenerate case, wrapper is the correct wrapper.
- if (reinterpret_cast<const void *>(Py_TYPE(wrapper)) == reinterpret_cast<const void *>(instanceType))
- return wrapper;
-
- if (!(wrapper->d && wrapper->d->cptr))
- return nullptr;
-
- ParentInfo *pInfo = wrapper->d->parentInfo;
- if (!pInfo)
- return nullptr;
-
- ChildrenList &children = pInfo->children;
-
- for (SbkObject *child : children) {
- if (!(child->d && child->d->cptr))
- continue;
- if (child->d->cptr[0] == wrapper->d->cptr[0]) {
- return reinterpret_cast<const void *>(Py_TYPE(child)) == reinterpret_cast<const void *>(instanceType)
- ? child : findColocatedChild(child, instanceType);
- }
- }
- return nullptr;
-}
-
-PyObject *newObject(SbkObjectType *instanceType,
- void *cptr,
- bool hasOwnership,
- bool isExactType,
- const char *typeName)
-{
- // Try to find the exact type of cptr.
- if (!isExactType) {
- if (SbkObjectType *exactType = ObjectType::typeForTypeName(typeName))
- instanceType = exactType;
- else
- instanceType = BindingManager::instance().resolveType(&cptr, instanceType);
- }
-
- bool shouldCreate = true;
- bool shouldRegister = true;
- SbkObject *self = nullptr;
-
- // Some logic to ensure that colocated child field does not overwrite the parent
- if (BindingManager::instance().hasWrapper(cptr)) {
- SbkObject *existingWrapper = BindingManager::instance().retrieveWrapper(cptr);
-
- self = findColocatedChild(existingWrapper, instanceType);
- if (self) {
- // Wrapper already registered for cptr.
- // This should not ideally happen, binding code should know when a wrapper
- // already exists and retrieve it instead.
- shouldRegister = shouldCreate = false;
- } else if (hasOwnership &&
- (!(Shiboken::Object::hasCppWrapper(existingWrapper) ||
- Shiboken::Object::hasOwnership(existingWrapper)))) {
- // Old wrapper is likely junk, since we have ownership and it doesn't.
- BindingManager::instance().releaseWrapper(existingWrapper);
- } else {
- // Old wrapper may be junk caused by some bug in identifying object deletion
- // but it may not be junk when a colocated field is accessed for an
- // object which was not created by python (returned from c++ factory function).
- // Hence we cannot release the wrapper confidently so we do not register.
- shouldRegister = false;
- }
- }
-
- if (shouldCreate) {
- self = reinterpret_cast<SbkObject *>(SbkObjectTpNew(reinterpret_cast<PyTypeObject *>(instanceType), nullptr, nullptr));
- self->d->cptr[0] = cptr;
- self->d->hasOwnership = hasOwnership;
- self->d->validCppObject = 1;
- if (shouldRegister) {
- BindingManager::instance().registerWrapper(self, cptr);
- }
- } else {
- Py_IncRef(reinterpret_cast<PyObject *>(self));
- }
- return reinterpret_cast<PyObject *>(self);
-}
-
-void destroy(SbkObject *self, void *cppData)
-{
- // Skip if this is called with NULL pointer this can happen in derived classes
- if (!self)
- return;
-
- // This can be called in c++ side
- Shiboken::GilState gil;
-
- // Remove all references attached to this object
- clearReferences(self);
-
- // Remove the object from parent control
-
- // Verify if this object has parent
- bool hasParent = (self->d->parentInfo && self->d->parentInfo->parent);
-
- if (self->d->parentInfo) {
- // Check for children information and make all invalid if they exists
- _destroyParentInfo(self, true);
- // If this object has parent then the pyobject can be invalid now, because we remove the last ref after remove from parent
- }
-
- //if !hasParent this object could still alive
- if (!hasParent && self->d->containsCppWrapper && !self->d->hasOwnership) {
- // Remove extra ref used by c++ object this will case the pyobject destruction
- // This can cause the object death
- Py_DECREF(reinterpret_cast<PyObject *>(self));
- }
-
- //Python Object is not destroyed yet
- if (cppData && Shiboken::BindingManager::instance().hasWrapper(cppData)) {
- // Remove from BindingManager
- Shiboken::BindingManager::instance().releaseWrapper(self);
- self->d->hasOwnership = false;
-
- // the cpp object instance was deleted
- delete[] self->d->cptr;
- self->d->cptr = nullptr;
- }
-
- // After this point the object can be death do not use the self pointer bellow
-}
-
-void removeParent(SbkObject *child, bool giveOwnershipBack, bool keepReference)
-{
- ParentInfo *pInfo = child->d->parentInfo;
- if (!pInfo || !pInfo->parent) {
- if (pInfo && pInfo->hasWrapperRef) {
- pInfo->hasWrapperRef = false;
- }
- return;
- }
-
- ChildrenList &oldBrothers = pInfo->parent->d->parentInfo->children;
- // Verify if this child is part of parent list
- auto iChild = oldBrothers.find(child);
- if (iChild == oldBrothers.end())
- return;
-
- oldBrothers.erase(iChild);
-
- pInfo->parent = nullptr;
-
- // This will keep the wrapper reference, will wait for wrapper destruction to remove that
- if (keepReference &&
- child->d->containsCppWrapper) {
- //If have already a extra ref remove this one
- if (pInfo->hasWrapperRef)
- Py_DECREF(child);
- else
- pInfo->hasWrapperRef = true;
- return;
- }
-
- // Transfer ownership back to Python
- child->d->hasOwnership = giveOwnershipBack;
-
- // Remove parent ref
- Py_DECREF(child);
-}
-
-void setParent(PyObject *parent, PyObject *child)
-{
- if (!child || child == Py_None || child == parent)
- return;
-
- /*
- * setParent is recursive when the child is a native Python sequence, i.e. objects not binded by Shiboken
- * like tuple and list.
- *
- * This "limitation" exists to fix the following problem: A class multiple inherits QObject and QString,
- * so if you pass this class to someone that takes the ownership, we CAN'T enter in this if, but hey! QString
- * follows the sequence protocol.
- */
- if (PySequence_Check(child) && !Object::checkType(child)) {
- Shiboken::AutoDecRef seq(PySequence_Fast(child, nullptr));
- for (Py_ssize_t i = 0, max = PySequence_Size(seq); i < max; ++i)
- setParent(parent, PySequence_Fast_GET_ITEM(seq.object(), i));
- return;
- }
-
- bool parentIsNull = !parent || parent == Py_None;
- auto parent_ = reinterpret_cast<SbkObject *>(parent);
- auto child_ = reinterpret_cast<SbkObject *>(child);
-
- if (!parentIsNull) {
- if (!parent_->d->parentInfo)
- parent_->d->parentInfo = new ParentInfo;
-
- // do not re-add a child
- if (child_->d->parentInfo && (child_->d->parentInfo->parent == parent_))
- return;
- }
-
- ParentInfo *pInfo = child_->d->parentInfo;
- bool hasAnotherParent = pInfo && pInfo->parent && pInfo->parent != parent_;
-
- //Avoid destroy child during reparent operation
- Py_INCREF(child);
-
- // check if we need to remove this child from the old parent
- if (parentIsNull || hasAnotherParent)
- removeParent(child_);
-
- // Add the child to the new parent
- pInfo = child_->d->parentInfo;
- if (!parentIsNull) {
- if (!pInfo)
- pInfo = child_->d->parentInfo = new ParentInfo;
-
- pInfo->parent = parent_;
- parent_->d->parentInfo->children.insert(child_);
-
- // Add Parent ref
- Py_INCREF(child_);
-
- // Remove ownership
- child_->d->hasOwnership = false;
- }
-
- // Remove previous safe ref
- Py_DECREF(child);
-}
-
-void deallocData(SbkObject *self, bool cleanup)
-{
- // Make cleanup if this is not a wrapper otherwise this will be done on wrapper destructor
- if(cleanup) {
- removeParent(self);
-
- if (self->d->parentInfo)
- _destroyParentInfo(self, true);
-
- clearReferences(self);
- }
-
- if (self->d->cptr) {
- // Remove from BindingManager
- Shiboken::BindingManager::instance().releaseWrapper(self);
- delete[] self->d->cptr;
- self->d->cptr = nullptr;
- // delete self->d; PYSIDE-205: wrong!
- }
- delete self->d; // PYSIDE-205: always delete d.
- Py_XDECREF(self->ob_dict);
-
- // PYSIDE-571: qApp is no longer allocated.
- if (PyObject_IS_GC(reinterpret_cast<PyObject *>(self)))
- Py_TYPE(self)->tp_free(self);
-}
-
-void setTypeUserData(SbkObject *wrapper, void *userData, DeleteUserDataFunc d_func)
-{
- SbkObjectTypePrivate *sotp = PepType_SOTP(Py_TYPE(wrapper));
- if (sotp->user_data)
- sotp->d_func(sotp->user_data);
-
- sotp->d_func = d_func;
- sotp->user_data = userData;
-}
-
-void *getTypeUserData(SbkObject *wrapper)
-{
- return PepType_SOTP(Py_TYPE(wrapper))->user_data;
-}
-
-static inline bool isNone(const PyObject *o)
-{
- return o == nullptr || o == Py_None;
-}
-
-static void removeRefCountKey(SbkObject *self, const char *key)
-{
- if (self->d->referredObjects) {
- const auto iterPair = self->d->referredObjects->equal_range(key);
- if (iterPair.first != iterPair.second) {
- decRefPyObjectList(iterPair.first, iterPair.second);
- self->d->referredObjects->erase(iterPair.first, iterPair.second);
- }
- }
-}
-
-void keepReference(SbkObject *self, const char *key, PyObject *referredObject, bool append)
-{
- if (isNone(referredObject)) {
- removeRefCountKey(self, key);
- return;
- }
-
- if (!self->d->referredObjects) {
- self->d->referredObjects =
- new Shiboken::RefCountMap{RefCountMap::value_type{key, referredObject}};
- Py_INCREF(referredObject);
- return;
- }
-
- RefCountMap &refCountMap = *(self->d->referredObjects);
- const auto iterPair = refCountMap.equal_range(key);
- if (std::any_of(iterPair.first, iterPair.second,
- [referredObject](const RefCountMap::value_type &v) { return v.second == referredObject; })) {
- return;
- }
-
- if (!append && iterPair.first != iterPair.second) {
- decRefPyObjectList(iterPair.first, iterPair.second);
- refCountMap.erase(iterPair.first, iterPair.second);
- }
-
- refCountMap.insert(RefCountMap::value_type{key, referredObject});
- Py_INCREF(referredObject);
-}
-
-void removeReference(SbkObject *self, const char *key, PyObject *referredObject)
-{
- if (!isNone(referredObject))
- removeRefCountKey(self, key);
-}
-
-void clearReferences(SbkObject *self)
-{
- if (!self->d->referredObjects)
- return;
-
- RefCountMap &refCountMap = *(self->d->referredObjects);
- for (auto it = refCountMap.begin(), end = refCountMap.end(); it != end; ++it)
- Py_DECREF(it->second);
- self->d->referredObjects->clear();
-}
-
-std::string info(SbkObject *self)
-{
- std::ostringstream s;
-
- if (self->d && self->d->cptr) {
- std::vector<SbkObjectType *> bases;
- if (ObjectType::isUserType(Py_TYPE(self)))
- bases = getCppBaseClasses(Py_TYPE(self));
- else
- bases.push_back(reinterpret_cast<SbkObjectType *>(Py_TYPE(self)));
-
- s << "C++ address....... ";
- for (size_t i = 0, size = bases.size(); i < size; ++i) {
- auto base = reinterpret_cast<PyTypeObject *>(bases[i]);
- s << base->tp_name << '/' << self->d->cptr[i] << ' ';
- }
- s << "\n";
- }
- else {
- s << "C++ address....... <<Deleted>>\n";
- }
-
- s << "hasOwnership...... " << bool(self->d->hasOwnership) << "\n"
- "containsCppWrapper " << self->d->containsCppWrapper << "\n"
- "validCppObject.... " << self->d->validCppObject << "\n"
- "wasCreatedByPython " << self->d->cppObjectCreated << "\n";
-
-
- if (self->d->parentInfo && self->d->parentInfo->parent) {
- s << "parent............ ";
- Shiboken::AutoDecRef parent(PyObject_Str(reinterpret_cast<PyObject *>(self->d->parentInfo->parent)));
- s << String::toCString(parent) << "\n";
- }
-
- if (self->d->parentInfo && !self->d->parentInfo->children.empty()) {
- s << "children.......... ";
- for (SbkObject *sbkChild : self->d->parentInfo->children) {
- Shiboken::AutoDecRef child(PyObject_Str(reinterpret_cast<PyObject *>(sbkChild)));
- s << String::toCString(child) << ' ';
- }
- s << '\n';
- }
-
- if (self->d->referredObjects && !self->d->referredObjects->empty()) {
- Shiboken::RefCountMap &map = *self->d->referredObjects;
- s << "referred objects.. ";
- std::string lastKey;
- for (auto it = map.begin(), end = map.end(); it != end; ++it) {
- if (it->first != lastKey) {
- if (!lastKey.empty())
- s << " ";
- s << '"' << it->first << "\" => ";
- lastKey = it->first;
- }
- Shiboken::AutoDecRef obj(PyObject_Str(it->second));
- s << String::toCString(obj) << ' ';
- }
- s << '\n';
- }
- return s.str();
-}
-
-} // namespace Object
-
-} // namespace Shiboken
diff --git a/sources/shiboken2/libshiboken/basewrapper.h b/sources/shiboken2/libshiboken/basewrapper.h
deleted file mode 100644
index 7248103cc..000000000
--- a/sources/shiboken2/libshiboken/basewrapper.h
+++ /dev/null
@@ -1,464 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef BASEWRAPPER_H
-#define BASEWRAPPER_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-#include <vector>
-#include <string>
-
-extern "C"
-{
-
-struct SbkConverter;
-struct SbkObjectPrivate;
-
-/// Base Python object for all the wrapped C++ classes.
-struct LIBSHIBOKEN_API SbkObject
-{
- PyObject_HEAD
- /// Instance dictionary.
- PyObject *ob_dict;
- /// List of weak references
- PyObject *weakreflist;
- SbkObjectPrivate *d;
-};
-
-
-/// PYSIDE-939: A general replacement for object_dealloc.
-LIBSHIBOKEN_API void Sbk_object_dealloc(PyObject *self);
-
-/// Dealloc the python object \p pyObj and the C++ object represented by it.
-LIBSHIBOKEN_API void SbkDeallocWrapper(PyObject *pyObj);
-LIBSHIBOKEN_API void SbkDeallocQAppWrapper(PyObject *pyObj);
-LIBSHIBOKEN_API void SbkDeallocWrapperWithPrivateDtor(PyObject *self);
-
-struct SbkObjectType;
-
-/// Function signature for the multiple inheritance information initializers that should be provided by classes with multiple inheritance.
-typedef int *(*MultipleInheritanceInitFunction)(const void *);
-
-/**
- * Special cast function is used to correctly cast an object when it's
- * part of a multiple inheritance hierarchy.
- * The implementation of this function is auto generated by the generator and you don't need to care about it.
- */
-typedef void *(*SpecialCastFunction)(void *, SbkObjectType *);
-typedef SbkObjectType *(*TypeDiscoveryFunc)(void *, SbkObjectType *);
-typedef void *(*TypeDiscoveryFuncV2)(void *, SbkObjectType *);
-
-// Used in userdata dealloc function
-typedef void (*DeleteUserDataFunc)(void *);
-
-typedef void (*ObjectDestructor)(void *);
-
-typedef void (*SubTypeInitHook)(SbkObjectType *, PyObject *, PyObject *);
-
-extern LIBSHIBOKEN_API PyTypeObject *SbkObjectType_TypeF(void);
-extern LIBSHIBOKEN_API SbkObjectType *SbkObject_TypeF(void);
-
-
-struct SbkObjectTypePrivate;
-/// PyTypeObject extended with C++ multiple inheritance information.
-struct LIBSHIBOKEN_API SbkObjectType
-{
- PyTypeObject type;
-};
-
-LIBSHIBOKEN_API PyObject *SbkObjectTpNew(PyTypeObject *subtype, PyObject *, PyObject *);
-// the special case of a switchable singleton
-LIBSHIBOKEN_API PyObject *SbkQAppTpNew(PyTypeObject *subtype, PyObject *args, PyObject *kwds);
-
-/**
- * PYSIDE-832: Use object_dealloc instead of nullptr.
- *
- * When moving to heaptypes, we were struck by a special default behavior of
- * PyType_FromSpecWithBases that inserts subtype_dealloc when tp_dealloc is
- * nullptr. But the default before conversion to heaptypes was to assign
- * object_dealloc. This seems to be a bug in the Limited API.
- */
-/// PYSIDE-939: Replaced by Sbk_object_dealloc.
-LIBSHIBOKEN_API PyObject *SbkDummyNew(PyTypeObject *type, PyObject *, PyObject *);
-
-/// PYSIDE-1286: Generate correct __module__ and __qualname__
-LIBSHIBOKEN_API PyObject *SbkType_FromSpec(PyType_Spec *);
-LIBSHIBOKEN_API PyObject *SbkType_FromSpecWithBases(PyType_Spec *, PyObject *);
-
-} // extern "C"
-
-namespace Shiboken
-{
-
-/**
-* Init shiboken library.
-*/
-LIBSHIBOKEN_API void init();
-
-
-/// Delete the class T allocated on \p cptr.
-template<typename T>
-void callCppDestructor(void *cptr)
-{
- delete reinterpret_cast<T *>(cptr);
-}
-
-// setErrorAboutWrongArguments now gets overload info from the signature module.
-LIBSHIBOKEN_API void setErrorAboutWrongArguments(PyObject *args, const char *funcName);
-
-namespace ObjectType {
-
-/**
-* Returns true if the object is an instance of a type created by the Shiboken generator.
-*/
-LIBSHIBOKEN_API bool checkType(PyTypeObject *pyObj);
-
-/**
-* Returns true if this object is an instance of an user defined type derived from an Shiboken type.
-*/
-LIBSHIBOKEN_API bool isUserType(PyTypeObject *pyObj);
-
-/**
-* Returns true if the constructor of \p ctorType can be called for a instance of type \p myType.
-* \note This function set a python error when returning false.
-*/
-LIBSHIBOKEN_API bool canCallConstructor(PyTypeObject *myType, PyTypeObject *ctorType);
-
-/**
- * Tells if the \p type represents an object of a class with multiple inheritance in C++.
- * When this occurs, the C++ pointer held by the Python wrapper will need to be cast when
- * passed as a parameter that expects a type of its ancestry.
- * \returns true if a call to ObjectType::cast() is needed to obtain the correct
- * C++ pointer for Python objects of type \p type.
- */
-LIBSHIBOKEN_API bool hasCast(SbkObjectType *type);
-/**
- * Cast the C++ pointer held by a Python object \p obj of type \p sourceType,
- * to a C++ pointer of a C++ class indicated by type \p targetType.
- * \returns The cast C++ pointer.
- */
-LIBSHIBOKEN_API void *cast(SbkObjectType *sourceType, SbkObject *obj, PyTypeObject *targetType);
-/// Set the C++ cast function for \p type.
-LIBSHIBOKEN_API void setCastFunction(SbkObjectType *type, SpecialCastFunction func);
-
-LIBSHIBOKEN_API void setOriginalName(SbkObjectType *self, const char *name);
-LIBSHIBOKEN_API const char *getOriginalName(SbkObjectType *self);
-
-LIBSHIBOKEN_API void setTypeDiscoveryFunctionV2(SbkObjectType *self, TypeDiscoveryFuncV2 func);
-LIBSHIBOKEN_API void copyMultipleInheritance(SbkObjectType *self, SbkObjectType *other);
-LIBSHIBOKEN_API void setMultipleInheritanceFunction(SbkObjectType *self, MultipleInheritanceInitFunction func);
-LIBSHIBOKEN_API MultipleInheritanceInitFunction getMultipleInheritanceFunction(SbkObjectType *self);
-
-LIBSHIBOKEN_API void setDestructorFunction(SbkObjectType *self, ObjectDestructor func);
-
-LIBSHIBOKEN_API void initPrivateData(SbkObjectType *self);
-
-enum WrapperFlags
-{
- InnerClass = 0x1,
- DeleteInMainThread = 0x2
-};
-
-/**
- * Initializes a Shiboken wrapper type and adds it to the module,
- * or to the enclosing class if the type is an inner class.
- * This function also calls initPrivateData and setDestructorFunction.
- * \param enclosingObject The module or enclosing class to where the new \p type will be added.
- * \param typeName Name by which the type will be known in Python.
- * \param originalName Original C++ name of the type.
- * \param type The new type to be initialized and added to the module.
- * \param cppObjDtor Memory deallocation function for the C++ object held by \p type.
- * Should not be used if the underlying C++ class has a private destructor.
- * \param baseType Base type from whom the new \p type inherits.
- * \param baseTypes Other base types from whom the new \p type inherits.
- * \param isInnerClass Tells if the new \p type is an inner class (the default is that it isn't).
- * If false then the \p enclosingObject is a module, otherwise it is another
- * wrapper type.
- * \returns true if the initialization went fine, false otherwise.
- */
-LIBSHIBOKEN_API SbkObjectType *introduceWrapperType(PyObject *enclosingObject,
- const char *typeName,
- const char *originalName,
- PyType_Spec *typeSpec,
- const char *signatureStrings[],
- ObjectDestructor cppObjDtor,
- SbkObjectType *baseType,
- PyObject *baseTypes,
- unsigned wrapperFlags = 0);
-
-/**
- * Set the subtype init hook for a type.
- *
- * This hook will be invoked every time the user creates a sub-type inherited from a Shiboken based type.
- * The hook gets 3 params, they are: The new type being created, args and kwds. The last two are the very
- * same got from tp_new.
- */
-LIBSHIBOKEN_API void setSubTypeInitHook(SbkObjectType *self, SubTypeInitHook func);
-
-/**
- * Get the user data previously set by Shiboken::Object::setTypeUserData
- */
-LIBSHIBOKEN_API void *getTypeUserData(SbkObjectType *self);
-LIBSHIBOKEN_API void setTypeUserData(SbkObjectType *self, void *userData, DeleteUserDataFunc d_func);
-
-/**
- * Return an instance of SbkObjectType for a C++ type name as determined by
- * typeinfo().name().
- * \param typeName Type name
- * \since 5.12
- */
-LIBSHIBOKEN_API SbkObjectType *typeForTypeName(const char *typeName);
-
-/**
- * Returns whether SbkObjectType has a special cast function (multiple inheritance)
- * \param sbkType Sbk type
- * \since 5.12
- */
-LIBSHIBOKEN_API bool hasSpecialCastFunction(SbkObjectType *sbkType);
-}
-
-namespace Object {
-
-/**
- * Returns a string with information about the internal state of the instance object, useful for debug purposes.
- */
-LIBSHIBOKEN_API std::string info(SbkObject *self);
-
-/**
-* Returns true if the object is an instance of a type created by the Shiboken generator.
-*/
-LIBSHIBOKEN_API bool checkType(PyObject *pyObj);
-
-/**
- * Returns true if this object type is an instance of an user defined type derived from an Shiboken type.
- * \see Shiboken::ObjectType::isUserType
- */
-LIBSHIBOKEN_API bool isUserType(PyObject *pyObj);
-
-/**
- * Generic function used to make ObjectType hashable, the C++ pointer is used as hash value.
- */
-LIBSHIBOKEN_API Py_hash_t hash(PyObject *pyObj);
-
-/**
- * Find a child of given wrapper having same address having the specified type.
- */
-LIBSHIBOKEN_API SbkObject *findColocatedChild(SbkObject *wrapper,
- const SbkObjectType *instanceType);
-
-/**
- * Bind a C++ object to Python.
- * \param instanceType equivalent Python type for the C++ object.
- * \param hasOwnership if true, Python will try to delete the underlying C++ object when there's no more refs.
- * \param isExactType if false, Shiboken will use some heuristics to detect the correct Python type of this C++
- * object, in any case you must provide \p instanceType, it'll be used as search starting point
- * and as fallback.
- * \param typeName If non-null, this will be used as helper to find the correct Python type for this object.
- */
-LIBSHIBOKEN_API PyObject *newObject(SbkObjectType *instanceType,
- void *cptr,
- bool hasOwnership = true,
- bool isExactType = false,
- const char *typeName = nullptr);
-
-/**
- * Changes the valid flag of a PyObject, invalid objects will raise an exception when someone tries to access it.
- */
-LIBSHIBOKEN_API void setValidCpp(SbkObject *pyObj, bool value);
-/**
- * Tells shiboken the Python object \p pyObj has a C++ wrapper used to intercept virtual method calls.
- */
-LIBSHIBOKEN_API void setHasCppWrapper(SbkObject *pyObj, bool value);
-/**
- * Return true if the Python object \p pyObj has a C++ wrapper used to intercept virtual method calls.
- */
-LIBSHIBOKEN_API bool hasCppWrapper(SbkObject *pyObj);
-
-/**
- * Return true if the Python object was created by Python, false otherwise.
- * \note This function was added to libshiboken only to be used by shiboken.wasCreatedByPython()
- */
-LIBSHIBOKEN_API bool wasCreatedByPython(SbkObject *pyObj);
-
-/**
- * Call the C++ object destructor and invalidates the Python object.
- * \note This function was added to libshiboken only to be used by shiboken.delete()
- */
-LIBSHIBOKEN_API void callCppDestructors(SbkObject *pyObj);
-
-/**
- * Return true if the Python is responsible for deleting the underlying C++ object.
- */
-LIBSHIBOKEN_API bool hasOwnership(SbkObject *pyObj);
-
-/**
- * Sets python as responsible to delete the underlying C++ object.
- * \note You this overload only when the PyObject can be a sequence and you want to
- * call this function for every item in the sequence.
- * \see getOwnership(SbkObject *)
- */
-LIBSHIBOKEN_API void getOwnership(PyObject *pyObj);
-
-/**
- * Sets python as responsible to delete the underlying C++ object.
- */
-LIBSHIBOKEN_API void getOwnership(SbkObject *pyObj);
-
-/**
- * Release the ownership, so Python will not delete the underlying C++ object.
- * \note You this overload only when the PyObject can be a sequence and you want to
- * call this function for every item in the sequence.
- * \see releaseOwnership(SbkObject *)
- */
-LIBSHIBOKEN_API void releaseOwnership(PyObject *pyObj);
-/**
- * Release the ownership, so Python will not delete the underlying C++ object.
- */
-LIBSHIBOKEN_API void releaseOwnership(SbkObject *pyObj);
-
-/**
- * Get the C++ pointer of type \p desiredType from a Python object.
- */
-LIBSHIBOKEN_API void *cppPointer(SbkObject *pyObj, PyTypeObject *desiredType);
-
-/**
- * Return a list with all C++ pointers held from a Python object.
- * \note This function was added to libshiboken only to be used by shiboken.getCppPointer()
- */
-LIBSHIBOKEN_API std::vector<void *>cppPointers(SbkObject *pyObj);
-
-/**
- * Set the C++ pointer of type \p desiredType of a Python object.
- */
-LIBSHIBOKEN_API bool setCppPointer(SbkObject *sbkObj, PyTypeObject *desiredType, void *cptr);
-
-/**
- * Returns false and sets a Python RuntimeError if the Python wrapper is not marked as valid.
- */
-LIBSHIBOKEN_API bool isValid(PyObject *pyObj);
-
-/**
- * Returns false if the Python wrapper is not marked as valid.
- * \param pyObj the object.
- * \param throwPyError sets a Python RuntimeError when the object isn't valid.
- */
-LIBSHIBOKEN_API bool isValid(SbkObject *pyObj, bool throwPyError = true);
-
-/**
- * Returns false if the Python wrapper is not marked as valid.
- * \param pyObj the object.
- * \param throwPyError sets a Python RuntimeError when the object isn't valid.
- */
-LIBSHIBOKEN_API bool isValid(PyObject *pyObj, bool throwPyError);
-
-/**
-* Set the parent of \p child to \p parent.
-* When an object dies, all their children, grandchildren, etc, are tagged as invalid.
-* \param parent the parent object, if null, the child will have no parents.
-* \param child the child.
-*/
-LIBSHIBOKEN_API void setParent(PyObject *parent, PyObject *child);
-
-/**
-* Remove this child from their parent, if any.
-* \param child the child.
-*/
-LIBSHIBOKEN_API void removeParent(SbkObject *child, bool giveOwnershipBack = true, bool keepReferenc = false);
-
-/**
- * Mark the object as invalid
- */
-LIBSHIBOKEN_API void invalidate(SbkObject *self);
-
-/**
- * Help function can be used to invalidate a sequence of object
- **/
-LIBSHIBOKEN_API void invalidate(PyObject *pyobj);
-
-/**
- * Make the object valid again
- */
-LIBSHIBOKEN_API void makeValid(SbkObject *self);
-
-/**
- * Destroy any data in Shiboken structure and c++ pointer if the pyboject has the ownership
- */
-LIBSHIBOKEN_API void destroy(SbkObject *self, void *cppData);
-
-/**
- * Set user data on type of \p wrapper.
- * \param wrapper instance object, the user data will be set on his type
- * \param userData the user data
- * \param d_func a function used to delete the user data
- */
-LIBSHIBOKEN_API void setTypeUserData(SbkObject *wrapper, void *userData, DeleteUserDataFunc d_func);
-/**
- * Get the user data previously set by Shiboken::Object::setTypeUserData
- */
-LIBSHIBOKEN_API void *getTypeUserData(SbkObject *wrapper);
-
-/**
- * Increments the reference count of the referred Python object.
- * A previous Python object in the same position identified by the 'key' parameter
- * will have its reference counter decremented automatically when replaced.
- * All the kept references should be decremented when the Python wrapper indicated by
- * 'self' dies.
- * No checking is done for any of the passed arguments, since it is meant to be used
- * by generated code it is supposed that the generator is correct.
- * \param self the wrapper instance that keeps references to other objects.
- * \param key a key that identifies the C++ method signature and argument where the referred Object came from.
- * \param referredObject the object whose reference is used by the self object.
- */
-LIBSHIBOKEN_API void keepReference(SbkObject *self, const char *key, PyObject *referredObject, bool append = false);
-
-/**
- * Removes any reference previously added by keepReference function
- * \param self the wrapper instance that keeps references to other objects.
- * \param key a key that identifies the C++ method signature and argument from where the referred Object came.
- * \param referredObject the object whose reference is used by the self object.
- */
-LIBSHIBOKEN_API void removeReference(SbkObject *self, const char *key, PyObject *referredObject);
-
-} // namespace Object
-
-} // namespace Shiboken
-
-#endif // BASEWRAPPER_H
diff --git a/sources/shiboken2/libshiboken/basewrapper_p.h b/sources/shiboken2/libshiboken/basewrapper_p.h
deleted file mode 100644
index 56a647b21..000000000
--- a/sources/shiboken2/libshiboken/basewrapper_p.h
+++ /dev/null
@@ -1,289 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef BASEWRAPPER_P_H
-#define BASEWRAPPER_P_H
-
-#include "sbkpython.h"
-#include "basewrapper.h"
-
-#include <unordered_map>
-#include <set>
-#include <string>
-#include <vector>
-
-struct SbkObject;
-struct SbkObjectType;
-struct SbkConverter;
-
-namespace Shiboken
-{
-/**
- * This mapping associates a method and argument of an wrapper object with the wrapper of
- * said argument when it needs the binding to help manage its reference count.
- */
-using RefCountMap = std::unordered_multimap<std::string, PyObject *> ;
-
-/// Linked list of SbkBaseWrapper pointers
-using ChildrenList = std::set<SbkObject *>;
-
-/// Structure used to store information about object parent and children.
-struct ParentInfo
-{
- /// Default ctor.
- ParentInfo() : parent(nullptr), hasWrapperRef(false) {}
- /// Pointer to parent object.
- SbkObject *parent;
- /// List of object children.
- ChildrenList children;
- /// has internal ref
- bool hasWrapperRef;
-};
-
-} // namespace Shiboken
-
-extern "C"
-{
-
-/**
- * \internal
- * Private data for SbkBaseWrapper
- */
-struct SbkObjectPrivate
-{
- /// Pointer to the C++ class.
- void ** cptr;
- /// True when Python is responsible for freeing the used memory.
- unsigned int hasOwnership : 1;
- /// This is true when the C++ class of the wrapped object has a virtual destructor AND was created by Python.
- unsigned int containsCppWrapper : 1;
- /// Marked as false when the object is lost to C++ and the binding can not know if it was deleted or not.
- unsigned int validCppObject : 1;
- /// Marked as true when the object constructor was called
- unsigned int cppObjectCreated : 1;
- /// Information about the object parents and children, may be null.
- Shiboken::ParentInfo *parentInfo;
- /// Manage reference count of objects that are referred to but not owned from.
- Shiboken::RefCountMap *referredObjects;
-
- ~SbkObjectPrivate()
- {
- delete parentInfo;
- parentInfo = nullptr;
- delete referredObjects;
- referredObjects = nullptr;
- }
-};
-
-// TODO-CONVERTERS: to be deprecated/removed
-/// The type behaviour was not defined yet
-#define BEHAVIOUR_UNDEFINED 0
-/// The type is a value type
-#define BEHAVIOUR_VALUETYPE 1
-/// The type is an object type
-#define BEHAVIOUR_OBJECTTYPE 2
-
-struct SbkObjectTypePrivate
-{
- SbkConverter *converter;
- int *mi_offsets;
- MultipleInheritanceInitFunction mi_init;
-
- /// Special cast function, null if this class doesn't have multiple inheritance.
- SpecialCastFunction mi_specialcast;
- TypeDiscoveryFuncV2 type_discovery;
- /// Pointer to a function responsible for deletion of the C++ instance calling the proper destructor.
- ObjectDestructor cpp_dtor;
- /// True if this type holds two or more C++ instances, e.g.: a Python class which inherits from two C++ classes.
- int is_multicpp : 1;
- /// True if this type was defined by the user.
- int is_user_type : 1;
- /// Tells is the type is a value type or an object-type, see BEHAVIOUR_ *constants.
- // TODO-CONVERTERS: to be deprecated/removed
- int type_behaviour : 2;
- int delete_in_main_thread : 1;
- /// C++ name
- char *original_name;
- /// Type user data
- void *user_data;
- DeleteUserDataFunc d_func;
- void (*subtype_init)(SbkObjectType *, PyObject *, PyObject *);
-};
-
-
-} // extern "C"
-
-namespace Shiboken
-{
-
-/**
- * \internal
- * Data required to invoke a C++ destructor
- */
-struct DestructorEntry
-{
- ObjectDestructor destructor;
- void *cppInstance;
-};
-
-/**
- * Utility function used to transform a PyObject that implements sequence protocol into a std::list.
- **/
-std::vector<SbkObject *> splitPyObject(PyObject *pyObj);
-
-/**
-* Visitor class used by walkOnClassHierarchy function.
-*/
-class HierarchyVisitor
-{
-public:
- HierarchyVisitor(const HierarchyVisitor &) = delete;
- HierarchyVisitor(HierarchyVisitor &&) = delete;
- HierarchyVisitor &operator=(const HierarchyVisitor &) = delete;
- HierarchyVisitor &operator=(HierarchyVisitor &&) = delete;
-
- HierarchyVisitor();
- virtual ~HierarchyVisitor();
-
- virtual bool visit(SbkObjectType *node) = 0; // return true to terminate
-};
-
-class BaseCountVisitor : public HierarchyVisitor
-{
-public:
- bool visit(SbkObjectType *) override;
-
- int count() const { return m_count; }
-
-private:
- int m_count = 0;
-};
-
-class BaseAccumulatorVisitor : public HierarchyVisitor
-{
-public:
- using Result = std::vector<SbkObjectType *>;
-
- bool visit(SbkObjectType *node) override;
-
- Result bases() const { return m_bases; }
-
-private:
- Result m_bases;
-};
-
-class GetIndexVisitor : public HierarchyVisitor
-{
-public:
- explicit GetIndexVisitor(PyTypeObject *desiredType) : m_desiredType(desiredType) {}
-
- bool visit(SbkObjectType *node) override;
-
- int index() const { return m_index; }
-
-private:
- int m_index = -1;
- PyTypeObject *m_desiredType;
-};
-
-/// Collect destructors and C++ instances of each C++ object held by a Python
-/// object
-class DtorAccumulatorVisitor : public HierarchyVisitor
-{
-public:
- explicit DtorAccumulatorVisitor(SbkObject *pyObj) : m_pyObject(pyObj) {}
-
- bool visit(SbkObjectType *node) override;
-
- using DestructorEntries = std::vector<DestructorEntry>;
-
- const DestructorEntries &entries() const { return m_entries; }
-
-private:
- DestructorEntries m_entries;
- SbkObject *m_pyObject;
-};
-
-/// \internal Internal function used to walk on classes inheritance trees.
-/**
-* Walk on class hierarchy using a DFS algorithm.
-* For each pure Shiboken type found, HiearchyVisitor::visit is called and the algorithm consider
-* all children of this type as visited.
-*/
-bool walkThroughClassHierarchy(PyTypeObject *currentType, HierarchyVisitor *visitor);
-
-inline int getTypeIndexOnHierarchy(PyTypeObject *baseType, PyTypeObject *desiredType)
-{
- GetIndexVisitor visitor(desiredType);
- walkThroughClassHierarchy(baseType, &visitor);
- return visitor.index();
-}
-
-inline int getNumberOfCppBaseClasses(PyTypeObject *baseType)
-{
- BaseCountVisitor visitor;
- walkThroughClassHierarchy(baseType, &visitor);
- return visitor.count();
-}
-
-inline std::vector<SbkObjectType *> getCppBaseClasses(PyTypeObject *baseType)
-{
- BaseAccumulatorVisitor visitor;
- walkThroughClassHierarchy(baseType, &visitor);
- return visitor.bases();
-}
-
-namespace Object
-{
-/**
-* Decrements the reference counters of every object referred by self.
-* \param self the wrapper instance that keeps references to other objects.
-*/
-void clearReferences(SbkObject *self);
-
-/**
- * Destroy internal data
- **/
-void deallocData(SbkObject *self, bool doCleanup);
-
-} // namespace Object
-
-} // namespace Shiboken
-
-#endif
diff --git a/sources/shiboken2/libshiboken/bindingmanager.cpp b/sources/shiboken2/libshiboken/bindingmanager.cpp
deleted file mode 100644
index 1ab8dd089..000000000
--- a/sources/shiboken2/libshiboken/bindingmanager.cpp
+++ /dev/null
@@ -1,348 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "autodecref.h"
-#include "basewrapper.h"
-#include "basewrapper_p.h"
-#include "bindingmanager.h"
-#include "sbkdbg.h"
-#include "gilstate.h"
-#include "sbkstring.h"
-#include "debugfreehook.h"
-
-#include <cstddef>
-#include <fstream>
-#include <unordered_map>
-
-namespace Shiboken
-{
-
-using WrapperMap = std::unordered_map<const void *, SbkObject *>;
-
-class Graph
-{
-public:
- using NodeList = std::vector<SbkObjectType *>;
- using Edges = std::unordered_map<SbkObjectType *, NodeList>;
-
- Edges m_edges;
-
- Graph() = default;
-
- void addEdge(SbkObjectType *from, SbkObjectType *to)
- {
- m_edges[from].push_back(to);
- }
-
-#ifndef NDEBUG
- void dumpDotGraph()
- {
- std::ofstream file("/tmp/shiboken_graph.dot");
-
- file << "digraph D {\n";
-
- for (auto i = m_edges.begin(), end = m_edges.end(); i != end; ++i) {
- auto node1 = reinterpret_cast<const PyTypeObject *>(i->first);
- const NodeList &nodeList = i->second;
- for (const SbkObjectType *o : nodeList) {
- auto node2 = reinterpret_cast<const PyTypeObject *>(o);
- file << '"' << node2->tp_name << "\" -> \""
- << node1->tp_name << "\"\n";
- }
- }
- file << "}\n";
- }
-#endif
-
- SbkObjectType *identifyType(void **cptr, SbkObjectType *type, SbkObjectType *baseType) const
- {
- auto edgesIt = m_edges.find(type);
- if (edgesIt != m_edges.end()) {
- const NodeList &adjNodes = m_edges.find(type)->second;
- for (SbkObjectType *node : adjNodes) {
- SbkObjectType *newType = identifyType(cptr, node, baseType);
- if (newType)
- return newType;
- }
- }
- void *typeFound = nullptr;
- if (PepType_SOTP(type) && PepType_SOTP(type)->type_discovery) {
- typeFound = PepType_SOTP(type)->type_discovery(*cptr, baseType);
- }
- if (typeFound) {
- // This "typeFound != type" is needed for backwards compatibility with old modules using a newer version of
- // libshiboken because old versions of type_discovery function used to return a SbkObjectType *instead of
- // a possible variation of the C++ instance pointer (*cptr).
- if (typeFound != type)
- *cptr = typeFound;
- return type;
- }
- return nullptr;
- }
-};
-
-
-#ifndef NDEBUG
-static void showWrapperMap(const WrapperMap &wrapperMap)
-{
- if (Py_VerboseFlag > 0) {
- fprintf(stderr, "-------------------------------\n");
- fprintf(stderr, "WrapperMap: %p (size: %d)\n", &wrapperMap, (int) wrapperMap.size());
- for (auto it = wrapperMap.begin(), end = wrapperMap.end(); it != end; ++it) {
- const SbkObject *sbkObj = it->second;
- fprintf(stderr, "key: %p, value: %p (%s, refcnt: %d)\n", it->first,
- static_cast<const void *>(sbkObj),
- (Py_TYPE(sbkObj))->tp_name,
- int(reinterpret_cast<const PyObject *>(sbkObj)->ob_refcnt));
- }
- fprintf(stderr, "-------------------------------\n");
- }
-}
-#endif
-
-struct BindingManager::BindingManagerPrivate {
- using DestructorEntries = std::vector<DestructorEntry>;
-
- WrapperMap wrapperMapper;
- Graph classHierarchy;
- DestructorEntries deleteInMainThread;
- bool destroying;
-
- BindingManagerPrivate() : destroying(false) {}
- bool releaseWrapper(void *cptr, SbkObject *wrapper);
- void assignWrapper(SbkObject *wrapper, const void *cptr);
-
-};
-
-bool BindingManager::BindingManagerPrivate::releaseWrapper(void *cptr, SbkObject *wrapper)
-{
- // The wrapper argument is checked to ensure that the correct wrapper is released.
- // Returns true if the correct wrapper is found and released.
- // If wrapper argument is NULL, no such check is performed.
- auto iter = wrapperMapper.find(cptr);
- if (iter != wrapperMapper.end() && (wrapper == nullptr || iter->second == wrapper)) {
- wrapperMapper.erase(iter);
- return true;
- }
- return false;
-}
-
-void BindingManager::BindingManagerPrivate::assignWrapper(SbkObject *wrapper, const void *cptr)
-{
- assert(cptr);
- auto iter = wrapperMapper.find(cptr);
- if (iter == wrapperMapper.end())
- wrapperMapper.insert(std::make_pair(cptr, wrapper));
-}
-
-BindingManager::BindingManager()
-{
- m_d = new BindingManager::BindingManagerPrivate;
-
-#ifdef SHIBOKEN_INSTALL_FREE_DEBUG_HOOK
- debugInstallFreeHook();
-#endif
-}
-
-BindingManager::~BindingManager()
-{
-#ifdef SHIBOKEN_INSTALL_FREE_DEBUG_HOOK
- debugRemoveFreeHook();
-#endif
-#ifndef NDEBUG
- showWrapperMap(m_d->wrapperMapper);
-#endif
- /* Cleanup hanging references. We just invalidate them as when
- * the BindingManager is being destroyed the interpreter is alredy
- * shutting down. */
- if (Py_IsInitialized()) { // ensure the interpreter is still valid
- while (!m_d->wrapperMapper.empty()) {
- Object::destroy(m_d->wrapperMapper.begin()->second, const_cast<void *>(m_d->wrapperMapper.begin()->first));
- }
- assert(m_d->wrapperMapper.empty());
- }
- delete m_d;
-}
-
-BindingManager &BindingManager::instance() {
- static BindingManager singleton;
- return singleton;
-}
-
-bool BindingManager::hasWrapper(const void *cptr)
-{
- return m_d->wrapperMapper.find(cptr) != m_d->wrapperMapper.end();
-}
-
-void BindingManager::registerWrapper(SbkObject *pyObj, void *cptr)
-{
- auto instanceType = reinterpret_cast<SbkObjectType *>(Py_TYPE(pyObj));
- SbkObjectTypePrivate *d = PepType_SOTP(instanceType);
-
- if (!d)
- return;
-
- if (d->mi_init && !d->mi_offsets)
- d->mi_offsets = d->mi_init(cptr);
- m_d->assignWrapper(pyObj, cptr);
- if (d->mi_offsets) {
- int *offset = d->mi_offsets;
- while (*offset != -1) {
- if (*offset > 0)
- m_d->assignWrapper(pyObj, reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(cptr) + *offset));
- offset++;
- }
- }
-}
-
-void BindingManager::releaseWrapper(SbkObject *sbkObj)
-{
- auto sbkType = reinterpret_cast<SbkObjectType *>(Py_TYPE(sbkObj));
- SbkObjectTypePrivate *d = PepType_SOTP(sbkType);
- int numBases = ((d && d->is_multicpp) ? getNumberOfCppBaseClasses(Py_TYPE(sbkObj)) : 1);
-
- void ** cptrs = reinterpret_cast<SbkObject *>(sbkObj)->d->cptr;
- for (int i = 0; i < numBases; ++i) {
- auto *cptr = reinterpret_cast<unsigned char *>(cptrs[i]);
- m_d->releaseWrapper(cptr, sbkObj);
- if (d && d->mi_offsets) {
- int *offset = d->mi_offsets;
- while (*offset != -1) {
- if (*offset > 0)
- m_d->releaseWrapper(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(cptr) + *offset), sbkObj);
- offset++;
- }
- }
- }
- sbkObj->d->validCppObject = false;
-}
-
-void BindingManager::runDeletionInMainThread()
-{
- for (const DestructorEntry &e : m_d->deleteInMainThread)
- e.destructor(e.cppInstance);
- m_d->deleteInMainThread.clear();
-}
-
-void BindingManager::addToDeletionInMainThread(const DestructorEntry &e)
-{
- m_d->deleteInMainThread.push_back(e);
-}
-
-SbkObject *BindingManager::retrieveWrapper(const void *cptr)
-{
- auto iter = m_d->wrapperMapper.find(cptr);
- if (iter == m_d->wrapperMapper.end())
- return nullptr;
- return iter->second;
-}
-
-PyObject *BindingManager::getOverride(const void *cptr, const char *methodName)
-{
- SbkObject *wrapper = retrieveWrapper(cptr);
- // The refcount can be 0 if the object is dieing and someone called
- // a virtual method from the destructor
- if (!wrapper || reinterpret_cast<const PyObject *>(wrapper)->ob_refcnt == 0)
- return nullptr;
-
- if (wrapper->ob_dict) {
- PyObject *method = PyDict_GetItemString(wrapper->ob_dict, methodName);
- if (method) {
- Py_INCREF(reinterpret_cast<PyObject *>(method));
- return method;
- }
- }
-
- Shiboken::AutoDecRef pyMethodName(Shiboken::String::fromCString(methodName));
- PyObject *method = PyObject_GetAttr(reinterpret_cast<PyObject *>(wrapper), pyMethodName);
-
- if (method && PyMethod_Check(method)
- && PyMethod_GET_SELF(method) == reinterpret_cast<PyObject *>(wrapper)) {
- PyObject *defaultMethod;
- PyObject *mro = Py_TYPE(wrapper)->tp_mro;
-
- // The first class in the mro (index 0) is the class being checked and it should not be tested.
- // The last class in the mro (size - 1) is the base Python object class which should not be tested also.
- for (int i = 1; i < PyTuple_GET_SIZE(mro) - 1; i++) {
- auto *parent = reinterpret_cast<PyTypeObject *>(PyTuple_GET_ITEM(mro, i));
- if (parent->tp_dict) {
- defaultMethod = PyDict_GetItem(parent->tp_dict, pyMethodName);
- if (defaultMethod && PyMethod_GET_FUNCTION(method) != defaultMethod)
- return method;
- }
- }
- }
-
- Py_XDECREF(method);
- return nullptr;
-}
-
-void BindingManager::addClassInheritance(SbkObjectType *parent, SbkObjectType *child)
-{
- m_d->classHierarchy.addEdge(parent, child);
-}
-
-SbkObjectType *BindingManager::resolveType(void **cptr, SbkObjectType *type)
-{
- SbkObjectType *identifiedType = m_d->classHierarchy.identifyType(cptr, type, type);
- return identifiedType ? identifiedType : type;
-}
-
-std::set<PyObject *> BindingManager::getAllPyObjects()
-{
- std::set<PyObject *> pyObjects;
- const WrapperMap &wrappersMap = m_d->wrapperMapper;
- auto it = wrappersMap.begin();
- for (; it != wrappersMap.end(); ++it)
- pyObjects.insert(reinterpret_cast<PyObject *>(it->second));
-
- return pyObjects;
-}
-
-void BindingManager::visitAllPyObjects(ObjectVisitor visitor, void *data)
-{
- WrapperMap copy = m_d->wrapperMapper;
- for (auto it = copy.begin(); it != copy.end(); ++it) {
- if (hasWrapper(it->first))
- visitor(it->second, data);
- }
-}
-
-} // namespace Shiboken
-
diff --git a/sources/shiboken2/libshiboken/bindingmanager.h b/sources/shiboken2/libshiboken/bindingmanager.h
deleted file mode 100644
index ba5535347..000000000
--- a/sources/shiboken2/libshiboken/bindingmanager.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef BINDINGMANAGER_H
-#define BINDINGMANAGER_H
-
-#include "sbkpython.h"
-#include <set>
-#include "shibokenmacros.h"
-
-struct SbkObject;
-struct SbkObjectType;
-
-namespace Shiboken
-{
-
-struct DestructorEntry;
-
-typedef void (*ObjectVisitor)(SbkObject *, void *);
-
-class LIBSHIBOKEN_API BindingManager
-{
-public:
- BindingManager(const BindingManager &) = delete;
- BindingManager(BindingManager &&) = delete;
- BindingManager &operator=(const BindingManager &) = delete;
- BindingManager &operator=(BindingManager &&) = delete;
-
- static BindingManager &instance();
-
- bool hasWrapper(const void *cptr);
-
- void registerWrapper(SbkObject *pyObj, void *cptr);
- void releaseWrapper(SbkObject *wrapper);
-
- void runDeletionInMainThread();
- void addToDeletionInMainThread(const DestructorEntry &);
-
- SbkObject *retrieveWrapper(const void *cptr);
- PyObject *getOverride(const void *cptr, const char *methodName);
-
- void addClassInheritance(SbkObjectType *parent, SbkObjectType *child);
- /**
- * Try to find the correct type of *cptr knowing that it's at least of type \p type.
- * In case of multiple inheritance this function may change the contents of cptr.
- * \param cptr a pointer to a pointer to the instance of type \p type
- * \param type type of *cptr
- * \warning This function is slow, use it only as last resort.
- */
- SbkObjectType *resolveType(void **cptr, SbkObjectType *type);
-
- std::set<PyObject *> getAllPyObjects();
-
- /**
- * Calls the function \p visitor for each object registered on binding manager.
- * \note As various C++ pointers can point to the same PyObject due to multiple inheritance
- * a PyObject can be called more than one time for each PyObject.
- * \param visitor function called for each object.
- * \param data user data passed as second argument to the visitor function.
- */
- void visitAllPyObjects(ObjectVisitor visitor, void *data);
-
-private:
- ~BindingManager();
- BindingManager();
-
- struct BindingManagerPrivate;
- BindingManagerPrivate *m_d;
-};
-
-} // namespace Shiboken
-
-#endif // BINDINGMANAGER_H
-
diff --git a/sources/shiboken2/libshiboken/bufferprocs_py37.cpp b/sources/shiboken2/libshiboken/bufferprocs_py37.cpp
deleted file mode 100644
index da6bb00a3..000000000
--- a/sources/shiboken2/libshiboken/bufferprocs_py37.cpp
+++ /dev/null
@@ -1,396 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*****************************************************************************
- *
- * Copied from abstract.c
- *
- * Py_buffer has been replaced by Pep_buffer
- *
- */
-
-#ifdef Py_LIMITED_API
-
-#include "sbkpython.h"
-/* Buffer C-API for Python 3.0 */
-
-int
-PyObject_GetBuffer(PyObject *obj, Pep_buffer *view, int flags)
-{
- PyBufferProcs *pb = PepType_AS_BUFFER(Py_TYPE(obj));
-
- if (pb == NULL || pb->bf_getbuffer == NULL) {
- PyErr_Format(PyExc_TypeError,
- "a bytes-like object is required, not '%.100s'",
- Py_TYPE(obj)->tp_name);
- return -1;
- }
- return (*pb->bf_getbuffer)(obj, view, flags);
-}
-
-static int
-_IsFortranContiguous(const Pep_buffer *view)
-{
- Py_ssize_t sd, dim;
- int i;
-
- /* 1) len = product(shape) * itemsize
- 2) itemsize > 0
- 3) len = 0 <==> exists i: shape[i] = 0 */
- if (view->len == 0) return 1;
- if (view->strides == NULL) { /* C-contiguous by definition */
- /* Trivially F-contiguous */
- if (view->ndim <= 1) return 1;
-
- /* ndim > 1 implies shape != NULL */
- assert(view->shape != NULL);
-
- /* Effectively 1-d */
- sd = 0;
- for (i=0; i<view->ndim; i++) {
- if (view->shape[i] > 1) sd += 1;
- }
- return sd <= 1;
- }
-
- /* strides != NULL implies both of these */
- assert(view->ndim > 0);
- assert(view->shape != NULL);
-
- sd = view->itemsize;
- for (i=0; i<view->ndim; i++) {
- dim = view->shape[i];
- if (dim > 1 && view->strides[i] != sd) {
- return 0;
- }
- sd *= dim;
- }
- return 1;
-}
-
-static int
-_IsCContiguous(const Pep_buffer *view)
-{
- Py_ssize_t sd, dim;
- int i;
-
- /* 1) len = product(shape) * itemsize
- 2) itemsize > 0
- 3) len = 0 <==> exists i: shape[i] = 0 */
- if (view->len == 0) return 1;
- if (view->strides == NULL) return 1; /* C-contiguous by definition */
-
- /* strides != NULL implies both of these */
- assert(view->ndim > 0);
- assert(view->shape != NULL);
-
- sd = view->itemsize;
- for (i=view->ndim-1; i>=0; i--) {
- dim = view->shape[i];
- if (dim > 1 && view->strides[i] != sd) {
- return 0;
- }
- sd *= dim;
- }
- return 1;
-}
-
-int
-PyBuffer_IsContiguous(const Pep_buffer *view, char order)
-{
-
- if (view->suboffsets != NULL) return 0;
-
- if (order == 'C')
- return _IsCContiguous(view);
- else if (order == 'F')
- return _IsFortranContiguous(view);
- else if (order == 'A')
- return (_IsCContiguous(view) || _IsFortranContiguous(view));
- return 0;
-}
-
-
-void *
-PyBuffer_GetPointer(Pep_buffer *view, Py_ssize_t *indices)
-{
- int i;
- auto pointer = reinterpret_cast<char *>(view->buf);
- for (i = 0; i < view->ndim; i++) {
- pointer += view->strides[i]*indices[i];
- if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
- pointer = *reinterpret_cast<char **>(pointer) + view->suboffsets[i];
- }
- }
- return pointer;
-}
-
-
-void
-_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
-{
- int k;
-
- for (k=0; k<nd; k++) {
- if (index[k] < shape[k]-1) {
- index[k]++;
- break;
- }
- else {
- index[k] = 0;
- }
- }
-}
-
-void
-_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
-{
- int k;
-
- for (k=nd-1; k>=0; k--) {
- if (index[k] < shape[k]-1) {
- index[k]++;
- break;
- }
- else {
- index[k] = 0;
- }
- }
-}
-
-int
-PyBuffer_FromContiguous(Pep_buffer *view, void *buf, Py_ssize_t len, char fort)
-{
- int k;
- void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
- Py_ssize_t *indices, elements;
- char *src, *ptr;
-
- if (len > view->len) {
- len = view->len;
- }
-
- if (PyBuffer_IsContiguous(view, fort)) {
- /* simplest copy is all that is needed */
- memcpy(view->buf, buf, len);
- return 0;
- }
-
- /* Otherwise a more elaborate scheme is needed */
-
- /* view->ndim <= 64 */
- indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
- if (indices == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- for (k=0; k<view->ndim; k++) {
- indices[k] = 0;
- }
-
- if (fort == 'F') {
- addone = _Py_add_one_to_index_F;
- }
- else {
- addone = _Py_add_one_to_index_C;
- }
- src = (char *)buf; // patched by CT
- /* XXX : This is not going to be the fastest code in the world
- several optimizations are possible.
- */
- elements = len / view->itemsize;
- while (elements--) {
- ptr = (char *)PyBuffer_GetPointer(view, indices); // patched by CT
- memcpy(ptr, src, view->itemsize);
- src += view->itemsize;
- addone(view->ndim, indices, view->shape);
- }
-
- PyMem_Free(indices);
- return 0;
-}
-
-int PyObject_CopyData(PyObject *dest, PyObject *src)
-{
- Pep_buffer view_dest, view_src;
- int k;
- Py_ssize_t *indices, elements;
- char *dptr, *sptr;
-
- if (!PyObject_CheckBuffer(dest) ||
- !PyObject_CheckBuffer(src)) {
- PyErr_SetString(PyExc_TypeError,
- "both destination and source must be "\
- "bytes-like objects");
- return -1;
- }
-
- if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
- if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
- PyBuffer_Release(&view_dest);
- return -1;
- }
-
- if (view_dest.len < view_src.len) {
- PyErr_SetString(PyExc_BufferError,
- "destination is too small to receive data from source");
- PyBuffer_Release(&view_dest);
- PyBuffer_Release(&view_src);
- return -1;
- }
-
- if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
- PyBuffer_IsContiguous(&view_src, 'C')) ||
- (PyBuffer_IsContiguous(&view_dest, 'F') &&
- PyBuffer_IsContiguous(&view_src, 'F'))) {
- /* simplest copy is all that is needed */
- memcpy(view_dest.buf, view_src.buf, view_src.len);
- PyBuffer_Release(&view_dest);
- PyBuffer_Release(&view_src);
- return 0;
- }
-
- /* Otherwise a more elaborate copy scheme is needed */
-
- /* XXX(nnorwitz): need to check for overflow! */
- indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
- if (indices == NULL) {
- PyErr_NoMemory();
- PyBuffer_Release(&view_dest);
- PyBuffer_Release(&view_src);
- return -1;
- }
- for (k=0; k<view_src.ndim;k++) {
- indices[k] = 0;
- }
- elements = 1;
- for (k=0; k<view_src.ndim; k++) {
- /* XXX(nnorwitz): can this overflow? */
- elements *= view_src.shape[k];
- }
- while (elements--) {
- _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
- dptr = (char *)PyBuffer_GetPointer(&view_dest, indices); // patched by CT
- sptr = (char *)PyBuffer_GetPointer(&view_src, indices); // patched by CT
- memcpy(dptr, sptr, view_src.itemsize);
- }
- PyMem_Free(indices);
- PyBuffer_Release(&view_dest);
- PyBuffer_Release(&view_src);
- return 0;
-}
-
-void
-PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
- Py_ssize_t *strides, int itemsize,
- char fort)
-{
- int k;
- Py_ssize_t sd;
-
- sd = itemsize;
- if (fort == 'F') {
- for (k=0; k<nd; k++) {
- strides[k] = sd;
- sd *= shape[k];
- }
- }
- else {
- for (k=nd-1; k>=0; k--) {
- strides[k] = sd;
- sd *= shape[k];
- }
- }
- return;
-}
-
-int
-PyBuffer_FillInfo(Pep_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
- int readonly, int flags)
-{
- if (view == NULL) {
- PyErr_SetString(PyExc_BufferError,
- "PyBuffer_FillInfo: view==NULL argument is obsolete");
- return -1;
- }
-
- if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
- (readonly == 1)) {
- PyErr_SetString(PyExc_BufferError,
- "Object is not writable.");
- return -1;
- }
-
- view->obj = obj;
- if (obj)
- Py_INCREF(obj);
- view->buf = buf;
- view->len = len;
- view->readonly = readonly;
- view->itemsize = 1;
- view->format = NULL;
- if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
- view->format = (char *)"B"; // patched by CT
- view->ndim = 1;
- view->shape = NULL;
- if ((flags & PyBUF_ND) == PyBUF_ND)
- view->shape = &(view->len);
- view->strides = NULL;
- if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
- view->strides = &(view->itemsize);
- view->suboffsets = NULL;
- view->internal = NULL;
- return 0;
-}
-
-void
-PyBuffer_Release(Pep_buffer *view)
-{
- PyObject *obj = view->obj;
- PyBufferProcs *pb;
- if (obj == NULL)
- return;
- pb = PepType_AS_BUFFER(Py_TYPE(obj));
- if (pb && pb->bf_releasebuffer)
- pb->bf_releasebuffer(obj, view);
- view->obj = NULL;
- Py_DECREF(obj);
-}
-
-#endif // Py_LIMITED_API
diff --git a/sources/shiboken2/libshiboken/bufferprocs_py37.h b/sources/shiboken2/libshiboken/bufferprocs_py37.h
deleted file mode 100644
index 6fc7a3ece..000000000
--- a/sources/shiboken2/libshiboken/bufferprocs_py37.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*
-PSF LICENSE AGREEMENT FOR PYTHON 3.7.0
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
- the Individual or Organization ("Licensee") accessing and otherwise using Python
- 3.7.0 software in source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
- grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
- analyze, test, perform and/or display publicly, prepare derivative works,
- distribute, and otherwise use Python 3.7.0 alone or in any derivative
- version, provided, however, that PSF's License Agreement and PSF's notice of
- copyright, i.e., "Copyright © 2001-2018 Python Software Foundation; All Rights
- Reserved" are retained in Python 3.7.0 alone or in any derivative version
- prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on or
- incorporates Python 3.7.0 or any part thereof, and wants to make the
- derivative work available to others as provided herein, then Licensee hereby
- agrees to include in any such work a brief summary of the changes made to Python
- 3.7.0.
-
-4. PSF is making Python 3.7.0 available to Licensee on an "AS IS" basis.
- PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
- EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
- WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
- USE OF PYTHON 3.7.0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.7.0
- FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
- MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.7.0, OR ANY DERIVATIVE
- THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material breach of
- its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any relationship
- of agency, partnership, or joint venture between PSF and Licensee. This License
- Agreement does not grant permission to use PSF trademarks or trade name in a
- trademark sense to endorse or promote products or services of Licensee, or any
- third party.
-
-8. By copying, installing or otherwise using Python 3.7.0, Licensee agrees
- to be bound by the terms and conditions of this License Agreement.
-*/
-
-#ifndef BUFFER_REENABLE_H
-#define BUFFER_REENABLE_H
-
-/* buffer interface */
-// This has been renamed to Pep_buffer and will be used.
-typedef struct bufferinfo {
- void *buf;
- PyObject *obj; /* owned reference */
- Py_ssize_t len;
- Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
- pointed to by strides in simple case.*/
- int readonly;
- int ndim;
- char *format;
- Py_ssize_t *shape;
- Py_ssize_t *strides;
- Py_ssize_t *suboffsets;
- void *internal;
-} Pep_buffer;
-
-typedef int (*getbufferproc)(PyObject *, Pep_buffer *, int);
-typedef void (*releasebufferproc)(PyObject *, Pep_buffer *);
-
-/* Maximum number of dimensions */
-#define PyBUF_MAX_NDIM 64
-
-/* Flags for getting buffers */
-#define PyBUF_SIMPLE 0
-#define PyBUF_WRITABLE 0x0001
-/* we used to include an E, backwards compatible alias */
-#define PyBUF_WRITEABLE PyBUF_WRITABLE
-#define PyBUF_FORMAT 0x0004
-#define PyBUF_ND 0x0008
-#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
-#define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
-#define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
-#define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
-#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
-
-#define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE)
-#define PyBUF_CONTIG_RO (PyBUF_ND)
-
-#define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE)
-#define PyBUF_STRIDED_RO (PyBUF_STRIDES)
-
-#define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
-#define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT)
-
-#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
-#define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT)
-
-
-#define PyBUF_READ 0x100
-#define PyBUF_WRITE 0x200
-
-/* End buffer interface */
-LIBSHIBOKEN_API PyObject *PyMemoryView_FromBuffer(Pep_buffer *info);
-#define Py_buffer Pep_buffer
-
-#endif // BUFFER_REENABLE_H
diff --git a/sources/shiboken2/libshiboken/debugfreehook.cpp b/sources/shiboken2/libshiboken/debugfreehook.cpp
deleted file mode 100644
index 3d52d88dc..000000000
--- a/sources/shiboken2/libshiboken/debugfreehook.cpp
+++ /dev/null
@@ -1,194 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "debugfreehook.h"
-#include "bindingmanager.h"
-#include "gilstate.h"
-
-#if defined(_WIN32) && defined(_DEBUG)
-#include <crtdbg.h>
-#include <windows.h>
-#endif
-
-#ifdef __GLIBC__
-#include <malloc.h>
-#endif
-
-#ifdef __APPLE__
-#include <malloc/malloc.h>
-#include <mach/mach.h>
-#include <mach/mach_vm.h>
-#endif
-
-#ifdef SHIBOKEN_INSTALL_FREE_DEBUG_HOOK
-extern "C" {
-
-static int testPointerBeingFreed(void *ptr)
-{
- // It is an error for a deleted pointer address to still be registered
- // in the BindingManager
- if (Shiboken::BindingManager::instance().hasWrapper(ptr)) {
- Shiboken::GilState state;
-
- SbkObject *wrapper = Shiboken::BindingManager::instance().retrieveWrapper(ptr);
-
- fprintf(stderr, "SbkObject still in binding map when deleted: ");
- PyObject_Print(reinterpret_cast<PyObject *>(wrapper), stderr, 0);
- fprintf(stderr, "\n");
-
-#ifdef _WIN32
- DebugBreak();
-#else
- assert(0);
-#endif
- return FALSE;
- }
-
- return TRUE;
-}
-
-#if defined(_WIN32) && defined(_DEBUG)
-static _CRT_ALLOC_HOOK lastCrtAllocHook;
-static int DebugAllocHook(int nAllocType, void *pvData,
- size_t nSize, int nBlockUse, long lRequest,
- const unsigned char * szFileName, int nLine)
-{
- // It is an error for a deleted pointer address to still be registered
- // in the BindingManager
- if ( nAllocType == _HOOK_FREE) {
- if ( !testPointerBeingFreed(pvData) ) {
- return 0;
- }
- }
-
- if ( lastCrtAllocHook != NULL ) {
- return lastCrtAllocHook(nAllocType, pvData, nSize, nBlockUse, lRequest,
- szFileName, nLine);
- }
-
- return 1;
-}
-#endif // _WIN32 && _DEBUG
-
-#ifdef __GLIBC__
-static void (*lastFreeHook)(void *ptr, const void *caller);
-static void DebugFreeHook(void *ptr, const void *caller)
-{
- testPointerBeingFreed(ptr);
-
- if ( lastFreeHook != NULL )
- lastFreeHook(ptr, caller);
-}
-#endif // __GLIBC__
-
-#ifdef __APPLE__
-static malloc_zone_t lastMallocZone;
-static void DebugFreeHook(malloc_zone_t *zone, void *ptr)
-{
- testPointerBeingFreed(ptr);
-
- if ( lastMallocZone.free != NULL )
- lastMallocZone.free(zone, ptr);
-}
-static void DebugFreeDefiniteSizeHook(malloc_zone_t *zone, void *ptr, size_t size)
-{
- testPointerBeingFreed(ptr);
-
- if ( lastMallocZone.free_definite_size != NULL )
- lastMallocZone.free_definite_size(zone, ptr, size);
-}
-#endif __APPLE__
-
-void debugInstallFreeHook(void)
-{
-#if defined(_WIN32) && defined(_DEBUG)
- lastCrtAllocHook = _CrtSetAllocHook(DebugAllocHook);
-#endif
-
-#ifdef __GLIBC__
- // __free_hook is not thread safe so it marked as deprecated. Use here
- // is hopefully safe and should catch errors in a single threaded program
- // and only miss some in a multithreaded program
- lastFreeHook = __free_hook;
- __free_hook = DebugFreeHook;
-#endif
-
-#ifdef __APPLE__
- malloc_zone_t *zone = malloc_default_zone();
- assert(zone != NULL);
- //remove the write protection from the zone struct
- if (zone->version >= 8) {
- vm_protect(mach_task_self(), (uintptr_t)zone, sizeof(*zone), 0, VM_PROT_READ | VM_PROT_WRITE);
- }
- lastMallocZone = *zone;
- zone->free = DebugFreeHook;
- zone->free_definite_size = DebugFreeDefiniteSizeHook;
- if (zone->version >= 8) {
- vm_protect(mach_task_self(), (uintptr_t)zone, sizeof(*zone), 0, VM_PROT_READ);
- }
-#endif
-}
-
-void debugRemoveFreeHook(void)
-{
-#if defined(_WIN32) && defined(_DEBUG)
- _CrtSetAllocHook(lastCrtAllocHook);
-#endif
-
-#ifdef __GLIBC__
- __free_hook = lastFreeHook;
-#endif
-
-#ifdef __APPLE__
- malloc_zone_t *zone = malloc_default_zone();
- assert(zone != NULL);
- //remove the write protection from the zone struct
- if (zone->version >= 8) {
- vm_protect(mach_task_self(), (uintptr_t)zone, sizeof(*zone), 0, VM_PROT_READ | VM_PROT_WRITE);
- }
- zone->free = lastMallocZone.free;
- zone->free_definite_size = lastMallocZone.free_definite_size;
- if (zone->version >= 8) {
- vm_protect(mach_task_self(), (uintptr_t)zone, sizeof(*zone), 0, VM_PROT_READ);
- }
-#endif
-}
-
-} // extern "C"
-#endif // SHIBOKEN_INSTALL_DEBUG_FREE_HOOK
diff --git a/sources/shiboken2/libshiboken/debugfreehook.h b/sources/shiboken2/libshiboken/debugfreehook.h
deleted file mode 100644
index fdf98d5d3..000000000
--- a/sources/shiboken2/libshiboken/debugfreehook.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DEBUGFREEHOOK_H
-#define DEBUGFREEHOOK_H
-
-// These functions enable C library runtime hooks to try to catch cases where
-// C++ object addresses remain in hash table of valid wrappers when the address
-// is passed to free. The hooks are probably not thread safe and thus
-// should only be enabled in single threaded environments
-
-// To enable the hook, uncomment the following define.
-//#define SHIBOKEN_INSTALL_FREE_DEBUG_HOOK
-
-#ifdef SHIBOKEN_INSTALL_FREE_DEBUG_HOOK
-extern "C" {
-
-void debugInstallFreeHook(void);
-void debugRemoveFreeHook(void);
-
-} // extern "C"
-
-#endif // SHIBOKEN_INSTALL_FREE_DEBUG_HOOK
-
-#endif // DEBUGFREEHOOK_H
diff --git a/sources/shiboken2/libshiboken/embed/embedding_generator.py b/sources/shiboken2/libshiboken/embed/embedding_generator.py
deleted file mode 100644
index 15f63649b..000000000
--- a/sources/shiboken2/libshiboken/embed/embedding_generator.py
+++ /dev/null
@@ -1,242 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of PySide2.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-"""
-embedding_generator.py
-
-This file takes the content of the two supported directories and inserts
-it into a zip file. The zip file is then converted into a C++ source
-file that can easily be unpacked again with Python (see signature.cpp,
-constant 'PySide_PythonCode').
-
-Note that this _is_ a zipfile, but since it is embedded into the shiboken
-binary, we cannot use the zipimport module from Python.
-But a similar solution is possible that allows for normal imports.
-
-See signature_bootstrap.py for details.
-"""
-
-from __future__ import print_function, absolute_import
-
-import sys
-import os
-import subprocess
-import textwrap
-import tempfile
-import argparse
-import marshal
-import traceback
-
-# work_dir is set to the source for testing, onl.
-# It can be overridden in the command line.
-work_dir = os.path.abspath(os.path.dirname(__file__))
-embed_dir = work_dir
-cur_dir = os.getcwd()
-source_dir = os.path.normpath(os.path.join(work_dir, "..", "..", ".."))
-assert os.path.basename(source_dir) == "sources"
-build_script_dir = os.path.normpath(os.path.join(work_dir, "..", "..", "..", ".."))
-assert os.path.exists(os.path.join(build_script_dir, "build_scripts"))
-
-sys.path.insert(0, build_script_dir)
-
-from build_scripts import utils
-
-
-def runpy(cmd, **kw):
- subprocess.call([sys.executable, '-E'] + cmd.split(), **kw)
-
-
-def create_zipfile(limited_api):
- """
- Collect all Python files, compile them, create a zip file
- and make a chunked base64 encoded file from it.
- """
- zip_name = "signature.zip"
- inc_name = "signature_inc.h"
- flag = '-b' if sys.version_info >= (3,) else ''
- os.chdir(work_dir)
-
- # Remove all left-over py[co] and other files first, in case we use '--reuse-build'.
- # Note that we could improve that with the PyZipfile function to use .pyc files
- # in different folders, but that makes only sense when COIN allows us to have
- # multiple Python versions in parallel.
- from os.path import join, getsize
- for root, dirs, files in os.walk(work_dir):
- for name in files:
- fpath = os.path.join(root, name)
- ew = name.endswith
- if ew(".pyc") or ew(".pyo") or ew(".zip") or ew(".inc"):
- os.remove(fpath)
- # We copy every Python file into this dir, but only for the right version.
- # For testing in the source dir, we need to filter.
- if sys.version_info[0] == 3:
- ignore = "backport_inspect.py typing27.py".split()
- else:
- ignore = "".split()
- utils.copydir(os.path.join(source_dir, "shiboken2", "shibokenmodule", "files.dir", "shibokensupport"),
- os.path.join(work_dir, "shibokensupport"),
- ignore=ignore, file_filter_function=lambda name, n2: name.endswith(".py"))
- if embed_dir != work_dir:
- utils.copyfile(os.path.join(embed_dir, "signature_bootstrap.py"), work_dir)
-
- if limited_api:
- pass # We cannot compile, unless we have folders per Python version
- else:
- files = ' '.join(fn for fn in os.listdir('.'))
- runpy('-m compileall -q {flag} {files}'.format(**locals()))
- files = ' '.join(fn for fn in os.listdir('.') if not fn == zip_name)
- runpy('-m zipfile -c {zip_name} {files}'.format(**locals()))
- tmp = tempfile.TemporaryFile(mode="w+")
- runpy('-m base64 {zip_name}'.format(**locals()), stdout=tmp)
- # now generate the include file
- tmp.seek(0)
- with open(inc_name, "w") as inc:
- _embed_file(tmp, inc)
- tmp.close()
- # also generate a simple embeddable .pyc file for signature_bootstrap.pyc
- boot_name = "signature_bootstrap.py" if limited_api else "signature_bootstrap.pyc"
- with open(boot_name, "rb") as ldr, open("signature_bootstrap_inc.h", "w") as inc:
- _embed_bytefile(ldr, inc, limited_api)
- os.chdir(cur_dir)
-
-
-def _embed_file(fin, fout):
- """
- Format a text file for embedding in a C++ source file.
- """
- # MSVC has a 64k string limitation. In C, it would be easy to create an
- # array of 64 byte strings and use them as one big array. In C++ this does
- # not work, since C++ insists in having the terminating nullbyte.
- # Therefore, we split the string after an arbitrary number of lines
- # (chunked file).
- limit = 50
- text = fin.readlines()
- print(textwrap.dedent("""
- /*
- * This is a ZIP archive of all Python files in the directory
- * "shiboken2/shibokenmodule/files.dir/shibokensupport/signature"
- * There is also a toplevel file "signature_bootstrap.py[c]" that will be
- * directly executed from C++ as a bootstrap loader.
- */
- """).strip(), file=fout)
- block, blocks = 0, len(text) // limit + 1
- for idx, line in enumerate(text):
- if idx % limit == 0:
- comma = "," if block else ""
- block += 1
- print(file=fout)
- print('/* Block {block} of {blocks} */{comma}'.format(**locals()), file=fout)
- print('\"{}\"'.format(line.strip()), file=fout)
- print('/* Sentinel */, \"\"', file=fout)
-
-
-def _embed_bytefile(fin, fout, is_text):
- """
- Format a binary file for embedding in a C++ source file.
- This version works directly with a single .pyc file.
- """
- fname = fin.name
- remark = ("No .pyc file because '--LIMITED-API=yes'" if is_text else
- "The .pyc header is stripped away")
- print(textwrap.dedent("""
- /*
- * This is the file "{fname}" as a simple byte array.
- * It can be directly embedded without any further processing.
- * {remark}.
- */
- """).format(**locals()).strip(), file=fout)
- headsize = ( 0 if is_text else
- 16 if sys.version_info >= (3, 7) else 12 if sys.version_info >= (3, 3) else 8)
- binstr = fin.read()[headsize:]
- if is_text:
- try:
- compile(binstr, fin.name, "exec")
- except SyntaxError as e:
- print(e)
- traceback.print_exc(file=sys.stdout)
- print(textwrap.dedent("""
- *************************************************************************
- ***
- *** Could not compile the boot loader '{fname}'!
- ***
- *************************************************************************
- """).format(version=sys.version_info[:3], **locals()))
- raise SystemError
- else:
- try:
- marshal.loads(binstr)
- except ValueError as e:
- print(e)
- traceback.print_exc(file=sys.stdout)
- print(textwrap.dedent("""
- *************************************************************************
- ***
- *** This Python version {version} seems to have a new .pyc header size.
- *** Please correct the 'headsize' constant ({headsize}).
- ***
- *************************************************************************
- """).format(version=sys.version_info[:3], **locals()))
- raise SystemError
-
- print(file=fout)
- use_ord = sys.version_info[0] == 2
- for i in range(0, len(binstr), 16):
- for c in bytes(binstr[i : i + 16]):
- print("{:#4},".format(ord(c) if use_ord else c), file=fout, end="")
- print(file=fout)
- print("/* End Of File */", file=fout)
-
-
-def str2bool(v):
- if v.lower() in ('yes', 'true', 't', 'y', '1'):
- return True
- elif v.lower() in ('no', 'false', 'f', 'n', '0'):
- return False
- else:
- raise argparse.ArgumentTypeError('Boolean value expected.')
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser()
- parser.add_argument('--cmake-dir', nargs="?")
- parser.add_argument('--limited-api', type=str2bool)
- args = parser.parse_args()
- if args.cmake_dir:
- work_dir = os.path.abspath(args.cmake_dir)
- create_zipfile(args.limited_api)
diff --git a/sources/shiboken2/libshiboken/embed/module_collector.py b/sources/shiboken2/libshiboken/embed/module_collector.py
deleted file mode 100644
index 3eaa0be5d..000000000
--- a/sources/shiboken2/libshiboken/embed/module_collector.py
+++ /dev/null
@@ -1,105 +0,0 @@
-# This Python file uses the following encoding: utf-8
-# It has been edited by fix-complaints.py .
-
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-"""
-module_collector.py
-
-Collect a number of modules listed on the command line.
-
-The purpose of this script is to generate the scripts needed for
-a complete isolation of the signature extension.
-
-Usage:
-
-Run this script in one of the used python versions.
-It will create an executable archive of the files on the command line.
-"""
-
-import sys
-import os
-import argparse
-import pickle
-from textwrap import dedent
-
-def source_archive(module, modname):
- fname = os.path.splitext(module.__file__)[0] + ".py"
- with open(fname) as source:
- text = source.read()
- encoded = text.replace("'''", "(triple_single)")
- # modname = module.__name__
- # Do not use: Some modules rename themselves!
- version = ".".join(map(str, sys.version_info[:3]))
- shortname = os.path.basename(fname)
- preamble = dedent(r"""
- # BEGIN SOURCE ARCHIVE Python {version} module {modname}
-
- sources = {{}} if "sources" not in globals() else sources
- sources["{modname}"] = '''\
- {encoded}'''.replace("(triple_single)", "'''")
-
- # END SOURCE ARCHIVE Python {version} module {modname}
- """).format(**locals())
- return preamble
-
-def read_all(modules):
- collected = ""
- for modname in modules:
- mod = __import__(modname)
- collected += source_archive(mod, modname)
- return collected
-
-def license_header():
- license = os.path.join(os.path.dirname(__file__), "qt_python_license.txt")
- with open(license) as f:
- return f.read()
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser()
- parser.add_argument('modules', nargs="+")
- args = parser.parse_args()
- print("modules:", args.modules)
- ret = license_header() + read_all(args.modules)
- ma_mi = "_".join(map(str, sys.version_info[:2]))
- outpath = os.path.join(os.path.dirname(__file__), "..", "..", "shibokenmodule",
- "files.dir", "shibokensupport", "python_minilib_{ma_mi}.py".format(**locals()))
- with open(outpath, "w") as f:
- f.write(ret)
diff --git a/sources/shiboken2/libshiboken/embed/qt_python_license.txt b/sources/shiboken2/libshiboken/embed/qt_python_license.txt
deleted file mode 100644
index b5f8c581a..000000000
--- a/sources/shiboken2/libshiboken/embed/qt_python_license.txt
+++ /dev/null
@@ -1,87 +0,0 @@
-# This Python file uses the following encoding: utf-8
-# It has been edited by fix-complaints.py .
-
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-##
-## PSF LICENSE AGREEMENT FOR PYTHON 3.7.0
-##
-## 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
-## the Individual or Organization ("Licensee") accessing and otherwise using Python
-## 3.7.0 software in source or binary form and its associated documentation.
-##
-## 2. Subject to the terms and conditions of this License Agreement, PSF hereby
-## grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
-## analyze, test, perform and/or display publicly, prepare derivative works,
-## distribute, and otherwise use Python 3.7.0 alone or in any derivative
-## version, provided, however, that PSF's License Agreement and PSF's notice of
-## copyright, i.e., "Copyright © 2001-2018 Python Software Foundation; All Rights
-## Reserved" are retained in Python 3.7.0 alone or in any derivative version
-## prepared by Licensee.
-##
-## 3. In the event Licensee prepares a derivative work that is based on or
-## incorporates Python 3.7.0 or any part thereof, and wants to make the
-## derivative work available to others as provided herein, then Licensee hereby
-## agrees to include in any such work a brief summary of the changes made to Python
-## 3.7.0.
-##
-## 4. PSF is making Python 3.7.0 available to Licensee on an "AS IS" basis.
-## PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
-## EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
-## WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
-## USE OF PYTHON 3.7.0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-##
-## 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.7.0
-## FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
-## MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.7.0, OR ANY DERIVATIVE
-## THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-##
-## 6. This License Agreement will automatically terminate upon a material breach of
-## its terms and conditions.
-##
-## 7. Nothing in this License Agreement shall be deemed to create any relationship
-## of agency, partnership, or joint venture between PSF and Licensee. This License
-## Agreement does not grant permission to use PSF trademarks or trade name in a
-## trademark sense to endorse or promote products or services of Licensee, or any
-## third party.
-##
-## 8. By copying, installing or otherwise using Python 3.7.0, Licensee agrees
-## to be bound by the terms and conditions of this License Agreement.
-##
diff --git a/sources/shiboken2/libshiboken/embed/signature_bootstrap.py b/sources/shiboken2/libshiboken/embed/signature_bootstrap.py
deleted file mode 100644
index eb182d8c4..000000000
--- a/sources/shiboken2/libshiboken/embed/signature_bootstrap.py
+++ /dev/null
@@ -1,180 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of PySide2.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-"""
-signature_bootstrap.py
-----------------------
-
-This file was originally directly embedded into the C source.
-After it grew more and more, I now prefer to have it as Python file.
-
-Meanwhile, there is also no more a stub loader necessary:
-Because we meanwhile have embedding support, we could also load this file
-directly from a .pyc file.
-
-This file replaces the hard to read Python stub in 'signature.cpp', and we
-could distinguish better between bootstrap related functions and loader
-functions.
-It is embedded into 'signature.cpp' as "embed/signature_bootstrap.inc".
-"""
-
-from __future__ import print_function, absolute_import
-
-recursion_trap = 0
-
-# We avoid real imports in phase 1 that could fail (simply removed all).
-# Python 2 is not able to import when the extension import is still active.
-# Phase 1 simply defines the functions, which will be used in Phase 2.
-
-def bootstrap():
- import sys
- import os
- import tempfile
- import traceback
- from contextlib import contextmanager
-
- global recursion_trap
- if recursion_trap:
- # we are probably called from outside, already
- print("Recursion occurred in Bootstrap. Did you start by hand? Then it's ok.")
- print("But you should trigger start by 'type.__signature__', only!")
- recursion_trap += 1
-
- @contextmanager
- def ensure_shibokensupport(support_path):
- # Make sure that we always have the shibokensupport containing package first.
- # Also remove any prior loaded module of this name, just in case.
- sys.path.insert(0, support_path)
-
- sbks = "shibokensupport"
- if sbks in sys.modules:
- del sys.modules[sbks]
- prefix = sbks + "."
- for key in list(key for key in sys.modules if key.startswith(prefix)):
- del sys.modules[key]
- try:
- import shibokensupport
- yield
- except Exception as e:
- print("Problem importing shibokensupport:")
- print(e)
- traceback.print_exc()
- print("sys.path:")
- for p in sys.path:
- print(" " + p)
- sys.stdout.flush()
- sys.exit(-1)
- sys.path.remove(support_path)
-
- try:
- import shiboken2 as root
- except ImportError:
- # uninstalled case without ctest, try only this one which has __init__:
- import shibokenmodule as root
- rp = os.path.realpath(os.path.dirname(root.__file__))
- # This can be the shiboken2 directory or the binary module, so search.
- look_for = os.path.join("files.dir", "shibokensupport", "signature", "loader.py")
- while len(rp) > 3 and not os.path.exists(os.path.join(rp, look_for)):
- rp = os.path.abspath(os.path.join(rp, ".."))
-
- # Here we decide if we work embedded or not.
- embedding_var = "pyside_uses_embedding"
- use_embedding = bool(getattr(sys, embedding_var, False))
- # We keep the zip file for inspection if the sys variable has been set.
- keep_zipfile = hasattr(sys, embedding_var)
- loader_path = os.path.join(rp, look_for)
- files_dir = os.path.abspath(os.path.join(loader_path, "..", "..", ".."))
- assert files_dir.endswith("files.dir")
-
- # We report in sys what we used. We could put more here as well.
- if not os.path.exists(loader_path):
- use_embedding = True
- support_path = prepare_zipfile() if use_embedding else files_dir
- setattr(sys, embedding_var, use_embedding)
-
- try:
- with ensure_shibokensupport(support_path):
- from shibokensupport.signature import loader
-
- except Exception as e:
- print('Exception:', e)
- traceback.print_exc(file=sys.stdout)
-
- finally:
- if use_embedding and not keep_zipfile:
- # clear the temp zipfile
- try:
- os.remove(support_path)
- except OSError as e:
- print(e)
- print("Error deleting {support_path}, ignored".format(**locals()))
- return loader
-
-# New functionality: Loading from a zip archive.
-# There exists the zip importer, but as it is written, only real zip files are
-# supported. Before I will start an own implementation, it is easiest to use
-# a temporary zip file.
-
-def prepare_zipfile():
- """
- Write the zip file to a real file and return its name.
- It will be implicitly opened as such when we add the name to sys.path .
- """
- import base64
- import tempfile
- import os
- import zipfile
-
- # 'zipstring_sequence' comes from signature.cpp
- zipbytes = base64.b64decode(''.join(zipstring_sequence))
- fd, fname = tempfile.mkstemp(prefix='embedded.', suffix='.zip')
- os.write(fd, zipbytes)
- os.close(fd)
- # Let us test the zipfile if it really is one.
- # Otherwise, zipimporter would simply ignore it without notice.
- try:
- z = zipfile.ZipFile(fname)
- z.close()
- except zipfile.BadZipFile as e:
- print('Broken Zip File:', e)
- traceback.print_exc(file=sys.stdout)
- finally:
- return fname
-
-# eof
diff --git a/sources/shiboken2/libshiboken/gilstate.cpp b/sources/shiboken2/libshiboken/gilstate.cpp
deleted file mode 100644
index a59c6f01e..000000000
--- a/sources/shiboken2/libshiboken/gilstate.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "gilstate.h"
-
-namespace Shiboken
-{
-
-GilState::GilState()
-{
- if (Py_IsInitialized()) {
- m_gstate = PyGILState_Ensure();
- m_locked = true;
- }
-}
-
-GilState::~GilState()
-{
- release();
-}
-
-void GilState::release()
-{
- if (m_locked && Py_IsInitialized()) {
- PyGILState_Release(m_gstate);
- m_locked = false;
- }
-}
-
-} // namespace Shiboken
-
diff --git a/sources/shiboken2/libshiboken/gilstate.h b/sources/shiboken2/libshiboken/gilstate.h
deleted file mode 100644
index d22f688ba..000000000
--- a/sources/shiboken2/libshiboken/gilstate.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef GILSTATE_H
-#define GILSTATE_H
-
-#include <shibokenmacros.h>
-#include "sbkpython.h"
-
-namespace Shiboken
-{
-
-class LIBSHIBOKEN_API GilState
-{
-public:
- GilState(const GilState &) = delete;
- GilState(GilState &&) = delete;
- GilState &operator=(const GilState &) = delete;
- GilState &operator=(GilState &&) = delete;
-
- GilState();
- ~GilState();
- void release();
-private:
- PyGILState_STATE m_gstate;
- bool m_locked = false;
-};
-
-} // namespace Shiboken
-
-#endif // GILSTATE_H
-
diff --git a/sources/shiboken2/libshiboken/helper.cpp b/sources/shiboken2/libshiboken/helper.cpp
deleted file mode 100644
index b0f909d39..000000000
--- a/sources/shiboken2/libshiboken/helper.cpp
+++ /dev/null
@@ -1,281 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "helper.h"
-#include "sbkstring.h"
-#include "sbkstaticstrings.h"
-
-#include <iomanip>
-#include <iostream>
-
-#include <stdarg.h>
-
-#ifdef _WIN32
-# ifndef NOMINMAX
-# define NOMINMAX
-# endif
-# include <windows.h>
-#else
-# include <pthread.h>
-#endif
-
-#include <algorithm>
-
-static void formatPyTypeObject(const PyTypeObject *obj, std::ostream &str)
-{
- if (obj) {
- str << '"' << obj->tp_name << "\", 0x" << std::hex
- << obj->tp_flags << std::dec;
- if (obj->tp_flags & Py_TPFLAGS_HEAPTYPE)
- str << " [heaptype]";
- if (obj->tp_flags & Py_TPFLAGS_BASETYPE)
- str << " [base]";
- if (obj->tp_flags & Py_TPFLAGS_HAVE_GC)
- str << " [gc]";
- if (obj->tp_flags & Py_TPFLAGS_LONG_SUBCLASS)
- str << " [long]";
- if (obj->tp_flags & Py_TPFLAGS_LIST_SUBCLASS)
- str << " [list]";
- if (obj->tp_flags & Py_TPFLAGS_TUPLE_SUBCLASS)
- str << " [tuple]";
- if (obj->tp_flags & Py_TPFLAGS_BYTES_SUBCLASS)
- str << " [bytes]";
- if (obj->tp_flags & Py_TPFLAGS_UNICODE_SUBCLASS)
- str << " [unicode]";
- if (obj->tp_flags & Py_TPFLAGS_DICT_SUBCLASS)
- str << " [dict]";
- if (obj->tp_flags & Py_TPFLAGS_TYPE_SUBCLASS)
- str << " [type]";
- if (obj->tp_flags & Py_TPFLAGS_IS_ABSTRACT)
- str << " [abstract]";
- } else {
- str << '0';
- }
-}
-
-static void formatPyObject(PyObject *obj, std::ostream &str);
-
-static void formatPySequence(PyObject *obj, std::ostream &str)
-{
- const Py_ssize_t size = PySequence_Size(obj);
- const Py_ssize_t printSize = std::min(size, Py_ssize_t(5));
- str << size << " <";
- for (Py_ssize_t i = 0; i < printSize; ++i) {
- if (i)
- str << ", ";
- str << '(';
- PyObject *item = PySequence_GetItem(obj, i);
- formatPyObject(item, str);
- str << ')';
- Py_XDECREF(item);
- }
- if (printSize < size)
- str << ",...";
- str << '>';
-}
-
-static void formatPyObject(PyObject *obj, std::ostream &str)
-{
- if (obj) {
- formatPyTypeObject(obj->ob_type, str);
- str << ", ";
- if (PyLong_Check(obj))
- str << PyLong_AsLong(obj);
- else if (PyFloat_Check(obj))
- str << PyFloat_AsDouble(obj);
-#ifdef IS_PY3K
- else if (PyUnicode_Check(obj))
- str << '"' << _PepUnicode_AsString(obj) << '"';
-#else
- else if (PyString_Check(obj))
- str << '"' << PyString_AsString(obj) << '"';
-#endif
- else if (PySequence_Check(obj))
- formatPySequence(obj, str);
- else
- str << "<unknown>";
- } else {
- str << '0';
- }
-}
-
-namespace Shiboken
-{
-
-debugPyObject::debugPyObject(PyObject *o) : m_object(o)
-{
-}
-
-debugPyTypeObject::debugPyTypeObject(const PyTypeObject *o) : m_object(o)
-{
-}
-
-std::ostream &operator<<(std::ostream &str, const debugPyTypeObject &o)
-{
- str << "PyTypeObject(";
- formatPyTypeObject(o.m_object, str);
- str << ')';
- return str;
-}
-
-std::ostream &operator<<(std::ostream &str, const debugPyObject &o)
-{
- str << "PyObject(";
- formatPyObject(o.m_object, str);
- str << ')';
- return str;
-}
-
-// PySide-510: Changed from PySequence to PyList, which is correct.
-bool listToArgcArgv(PyObject *argList, int *argc, char ***argv, const char *defaultAppName)
-{
- if (!PyList_Check(argList))
- return false;
-
- if (!defaultAppName)
- defaultAppName = "PySideApplication";
-
- // Check all items
- Shiboken::AutoDecRef args(PySequence_Fast(argList, nullptr));
- int numArgs = int(PySequence_Fast_GET_SIZE(argList));
- for (int i = 0; i < numArgs; ++i) {
- PyObject *item = PyList_GET_ITEM(args.object(), i);
- if (!PyBytes_Check(item) && !PyUnicode_Check(item))
- return false;
- }
-
- bool hasEmptyArgList = numArgs == 0;
- if (hasEmptyArgList)
- numArgs = 1;
-
- *argc = numArgs;
- *argv = new char *[*argc];
-
- if (hasEmptyArgList) {
- // Try to get the script name
- PyObject *globals = PyEval_GetGlobals();
- PyObject *appName = PyDict_GetItem(globals, Shiboken::PyMagicName::file());
- (*argv)[0] = strdup(appName ? Shiboken::String::toCString(appName) : defaultAppName);
- } else {
- for (int i = 0; i < numArgs; ++i) {
- PyObject *item = PyList_GET_ITEM(args.object(), i);
- char *string = nullptr;
- if (Shiboken::String::check(item)) {
- string = strdup(Shiboken::String::toCString(item));
- }
- (*argv)[i] = string;
- }
- }
-
- return true;
-}
-
-int *sequenceToIntArray(PyObject *obj, bool zeroTerminated)
-{
- AutoDecRef seq(PySequence_Fast(obj, "Sequence of ints expected"));
- if (seq.isNull())
- return nullptr;
-
- Py_ssize_t size = PySequence_Fast_GET_SIZE(seq.object());
- int *array = new int[size + (zeroTerminated ? 1 : 0)];
-
- for (int i = 0; i < size; i++) {
- PyObject *item = PySequence_Fast_GET_ITEM(seq.object(), i);
- if (!PyInt_Check(item)) {
- PyErr_SetString(PyExc_TypeError, "Sequence of ints expected");
- delete[] array;
- return nullptr;
- }
- array[i] = PyInt_AsLong(item);
- }
-
- if (zeroTerminated)
- array[size] = 0;
-
- return array;
-}
-
-
-int warning(PyObject *category, int stacklevel, const char *format, ...)
-{
- va_list args;
- va_start(args, format);
-#ifdef _WIN32
- va_list args2 = args;
-#else
- va_list args2;
- va_copy(args2, args);
-#endif
-
- // check the necessary memory
- int size = vsnprintf(nullptr, 0, format, args) + 1;
- auto message = new char[size];
- int result = 0;
- if (message) {
- // format the message
- vsnprintf(message, size, format, args2);
- result = PyErr_WarnEx(category, message, stacklevel);
- delete [] message;
- }
- va_end(args2);
- va_end(args);
- return result;
-}
-
-ThreadId currentThreadId()
-{
-#if defined(_WIN32)
- return GetCurrentThreadId();
-#elif defined(__APPLE_CC__)
- return reinterpret_cast<ThreadId>(pthread_self());
-#else
- return pthread_self();
-#endif
-}
-
-// Internal, used by init() from main thread
-static ThreadId _mainThreadId{0};
-void _initMainThreadId() { _mainThreadId = currentThreadId(); }
-
-ThreadId mainThreadId()
-{
- return _mainThreadId;
-}
-
-} // namespace Shiboken
diff --git a/sources/shiboken2/libshiboken/helper.h b/sources/shiboken2/libshiboken/helper.h
deleted file mode 100644
index 7e46f3d93..000000000
--- a/sources/shiboken2/libshiboken/helper.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef HELPER_H
-#define HELPER_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-#include "autodecref.h"
-
-#include <iosfwd>
-
-#define SBK_UNUSED(x) (void)(x);
-
-namespace Shiboken
-{
-
-/**
-* It transforms a python sequence into two C variables, argc and argv.
-* This function tries to find the application (script) name and put it into argv[0], if
-* the application name can't be guessed, defaultAppName will be used.
-*
-* No memory is allocated is an error occur.
-*
-* \note argc must be a valid address.
-* \note The argv array is allocated using new operator and each item is allocated using malloc.
-* \returns True on sucess, false otherwise.
-*/
-LIBSHIBOKEN_API bool listToArgcArgv(PyObject *argList, int *argc, char ***argv, const char *defaultAppName = nullptr);
-
-/**
- * Convert a python sequence into a heap-allocated array of ints.
- *
- * \returns The newly allocated array or NULL in case of error or empty sequence. Check with PyErr_Occurred
- * if it was successfull.
- */
-LIBSHIBOKEN_API int *sequenceToIntArray(PyObject *obj, bool zeroTerminated = false);
-
-/**
- * Creates and automatically deallocates C++ arrays.
- */
-template<class T>
-class AutoArrayPointer
-{
- public:
- AutoArrayPointer(const AutoArrayPointer &) = delete;
- AutoArrayPointer(AutoArrayPointer &&) = delete;
- AutoArrayPointer &operator=(const AutoArrayPointer &) = delete;
- AutoArrayPointer &operator=(AutoArrayPointer &&) = delete;
-
- explicit AutoArrayPointer(int size) { data = new T[size]; }
- T &operator[](int pos) { return data[pos]; }
- operator T *() const { return data; }
- ~AutoArrayPointer() { delete[] data; }
- private:
- T *data;
-};
-
-using ThreadId = unsigned long long;
-LIBSHIBOKEN_API ThreadId currentThreadId();
-LIBSHIBOKEN_API ThreadId mainThreadId();
-
-/**
- * An utility function used to call PyErr_WarnEx with a formatted message.
- */
-LIBSHIBOKEN_API int warning(PyObject *category, int stacklevel, const char *format, ...);
-
-struct LIBSHIBOKEN_API debugPyObject
-{
- explicit debugPyObject(PyObject *o);
-
- PyObject *m_object;
-};
-
-struct LIBSHIBOKEN_API debugPyTypeObject
-{
- explicit debugPyTypeObject(const PyTypeObject *o);
-
- const PyTypeObject *m_object;
-};
-
-LIBSHIBOKEN_API std::ostream &operator<<(std::ostream &str, const debugPyObject &o);
-LIBSHIBOKEN_API std::ostream &operator<<(std::ostream &str, const debugPyTypeObject &o);
-
-} // namespace Shiboken
-
-
-#endif // HELPER_H
diff --git a/sources/shiboken2/libshiboken/pep384_issue33738.cpp b/sources/shiboken2/libshiboken/pep384_issue33738.cpp
deleted file mode 100644
index c20edeefa..000000000
--- a/sources/shiboken2/libshiboken/pep384_issue33738.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// There is a bug in Python 3.6 that turned the Index_Check function
-// into a macro without taking care of the limited API.
-// This leads to the single problem that we don't have
-// access to PyLong_Type's nb_index field which is no heap type.
-// We cannot easily create this function by inheritance since it is
-// not inherited.
-//
-// Simple solution: Create the structure and write such a function.
-// Long term: Submit a patch to python.org .
-
-// Update: I did the long-term solution for python 3.7 in issue 33738.
-
-typedef struct {
- /* Number implementations must check *both*
- arguments for proper type and implement the necessary conversions
- in the slot functions themselves. */
-
- binaryfunc nb_add;
- binaryfunc nb_subtract;
- binaryfunc nb_multiply;
- binaryfunc nb_remainder;
- binaryfunc nb_divmod;
- ternaryfunc nb_power;
- unaryfunc nb_negative;
- unaryfunc nb_positive;
- unaryfunc nb_absolute;
- inquiry nb_bool;
- unaryfunc nb_invert;
- binaryfunc nb_lshift;
- binaryfunc nb_rshift;
- binaryfunc nb_and;
- binaryfunc nb_xor;
- binaryfunc nb_or;
- unaryfunc nb_int;
- void *nb_reserved; /* the slot formerly known as nb_long */
- unaryfunc nb_float;
-
- binaryfunc nb_inplace_add;
- binaryfunc nb_inplace_subtract;
- binaryfunc nb_inplace_multiply;
- binaryfunc nb_inplace_remainder;
- ternaryfunc nb_inplace_power;
- binaryfunc nb_inplace_lshift;
- binaryfunc nb_inplace_rshift;
- binaryfunc nb_inplace_and;
- binaryfunc nb_inplace_xor;
- binaryfunc nb_inplace_or;
-
- binaryfunc nb_floor_divide;
- binaryfunc nb_true_divide;
- binaryfunc nb_inplace_floor_divide;
- binaryfunc nb_inplace_true_divide;
-
- unaryfunc nb_index;
-
- binaryfunc nb_matrix_multiply;
- binaryfunc nb_inplace_matrix_multiply;
-} PyNumberMethods;
-
-// temporary structure until we have a generator for the offsets
-typedef struct _oldtypeobject {
- PyVarObject ob_base;
- void *X01; // const char *tp_name;
- void *X02; // Py_ssize_t tp_basicsize;
- void *X03; // Py_ssize_t tp_itemsize;
- void *X04; // destructor tp_dealloc;
- void *X05; // printfunc tp_print;
- void *X06; // getattrfunc tp_getattr;
- void *X07; // setattrfunc tp_setattr;
- void *X08; // PyAsyncMethods *tp_as_async;
- void *X09; // reprfunc tp_repr;
- PyNumberMethods *tp_as_number;
-
-} PyOldTypeObject;
-
-int PyIndex_Check(PyObject *obj)
-{
- PyOldTypeObject *type = reinterpret_cast<PyOldTypeObject *>(Py_TYPE(obj));
- return type->tp_as_number != NULL &&
- type->tp_as_number->nb_index != NULL;
-}
-
diff --git a/sources/shiboken2/libshiboken/pep384impl.cpp b/sources/shiboken2/libshiboken/pep384impl.cpp
deleted file mode 100644
index f07cac613..000000000
--- a/sources/shiboken2/libshiboken/pep384impl.cpp
+++ /dev/null
@@ -1,802 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkpython.h"
-#include "autodecref.h"
-#include "sbkstaticstrings.h"
-#include "sbkstaticstrings_p.h"
-#include <stdlib.h>
-
-
-extern "C"
-{
-
-/*
- * The documentation is located in pep384impl_doc.rst
- */
-#if PY_VERSION_HEX < 0x03000000
-#define IS_PY2
-#endif // PY_VERSION_HEX < 0x03000000
-/*
- * Here is the verification code for PyTypeObject.
- * We create a type object and check if its fields
- * appear at the right offsets.
- */
-#ifdef Py_LIMITED_API
-
-#define make_dummy_int(x) (x * sizeof(void *))
-#define make_dummy(x) (reinterpret_cast<void *>(make_dummy_int(x)))
-
-static PyObject *
-dummy_func(PyObject * /* self */, PyObject * /* args */)
-{
- Py_RETURN_NONE;
-}
-
-static struct PyMethodDef probe_methoddef[] = {
- {"dummy", dummy_func, METH_NOARGS},
- {nullptr}
-};
-
-static PyGetSetDef probe_getseters[] = {
- {nullptr} /* Sentinel */
-};
-
-#define probe_tp_dealloc make_dummy(1)
-#define probe_tp_repr make_dummy(2)
-#define probe_tp_call make_dummy(3)
-#define probe_tp_str make_dummy(4)
-#define probe_tp_traverse make_dummy(5)
-#define probe_tp_clear make_dummy(6)
-#define probe_tp_iternext make_dummy(7)
-#define probe_tp_methods probe_methoddef
-#define probe_tp_getset probe_getseters
-#define probe_tp_descr_get make_dummy(10)
-#define probe_tp_init make_dummy(11)
-#define probe_tp_alloc make_dummy(12)
-#define probe_tp_new make_dummy(13)
-#define probe_tp_free make_dummy(14)
-#define probe_tp_is_gc make_dummy(15)
-
-#define probe_tp_name "type.probe"
-#define probe_tp_basicsize make_dummy_int(42)
-
-static PyType_Slot typeprobe_slots[] = {
- {Py_tp_dealloc, probe_tp_dealloc},
- {Py_tp_repr, probe_tp_repr},
- {Py_tp_call, probe_tp_call},
- {Py_tp_str, probe_tp_str},
- {Py_tp_traverse, probe_tp_traverse},
- {Py_tp_clear, probe_tp_clear},
- {Py_tp_iternext, probe_tp_iternext},
- {Py_tp_methods, probe_tp_methods},
- {Py_tp_getset, probe_tp_getset},
- {Py_tp_descr_get, probe_tp_descr_get},
- {Py_tp_init, probe_tp_init},
- {Py_tp_alloc, probe_tp_alloc},
- {Py_tp_new, probe_tp_new},
- {Py_tp_free, probe_tp_free},
- {Py_tp_is_gc, probe_tp_is_gc},
- {0, nullptr}
-};
-static PyType_Spec typeprobe_spec = {
- probe_tp_name,
- probe_tp_basicsize,
- 0,
- Py_TPFLAGS_DEFAULT,
- typeprobe_slots,
-};
-
-static void
-check_PyTypeObject_valid()
-{
- auto *obtype = reinterpret_cast<PyObject *>(&PyType_Type);
- auto *probe_tp_base = reinterpret_cast<PyTypeObject *>(
- PyObject_GetAttr(obtype, Shiboken::PyMagicName::base()));
- auto *probe_tp_bases = PyObject_GetAttr(obtype, Shiboken::PyMagicName::bases());
- auto *check = reinterpret_cast<PyTypeObject *>(
- PyType_FromSpecWithBases(&typeprobe_spec, probe_tp_bases));
- auto *typetype = reinterpret_cast<PyTypeObject *>(obtype);
- PyObject *w = PyObject_GetAttr(obtype, Shiboken::PyMagicName::weakrefoffset());
- long probe_tp_weakrefoffset = PyLong_AsLong(w);
- PyObject *d = PyObject_GetAttr(obtype, Shiboken::PyMagicName::dictoffset());
- long probe_tp_dictoffset = PyLong_AsLong(d);
- PyObject *probe_tp_mro = PyObject_GetAttr(obtype, Shiboken::PyMagicName::mro());
- if (false
- || strcmp(probe_tp_name, check->tp_name) != 0
- || probe_tp_basicsize != check->tp_basicsize
- || probe_tp_dealloc != check->tp_dealloc
- || probe_tp_repr != check->tp_repr
- || probe_tp_call != check->tp_call
- || probe_tp_str != check->tp_str
- || probe_tp_traverse != check->tp_traverse
- || probe_tp_clear != check->tp_clear
- || probe_tp_weakrefoffset != typetype->tp_weaklistoffset
- || probe_tp_iternext != check->tp_iternext
- || probe_tp_methods != check->tp_methods
- || probe_tp_getset != check->tp_getset
- || probe_tp_base != typetype->tp_base
- || !PyDict_Check(check->tp_dict)
- || !PyDict_GetItemString(check->tp_dict, "dummy")
- || probe_tp_descr_get != check->tp_descr_get
- || probe_tp_dictoffset != typetype->tp_dictoffset
- || probe_tp_init != check->tp_init
- || probe_tp_alloc != check->tp_alloc
- || probe_tp_new != check->tp_new
- || probe_tp_free != check->tp_free
- || probe_tp_is_gc != check->tp_is_gc
- || probe_tp_bases != typetype->tp_bases
- || probe_tp_mro != typetype->tp_mro
- || Py_TPFLAGS_DEFAULT != (check->tp_flags & Py_TPFLAGS_DEFAULT))
- Py_FatalError("The structure of type objects has changed!");
- Py_DECREF(check);
- Py_DECREF(probe_tp_base);
- Py_DECREF(w);
- Py_DECREF(d);
- Py_DECREF(probe_tp_bases);
- Py_DECREF(probe_tp_mro);
-}
-
-#if PY_VERSION_HEX < PY_ISSUE33738_SOLVED
-#include "pep384_issue33738.cpp"
-#endif
-
-#endif // Py_LIMITED_API
-
-/*****************************************************************************
- *
- * Support for unicodeobject.h
- *
- */
-#ifdef Py_LIMITED_API
-
-char *
-_PepUnicode_AsString(PyObject *str)
-{
- /*
- * We need to keep the string alive but cannot borrow the Python object.
- * Ugly easy way out: We re-code as an interned bytes string. This
- * produces a pseudo-leak as long as there are new strings.
- * Typically, this function is used for name strings, and the dict size
- * will not grow so much.
- */
-#define STRINGIFY(x) #x
-#define TOSTRING(x) STRINGIFY(x)
-#define AT __FILE__ ":" TOSTRING(__LINE__)
-
- static PyObject *cstring_dict = nullptr;
- if (cstring_dict == nullptr) {
- cstring_dict = PyDict_New();
- if (cstring_dict == nullptr)
- Py_FatalError("Error in " AT);
- }
- PyObject *bytesStr = PyUnicode_AsEncodedString(str, "utf8", nullptr);
- PyObject *entry = PyDict_GetItemWithError(cstring_dict, bytesStr);
- if (entry == nullptr) {
- int e = PyDict_SetItem(cstring_dict, bytesStr, bytesStr);
- if (e != 0)
- Py_FatalError("Error in " AT);
- entry = bytesStr;
- }
- else
- Py_DECREF(bytesStr);
- return PyBytes_AsString(entry);
-}
-#endif // Py_LIMITED_API
-
-/*****************************************************************************
- *
- * Support for longobject.h
- *
- */
-#ifdef Py_LIMITED_API
-
-/*
- * This is the original Python function _PyLong_AsInt() from longobject.c .
- * We define it here because we are not allowed to use the function
- * from Python with an underscore.
- */
-
-/* Get a C int from an int object or any object that has an __int__
- method. Return -1 and set an error if overflow occurs. */
-
-int
-_PepLong_AsInt(PyObject *obj)
-{
- int overflow;
- long result = PyLong_AsLongAndOverflow(obj, &overflow);
- if (overflow || result > INT_MAX || result < INT_MIN) {
- /* XXX: could be cute and give a different
- message for overflow == -1 */
- PyErr_SetString(PyExc_OverflowError,
- "Python int too large to convert to C int");
- return -1;
- }
- return int(result);
-}
-#endif // Py_LIMITED_API
-
-/*****************************************************************************
- *
- * Support for pydebug.h
- *
- */
-#ifdef Py_LIMITED_API
-
-static PyObject *sys_flags = nullptr;
-
-int
-Pep_GetFlag(const char *name)
-{
- static int initialized = 0;
- int ret = -1;
-
- if (!initialized) {
- sys_flags = PySys_GetObject("flags");
- // func gives no error if nullptr is returned and does not incref.
- Py_XINCREF(sys_flags);
- initialized = 1;
- }
- if (sys_flags != nullptr) {
- PyObject *ob_ret = PyObject_GetAttrString(sys_flags, name);
- if (ob_ret != nullptr) {
- long long_ret = PyLong_AsLong(ob_ret);
- Py_DECREF(ob_ret);
- ret = (int) long_ret;
- }
- }
- return ret;
-}
-
-int
-Pep_GetVerboseFlag()
-{
- static int initialized = 0;
- static int verbose_flag = -1;
-
- if (!initialized) {
- verbose_flag = Pep_GetFlag("verbose");
- if (verbose_flag != -1)
- initialized = 1;
- }
- return verbose_flag;
-}
-#endif // Py_LIMITED_API
-
-/*****************************************************************************
- *
- * Support for code.h
- *
- */
-#ifdef Py_LIMITED_API
-
-int
-PepCode_Get(PyCodeObject *co, const char *name)
-{
- PyObject *ob = (PyObject *)co;
- PyObject *ob_ret;
- int ret = -1;
-
- ob_ret = PyObject_GetAttrString(ob, name);
- if (ob_ret != nullptr) {
- long long_ret = PyLong_AsLong(ob_ret);
- Py_DECREF(ob_ret);
- ret = (int) long_ret;
- }
- return ret;
-}
-#endif // Py_LIMITED_API
-
-/*****************************************************************************
- *
- * Support for datetime.h
- *
- */
-#ifdef Py_LIMITED_API
-
-datetime_struc *PyDateTimeAPI = nullptr;
-
-static PyTypeObject *dt_getCheck(const char *name)
-{
- PyObject *op = PyObject_GetAttrString(PyDateTimeAPI->module, name);
- if (op == nullptr) {
- fprintf(stderr, "datetime.%s not found\n", name);
- Py_FatalError("aborting");
- }
- return reinterpret_cast<PyTypeObject *>(op);
-}
-
-// init_DateTime is called earlier than our module init.
-// We use the provided PyDateTime_IMPORT machinery.
-datetime_struc *
-init_DateTime(void)
-{
- static int initialized = 0;
- if (!initialized) {
- PyDateTimeAPI = (datetime_struc *)malloc(sizeof(datetime_struc));
- if (PyDateTimeAPI == nullptr)
- Py_FatalError("PyDateTimeAPI malloc error, aborting");
- PyDateTimeAPI->module = PyImport_ImportModule("datetime");
- if (PyDateTimeAPI->module == nullptr)
- Py_FatalError("datetime module not found, aborting");
- PyDateTimeAPI->DateType = dt_getCheck("date");
- PyDateTimeAPI->DateTimeType = dt_getCheck("datetime");
- PyDateTimeAPI->TimeType = dt_getCheck("time");
- PyDateTimeAPI->DeltaType = dt_getCheck("timedelta");
- PyDateTimeAPI->TZInfoType = dt_getCheck("tzinfo");
- initialized = 1;
- }
- return PyDateTimeAPI;
-}
-
-int
-PyDateTime_Get(PyObject *ob, const char *name)
-{
- PyObject *ob_ret;
- int ret = -1;
-
- ob_ret = PyObject_GetAttrString(ob, name);
- if (ob_ret != nullptr) {
- long long_ret = PyLong_AsLong(ob_ret);
- Py_DECREF(ob_ret);
- ret = (int) long_ret;
- }
- return ret;
-}
-
-PyObject *
-PyDate_FromDate(int year, int month, int day)
-{
- return PyObject_CallFunction((PyObject *)PyDateTimeAPI->DateType,
- (char *)"(iii)", year, month, day);
-}
-
-PyObject *
-PyDateTime_FromDateAndTime(int year, int month, int day,
- int hour, int min, int sec, int usec)
-{
- return PyObject_CallFunction((PyObject *)PyDateTimeAPI->DateTimeType,
- (char *)"(iiiiiii)", year, month, day,
- hour, min, sec, usec);
-}
-
-PyObject *
-PyTime_FromTime(int hour, int min, int sec, int usec)
-{
- return PyObject_CallFunction((PyObject *)PyDateTimeAPI->TimeType,
- (char *)"(iiii)", hour, min, sec, usec);
-}
-#endif // Py_LIMITED_API
-
-/*****************************************************************************
- *
- * Support for pythonrun.h
- *
- */
-#ifdef Py_LIMITED_API
-
-// Flags are ignored in these simple helpers.
-PyObject *
-PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
-{
- PyObject *code = Py_CompileString(str, "pyscript", start);
- PyObject *ret = nullptr;
-
- if (code != nullptr) {
- ret = PyEval_EvalCode(code, globals, locals);
- }
- Py_XDECREF(code);
- return ret;
-}
-
-#endif // Py_LIMITED_API
-
-// This is only a simple local helper that returns a computed variable.
-// Used also in Python 2.
-#if defined(Py_LIMITED_API) || defined(IS_PY2)
-static PyObject *
-PepRun_GetResult(const char *command)
-{
- PyObject *d, *v, *res;
-
- d = PyDict_New();
- if (d == nullptr
- || PyDict_SetItem(d, Shiboken::PyMagicName::builtins(), PyEval_GetBuiltins()) < 0) {
- return nullptr;
- }
- v = PyRun_String(command, Py_file_input, d, d);
- res = v ? PyDict_GetItem(d, Shiboken::PyName::result()) : nullptr;
- Py_XDECREF(v);
- Py_DECREF(d);
- return res;
-}
-#endif // defined(Py_LIMITED_API) || defined(IS_PY2)
-
-/*****************************************************************************
- *
- * Support for classobject.h
- *
- */
-#ifdef Py_LIMITED_API
-
-PyTypeObject *PepMethod_TypePtr = nullptr;
-
-static PyTypeObject *getMethodType(void)
-{
- static const char prog[] =
- "class _C:\n"
- " def _m(self): pass\n"
- "result = type(_C()._m)\n";
- return reinterpret_cast<PyTypeObject *>(PepRun_GetResult(prog));
-}
-
-// We have no access to PyMethod_New and must call types.MethodType, instead.
-PyObject *
-PyMethod_New(PyObject *func, PyObject *self)
-{
- return PyObject_CallFunction((PyObject *)PepMethod_TypePtr,
- (char *)"(OO)", func, self);
-}
-
-PyObject *
-PyMethod_Function(PyObject *im)
-{
- PyObject *ret = PyObject_GetAttr(im, Shiboken::PyMagicName::func());
-
- // We have to return a borrowed reference.
- Py_DECREF(ret);
- return ret;
-}
-
-PyObject *
-PyMethod_Self(PyObject *im)
-{
- PyObject *ret = PyObject_GetAttr(im, Shiboken::PyMagicName::self());
-
- // We have to return a borrowed reference.
- // If we don't obey that here, then we get a test error!
- Py_DECREF(ret);
- return ret;
-}
-#endif // Py_LIMITED_API
-
-/*****************************************************************************
- *
- * Support for funcobject.h
- *
- */
-#ifdef Py_LIMITED_API
-
-PyObject *
-PepFunction_Get(PyObject *ob, const char *name)
-{
- PyObject *ret;
-
- // We have to return a borrowed reference.
- ret = PyObject_GetAttrString(ob, name);
- Py_XDECREF(ret);
- return ret;
-}
-
-// This became necessary after Windows was activated.
-
-PyTypeObject *PepFunction_TypePtr = nullptr;
-
-static PyTypeObject *getFunctionType(void)
-{
- static const char prog[] =
- "from types import FunctionType as result\n";
- return reinterpret_cast<PyTypeObject *>(PepRun_GetResult(prog));
-}
-#endif // Py_LIMITED_API || Python 2
-
-/*****************************************************************************
- *
- * Support for dictobject.h
- *
- */
-
-// PYSIDE-803, PYSIDE-813: We need that GIL-free version from Python 2.7.12 .
-#ifdef IS_PY2
-
-/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
- This returns NULL *with* an exception set if an exception occurred.
- It returns NULL *without* an exception set if the key wasn't present.
-*/
-PyObject *
-PyDict_GetItemWithError(PyObject *op, PyObject *key)
-{
- long hash;
- PyDictObject *mp = reinterpret_cast<PyDictObject *>(op);
- PyDictEntry *ep;
- if (!PyDict_Check(op)) {
- PyErr_BadInternalCall();
- return nullptr;
- }
- if (!PyString_CheckExact(key) ||
- (hash = (reinterpret_cast<PyStringObject *>(key))->ob_shash) == -1)
- {
- hash = PyObject_Hash(key);
- if (hash == -1) {
- return nullptr;
- }
- }
-
- ep = (mp->ma_lookup)(mp, key, hash);
- if (ep == nullptr) {
- return nullptr;
- }
- return ep->me_value;
-}
-#endif // IS_PY2
-
-/*****************************************************************************
- *
- * Extra support for signature.cpp
- *
- */
-#ifdef Py_LIMITED_API
-
-PyTypeObject *PepStaticMethod_TypePtr = nullptr;
-
-static PyTypeObject *
-getStaticMethodType(void)
-{
- // this works for Python 3, only
- // "StaticMethodType = type(str.__dict__['maketrans'])\n";
- static const char prog[] =
- "from xxsubtype import spamlist\n"
- "result = type(spamlist.__dict__['staticmeth'])\n";
- return reinterpret_cast<PyTypeObject *>(PepRun_GetResult(prog));
-}
-
-typedef struct {
- PyObject_HEAD
- PyObject *sm_callable;
- PyObject *sm_dict;
-} staticmethod;
-
-PyObject *
-PyStaticMethod_New(PyObject *callable)
-{
- staticmethod *sm = (staticmethod *)
- PyType_GenericAlloc(PepStaticMethod_TypePtr, 0);
- if (sm != nullptr) {
- Py_INCREF(callable);
- sm->sm_callable = callable;
- }
- return reinterpret_cast<PyObject *>(sm);
-}
-#endif // Py_LIMITED_API
-
-#ifdef IS_PY2
-PyTypeObject *PepMethodDescr_TypePtr = nullptr;
-
-static PyTypeObject *
-getMethodDescrType(void)
-{
- static const char prog[] =
- "result = type(str.split)\n";
- return reinterpret_cast<PyTypeObject *>(PepRun_GetResult(prog));
-}
-#endif // IS_PY2
-
-/*****************************************************************************
- *
- * Common newly needed functions
- *
- */
-
-// The introduction of heaptypes converted many type names to the
-// dotted form, since PyType_FromSpec uses it to compute the module
-// name. This function reverts this effect.
-const char *
-PepType_GetNameStr(PyTypeObject *type)
-{
- const char *ret = type->tp_name;
- const char *nodots = strrchr(ret, '.');
- if (nodots)
- ret = nodots + 1;
- return ret;
-}
-
-/*****************************************************************************
- *
- * Newly introduced convenience functions
- *
- */
-#if PY_VERSION_HEX < 0x03070000 || defined(Py_LIMITED_API)
-
-PyObject *
-PyImport_GetModule(PyObject *name)
-{
- PyObject *m;
- PyObject *modules = PyImport_GetModuleDict();
- if (modules == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
- return NULL;
- }
- Py_INCREF(modules);
- if (PyDict_CheckExact(modules)) {
- m = PyDict_GetItemWithError(modules, name); /* borrowed */
- Py_XINCREF(m);
- }
- else {
- m = PyObject_GetItem(modules, name);
- if (m == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
- PyErr_Clear();
- }
- }
- Py_DECREF(modules);
- return m;
-}
-
-#endif // PY_VERSION_HEX < 0x03070000 || defined(Py_LIMITED_API)
-/*****************************************************************************
- *
- * Extra support for name mangling
- *
- */
-
-#ifdef Py_LIMITED_API
-// We keep these definitions local, because they don't work in Python 2.
-# define PyUnicode_GET_LENGTH(op) PyUnicode_GetLength((PyObject *)(op))
-# define PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar((PyObject *)(u), (i))
-#endif // Py_LIMITED_API
-
-PyObject *
-_Pep_PrivateMangle(PyObject *self, PyObject *name)
-{
- /*
- * Name mangling: __private becomes _classname__private.
- * This function is modelled after _Py_Mangle, but is optimized
- * a little for our purpose.
- */
-#ifdef IS_PY2
- const char *namestr = PyString_AsString(name);
- if (namestr == nullptr || namestr[0] != '_' || namestr[1] != '_') {
- Py_INCREF(name);
- return name;
- }
- size_t nlen = strlen(namestr);
- /* Don't mangle __id__ or names with dots. */
- if ((namestr[nlen-1] == '_' && namestr[nlen-2] == '_')
- || strchr(namestr, '.')) {
- Py_INCREF(name);
- return name;
- }
-#else
- if (PyUnicode_READ_CHAR(name, 0) != '_' ||
- PyUnicode_READ_CHAR(name, 1) != '_') {
- Py_INCREF(name);
- return name;
- }
- size_t nlen = PyUnicode_GET_LENGTH(name);
- /* Don't mangle __id__ or names with dots. */
- if ((PyUnicode_READ_CHAR(name, nlen-1) == '_' &&
- PyUnicode_READ_CHAR(name, nlen-2) == '_') ||
- PyUnicode_FindChar(name, '.', 0, nlen, 1) != -1) {
- Py_INCREF(name);
- return name;
- }
-#endif // IS_PY2
- Shiboken::AutoDecRef privateobj(PyObject_GetAttr(
- reinterpret_cast<PyObject *>(Py_TYPE(self)), Shiboken::PyMagicName::name()));
-#ifndef Py_LIMITED_API
- return _Py_Mangle(privateobj, name);
-#else
- // For some reason, _Py_Mangle is not in the Limited API. Why?
- size_t plen = PyUnicode_GET_LENGTH(privateobj);
- /* Strip leading underscores from class name */
- size_t ipriv = 0;
- while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
- ipriv++;
- if (ipriv == plen) {
- Py_INCREF(name);
- return name; /* Don't mangle if class is just underscores */
- }
- plen -= ipriv;
-
- if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
- PyErr_SetString(PyExc_OverflowError,
- "private identifier too large to be mangled");
- return nullptr;
- }
- size_t const amount = ipriv + 1 + plen + nlen;
- size_t const big_stack = 1000;
- wchar_t bigbuf[big_stack];
- wchar_t *resbuf = amount <= big_stack ? bigbuf : (wchar_t *)malloc(sizeof(wchar_t) * amount);
- if (!resbuf)
- return 0;
- /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
- resbuf[0] = '_';
- if (PyUnicode_AsWideChar(privateobj, resbuf + 1, ipriv + plen) < 0)
- return 0;
- if (PyUnicode_AsWideChar(name, resbuf + ipriv + plen + 1, nlen) < 0)
- return 0;
- PyObject *result = PyUnicode_FromWideChar(resbuf + ipriv, 1 + plen + nlen);
- if (amount > big_stack)
- free(resbuf);
- return result;
-#endif // else Py_LIMITED_API
-}
-
-/*****************************************************************************
- *
- * Runtime support for Python 3.8 incompatibilities
- *
- */
-
-int PepRuntime_38_flag = 0;
-
-static void
-init_PepRuntime()
-{
- // We expect a string of the form "\d\.\d+\."
- const char *version = Py_GetVersion();
- if (version[0] < '3')
- return;
- if (std::atoi(version + 2) >= 8)
- PepRuntime_38_flag = 1;
-}
-
-/*****************************************************************************
- *
- * Module Initialization
- *
- */
-
-void
-Pep384_Init()
-{
- init_PepRuntime();
-#ifdef Py_LIMITED_API
- check_PyTypeObject_valid();
- Pep_GetVerboseFlag();
- PepMethod_TypePtr = getMethodType();
- PepFunction_TypePtr = getFunctionType();
- PepStaticMethod_TypePtr = getStaticMethodType();
-#endif // Py_LIMITED_API
-
-#ifdef IS_PY2
- PepMethodDescr_TypePtr = getMethodDescrType();
-#endif // IS_PY2
-}
-
-} // extern "C"
diff --git a/sources/shiboken2/libshiboken/pep384impl.h b/sources/shiboken2/libshiboken/pep384impl.h
deleted file mode 100644
index 541b0e775..000000000
--- a/sources/shiboken2/libshiboken/pep384impl.h
+++ /dev/null
@@ -1,557 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PEP384IMPL_H
-#define PEP384IMPL_H
-
-extern "C"
-{
-
-/*****************************************************************************
- *
- * RESOLVED: memoryobject.h
- *
- */
-
-// Extracted into bufferprocs27.h
-#ifdef Py_LIMITED_API
-#include "bufferprocs_py37.h"
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: object.h
- *
- */
-#ifdef Py_LIMITED_API
-// Why the hell is this useful debugging function not allowed?
-// BTW: When used, it breaks on Windows, intentionally!
-LIBSHIBOKEN_API void _PyObject_Dump(PyObject *);
-#endif
-
-/*
- * There are a few structures that are needed, but cannot be used without
- * breaking the API. We use some heuristics to get those fields anyway
- * and validate that we really found them, see pep384impl.cpp .
- */
-
-#ifdef Py_LIMITED_API
-
-/*
- * These are the type object fields that we use.
- * We will verify that they never change.
- * The unused fields are intentionally named as "void *Xnn" because
- * the chance is smaller to forget to validate a field.
- * When we need more fields, we replace it back and add it to the
- * validation.
- */
-typedef struct _typeobject {
- PyVarObject ob_base;
- const char *tp_name;
- Py_ssize_t tp_basicsize;
- void *X03; // Py_ssize_t tp_itemsize;
- destructor tp_dealloc;
- void *X05; // Py_ssize_t tp_vectorcall_offset;
- void *X06; // getattrfunc tp_getattr;
- void *X07; // setattrfunc tp_setattr;
- void *X08; // PyAsyncMethods *tp_as_async;
- reprfunc tp_repr;
- void *X10; // PyNumberMethods *tp_as_number;
- void *X11; // PySequenceMethods *tp_as_sequence;
- void *X12; // PyMappingMethods *tp_as_mapping;
- void *X13; // hashfunc tp_hash;
- ternaryfunc tp_call;
- reprfunc tp_str;
- void *X16; // getattrofunc tp_getattro;
- void *X17; // setattrofunc tp_setattro;
- void *X18; // PyBufferProcs *tp_as_buffer;
- unsigned long tp_flags;
- void *X20; // const char *tp_doc;
- traverseproc tp_traverse;
- inquiry tp_clear;
- void *X23; // richcmpfunc tp_richcompare;
- Py_ssize_t tp_weaklistoffset;
- void *X25; // getiterfunc tp_iter;
- iternextfunc tp_iternext;
- struct PyMethodDef *tp_methods;
- void *X28; // struct PyMemberDef *tp_members;
- struct PyGetSetDef *tp_getset;
- struct _typeobject *tp_base;
- PyObject *tp_dict;
- descrgetfunc tp_descr_get;
- void *X33; // descrsetfunc tp_descr_set;
- Py_ssize_t tp_dictoffset;
- initproc tp_init;
- allocfunc tp_alloc;
- newfunc tp_new;
- freefunc tp_free;
- inquiry tp_is_gc; /* For PyObject_IS_GC */
- PyObject *tp_bases;
- PyObject *tp_mro; /* method resolution order */
-
-} PyTypeObject;
-
-#ifndef PyObject_IS_GC
-/* Test if an object has a GC head */
-#define PyObject_IS_GC(o) \
- (PyType_IS_GC(Py_TYPE(o)) \
- && (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
-#endif
-
-// This was a macro error in the limited API from the beginning.
-// It was fixed in Python master, but did make it only in Python 3.8 .
-#define PY_ISSUE33738_SOLVED 0x03080000
-#if PY_VERSION_HEX < PY_ISSUE33738_SOLVED
-#undef PyIndex_Check
-LIBSHIBOKEN_API int PyIndex_Check(PyObject *obj);
-#endif
-
-#endif // Py_LIMITED_API
-
-struct SbkObjectTypePrivate;
-struct PySideQFlagsTypePrivate;
-struct _SbkGenericTypePrivate;
-
-#define PepHeapType_SIZE \
- (reinterpret_cast<PyTypeObject *>(&PyType_Type)->tp_basicsize)
-
-#define _genericTypeExtender(etype) \
- (reinterpret_cast<char *>(etype) + PepHeapType_SIZE)
-
-#define PepType_SOTP(etype) \
- (*reinterpret_cast<SbkObjectTypePrivate **>(_genericTypeExtender(etype)))
-
-#define PepType_SETP(etype) \
- (reinterpret_cast<SbkEnumTypePrivate *>(_genericTypeExtender(etype)))
-
-#define PepType_PFTP(etype) \
- (reinterpret_cast<PySideQFlagsTypePrivate *>(_genericTypeExtender(etype)))
-
-#define PepType_SGTP(etype) \
- (reinterpret_cast<_SbkGenericTypePrivate *>(_genericTypeExtender(etype)))
-
-// functions used everywhere
-LIBSHIBOKEN_API const char *PepType_GetNameStr(PyTypeObject *type);
-
-/*****************************************************************************
- *
- * RESOLVED: longobject.h
- *
- */
-#ifdef Py_LIMITED_API
-LIBSHIBOKEN_API int _PepLong_AsInt(PyObject *);
-#else
-#define _PepLong_AsInt _PyLong_AsInt
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: pydebug.h
- *
- */
-#ifdef Py_LIMITED_API
-/*
- * We have no direct access to Py_VerboseFlag because debugging is not
- * supported. The python developers are partially a bit too rigorous.
- * Instead, we compute the value and use a function call macro.
- * Was before: extern LIBSHIBOKEN_API int Py_VerboseFlag;
- */
-LIBSHIBOKEN_API int Pep_GetFlag(const char *name);
-LIBSHIBOKEN_API int Pep_GetVerboseFlag(void);
-#define Py_VerboseFlag Pep_GetVerboseFlag()
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: unicodeobject.h
- *
- */
-
-///////////////////////////////////////////////////////////////////////
-//
-// PYSIDE-813: About The Length Of Unicode Objects
-// -----------------------------------------------
-//
-// In Python 2 and before Python 3.3, the macro PyUnicode_GET_SIZE
-// worked fine and really like a macro.
-//
-// Meanwhile, the unicode objects have changed their layout very much,
-// and the former cheap macro call has become a real function call
-// that converts objects and needs PyMemory.
-//
-// That is not only inefficient, but also requires the GIL!
-// This problem was visible by debug Python and qdatastream_test.py .
-// It was found while fixing the refcount problem of PYSIDE-813 which
-// needed a debug Python.
-//
-
-// PyUnicode_GetSize is deprecated in favor of PyUnicode_GetLength.
-#if PY_VERSION_HEX < 0x03000000
-#define PepUnicode_GetLength(op) PyUnicode_GetSize((PyObject *)(op))
-#else
-#define PepUnicode_GetLength(op) PyUnicode_GetLength((PyObject *)(op))
-#endif
-
-#ifdef Py_LIMITED_API
-
-LIBSHIBOKEN_API char *_PepUnicode_AsString(PyObject *);
-
-#else
-#define _PepUnicode_AsString PyUnicode_AsUTF8
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: bytesobject.h
- *
- */
-#ifdef Py_LIMITED_API
-#define PyBytes_AS_STRING(op) PyBytes_AsString(op)
-#define PyBytes_GET_SIZE(op) PyBytes_Size(op)
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: floatobject.h
- *
- */
-#ifdef Py_LIMITED_API
-#define PyFloat_AS_DOUBLE(op) PyFloat_AsDouble(op)
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: tupleobject.h
- *
- */
-#ifdef Py_LIMITED_API
-#define PyTuple_GET_ITEM(op, i) PyTuple_GetItem((PyObject *)op, i)
-#define PyTuple_SET_ITEM(op, i, v) PyTuple_SetItem(op, i, v)
-#define PyTuple_GET_SIZE(op) PyTuple_Size((PyObject *)op)
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: listobject.h
- *
- */
-#ifdef Py_LIMITED_API
-#define PyList_GET_ITEM(op, i) PyList_GetItem(op, i)
-#define PyList_SET_ITEM(op, i, v) PyList_SetItem(op, i, v)
-#define PyList_GET_SIZE(op) PyList_Size(op)
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: dictobject.h
- *
- * PYSIDE-803, PYSIDE-813: We need PyDict_GetItemWithError in order to
- * avoid the GIL.
- */
-#if PY_VERSION_HEX < 0x03000000
-LIBSHIBOKEN_API PyObject *PyDict_GetItemWithError(PyObject *mp, PyObject *key);
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: methodobject.h
- *
- */
-
-#ifdef Py_LIMITED_API
-
-typedef struct _pycfunc PyCFunctionObject;
-#define PyCFunction_GET_FUNCTION(func) PyCFunction_GetFunction((PyObject *)func)
-#define PyCFunction_GET_SELF(func) PyCFunction_GetSelf((PyObject *)func)
-#define PyCFunction_GET_FLAGS(func) PyCFunction_GetFlags((PyObject *)func)
-#define PepCFunction_GET_NAMESTR(func) \
- _PepUnicode_AsString(PyObject_GetAttrString((PyObject *)func, "__name__"))
-#else
-#define PepCFunction_GET_NAMESTR(func) ((func)->m_ml->ml_name)
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: pythonrun.h
- *
- */
-#ifdef Py_LIMITED_API
-LIBSHIBOKEN_API PyObject *PyRun_String(const char *, int, PyObject *, PyObject *);
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: abstract.h
- *
- */
-#ifdef Py_LIMITED_API
-
-// This definition breaks the limited API a little, because it re-enables the
-// buffer functions.
-// But this is no problem as we check it's validity for every version.
-
-#define PYTHON_BUFFER_VERSION_COMPATIBLE (PY_VERSION_HEX >= 0x03030000 && \
- PY_VERSION_HEX < 0x0308FFFF)
-#if !PYTHON_BUFFER_VERSION_COMPATIBLE
-# error Please check the buffer compatibility for this python version!
-#endif
-
-typedef struct {
- getbufferproc bf_getbuffer;
- releasebufferproc bf_releasebuffer;
-} PyBufferProcs;
-
-typedef struct _Pepbuffertype {
- PyVarObject ob_base;
- void *skip[17];
- PyBufferProcs *tp_as_buffer;
-} PepBufferType;
-
-#define PepType_AS_BUFFER(type) \
- reinterpret_cast<PepBufferType *>(type)->tp_as_buffer
-
-#define PyObject_CheckBuffer(obj) \
- ((PepType_AS_BUFFER(Py_TYPE(obj)) != NULL) && \
- (PepType_AS_BUFFER(Py_TYPE(obj))->bf_getbuffer != NULL))
-
-LIBSHIBOKEN_API int PyObject_GetBuffer(PyObject *ob, Pep_buffer *view, int flags);
-LIBSHIBOKEN_API void PyBuffer_Release(Pep_buffer *view);
-
-#else
-
-#define Pep_buffer Py_buffer
-#define PepType_AS_BUFFER(type) ((type)->tp_as_buffer)
-
-#endif /* Py_LIMITED_API */
-
-/*****************************************************************************
- *
- * RESOLVED: funcobject.h
- *
- */
-#ifdef Py_LIMITED_API
-typedef struct _func PyFunctionObject;
-
-extern LIBSHIBOKEN_API PyTypeObject *PepFunction_TypePtr;
-LIBSHIBOKEN_API PyObject *PepFunction_Get(PyObject *, const char *);
-
-#define PyFunction_Check(op) (Py_TYPE(op) == PepFunction_TypePtr)
-#define PyFunction_GET_CODE(func) PyFunction_GetCode(func)
-
-#define PyFunction_GetCode(func) PepFunction_Get((PyObject *)func, "__code__")
-#define PepFunction_GetName(func) PepFunction_Get((PyObject *)func, "__name__")
-#else
-#define PepFunction_TypePtr (&PyFunction_Type)
-#define PepFunction_GetName(func) (((PyFunctionObject *)func)->func_name)
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: classobject.h
- *
- */
-#ifdef Py_LIMITED_API
-
-typedef struct _meth PyMethodObject;
-
-extern LIBSHIBOKEN_API PyTypeObject *PepMethod_TypePtr;
-
-LIBSHIBOKEN_API PyObject *PyMethod_New(PyObject *, PyObject *);
-LIBSHIBOKEN_API PyObject *PyMethod_Function(PyObject *);
-LIBSHIBOKEN_API PyObject *PyMethod_Self(PyObject *);
-
-#define PyMethod_Check(op) ((op)->ob_type == PepMethod_TypePtr)
-
-#define PyMethod_GET_SELF(op) PyMethod_Self(op)
-#define PyMethod_GET_FUNCTION(op) PyMethod_Function(op)
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: code.h
- *
- */
-#ifdef Py_LIMITED_API
-/* Bytecode object */
-
-// we have to grab the code object from python
-typedef struct _code PyCodeObject;
-
-LIBSHIBOKEN_API int PepCode_Get(PyCodeObject *co, const char *name);
-
-#define PepCode_GET_FLAGS(o) PepCode_Get(o, "co_flags")
-#define PepCode_GET_ARGCOUNT(o) PepCode_Get(o, "co_argcount")
-
-/* Masks for co_flags above */
-#define CO_OPTIMIZED 0x0001
-#define CO_NEWLOCALS 0x0002
-#define CO_VARARGS 0x0004
-#define CO_VARKEYWORDS 0x0008
-#define CO_NESTED 0x0010
-#define CO_GENERATOR 0x0020
-#else
-#define PepCode_GET_FLAGS(o) ((o)->co_flags)
-#define PepCode_GET_ARGCOUNT(o) ((o)->co_argcount)
-#endif
-
-/*****************************************************************************
- *
- * RESOLVED: datetime.h
- *
- */
-#ifdef Py_LIMITED_API
-
-LIBSHIBOKEN_API int PyDateTime_Get(PyObject *ob, const char *name);
-
-#define PyDateTime_GetYear(o) PyDateTime_Get(o, "year")
-#define PyDateTime_GetMonth(o) PyDateTime_Get(o, "month")
-#define PyDateTime_GetDay(o) PyDateTime_Get(o, "day")
-#define PyDateTime_GetHour(o) PyDateTime_Get(o, "hour")
-#define PyDateTime_GetMinute(o) PyDateTime_Get(o, "minute")
-#define PyDateTime_GetSecond(o) PyDateTime_Get(o, "second")
-#define PyDateTime_GetMicrosecond(o) PyDateTime_Get(o, "microsecond")
-#define PyDateTime_GetFold(o) PyDateTime_Get(o, "fold")
-
-#define PyDateTime_GET_YEAR(o) PyDateTime_GetYear(o)
-#define PyDateTime_GET_MONTH(o) PyDateTime_GetMonth(o)
-#define PyDateTime_GET_DAY(o) PyDateTime_GetDay(o)
-
-#define PyDateTime_DATE_GET_HOUR(o) PyDateTime_GetHour(o)
-#define PyDateTime_DATE_GET_MINUTE(o) PyDateTime_GetMinute(o)
-#define PyDateTime_DATE_GET_SECOND(o) PyDateTime_GetSecond(o)
-#define PyDateTime_DATE_GET_MICROSECOND(o) PyDateTime_GetMicrosecond(o)
-#define PyDateTime_DATE_GET_FOLD(o) PyDateTime_GetFold(o)
-
-#define PyDateTime_TIME_GET_HOUR(o) PyDateTime_GetHour(o)
-#define PyDateTime_TIME_GET_MINUTE(o) PyDateTime_GetMinute(o)
-#define PyDateTime_TIME_GET_SECOND(o) PyDateTime_GetSecond(o)
-#define PyDateTime_TIME_GET_MICROSECOND(o) PyDateTime_GetMicrosecond(o)
-#define PyDateTime_TIME_GET_FOLD(o) PyDateTime_GetFold(o)
-
-/* Define structure slightly similar to C API. */
-typedef struct {
- PyObject *module;
- /* type objects */
- PyTypeObject *DateType;
- PyTypeObject *DateTimeType;
- PyTypeObject *TimeType;
- PyTypeObject *DeltaType;
- PyTypeObject *TZInfoType;
-} datetime_struc;
-
-LIBSHIBOKEN_API datetime_struc *init_DateTime(void);
-
-#define PyDateTime_IMPORT PyDateTimeAPI = init_DateTime()
-
-extern LIBSHIBOKEN_API datetime_struc *PyDateTimeAPI;
-
-#define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType)
-#define PyDateTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateTimeType)
-#define PyTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->TimeType)
-
-LIBSHIBOKEN_API PyObject *PyDate_FromDate(int year, int month, int day);
-LIBSHIBOKEN_API PyObject *PyDateTime_FromDateAndTime(
- int year, int month, int day, int hour, int min, int sec, int usec);
-LIBSHIBOKEN_API PyObject *PyTime_FromTime(
- int hour, int minute, int second, int usecond);
-
-#endif /* Py_LIMITED_API */
-
-/*****************************************************************************
- *
- * Extra support for name mangling
- *
- */
-
-// PYSIDE-772: This function supports the fix, but is not meant as public.
-LIBSHIBOKEN_API PyObject *_Pep_PrivateMangle(PyObject *self, PyObject *name);
-
-/*****************************************************************************
- *
- * Extra support for signature.cpp
- *
- */
-
-#ifdef Py_LIMITED_API
-extern LIBSHIBOKEN_API PyTypeObject *PepStaticMethod_TypePtr;
-LIBSHIBOKEN_API PyObject *PyStaticMethod_New(PyObject *callable);
-#else
-#define PepStaticMethod_TypePtr &PyStaticMethod_Type
-#endif
-// Although not PEP specific, we resolve this similar issue, here:
-#if PY_VERSION_HEX < 0x03000000
-extern LIBSHIBOKEN_API PyTypeObject *PepMethodDescr_TypePtr;
-#else
-#define PepMethodDescr_TypePtr &PyMethodDescr_Type
-#endif
-
-/*****************************************************************************
- *
- * Newly introduced convenience functions
- *
- * This is not defined if Py_LIMITED_API is defined.
- */
-#if PY_VERSION_HEX < 0x03070000 || defined(Py_LIMITED_API)
-LIBSHIBOKEN_API PyObject *PyImport_GetModule(PyObject *name);
-#endif // PY_VERSION_HEX < 0x03070000 || defined(Py_LIMITED_API)
-
-/*****************************************************************************
- *
- * Runtime support for Python 3.8 incompatibilities
- *
- */
-
-#ifndef Py_TPFLAGS_METHOD_DESCRIPTOR
-/* Objects behave like an unbound method */
-#define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
-#endif
-
-extern LIBSHIBOKEN_API int PepRuntime_38_flag;
-
-/*****************************************************************************
- *
- * Module Initialization
- *
- */
-
-LIBSHIBOKEN_API void Pep384_Init(void);
-
-} // extern "C"
-
-#endif // PEP384IMPL_H
diff --git a/sources/shiboken2/libshiboken/pep384impl_doc.rst b/sources/shiboken2/libshiboken/pep384impl_doc.rst
deleted file mode 100644
index d8ebdbe70..000000000
--- a/sources/shiboken2/libshiboken/pep384impl_doc.rst
+++ /dev/null
@@ -1,721 +0,0 @@
-****************************************
-The Transition To The Limited Python API
-****************************************
-
-
-Foreword
-========
-
-Python supports a limited API that restricts access to certain structures.
-Besides eliminating whole modules and all functions and macros which names
-start with an
-underscore, the most drastic restriction is the removal of normal type object
-declarations.
-
-For details about the eliminated modules and functions, please see the
-`PEP 384`_ page for reference.
-
-
-.. _`PEP 384`: https://www.python.org/dev/peps/pep-0384/
-
-
-
-Changed Modules
-===============
-
-All changed module's include files are listed with the changed functions here.
-As a general rule, it was tried to keep the changes to a minimum diff.
-Macros which are not available were changed to functions with the same name
-if possible. Completely removed names ``Py{name}`` were re-implemented as ``Pep{name}``.
-
-
-memoryobject.h
---------------
-
-The buffer protocol was completely removed. We redefined all the structures
-and methods, because PySide uses that. This is an exception to the limited API
-that we have to check ourselves. The code is extracted in bufferprocs_py37.h .
-This is related to the following:
-
-
-abstract.h
-----------
-
-This belongs to the buffer protocol like memoryobject.h .
-As replacement for ``Py_buffer`` we defined ``Pep_buffer`` and several other
-internal macros.
-
-The version is checked by hand, and the version number must be updated only
-if the implementation does not change. Otherwise, we need to write version
-dependent code paths.
-
-It is questionable if it is worthwhile to continue using the buffer protocol
-or if we should try to get rid of ``Pep_buffer``, completely.
-
-
-longobject.h
-------------
-
-``_PyLong_AsInt`` is not available. We defined a ``_PepLong_AsInt`` function, instead.
-Maybe this should be replaced by ``PyLong_AsLong``.
-
-
-pydebug.h
----------
-
-We have no direct access to ``Py_VerboseFlag`` because debugging is not
-supported. We redefined it as macro ``Py_VerboseFlag`` which calls ``Pep_VerboseFlag``.
-
-
-unicodeobject.h
----------------
-
-The macro ``PyUnicode_GET_SIZE`` was removed and replaced by ``PepUnicode_GetLength``
-which evaluates to ``PyUnicode_GetSize`` for Python 2 and ``PyUnicode_GetLength`` for Python 3.
-Since Python 3.3, ``PyUnicode_GetSize`` would have the bad side effect of requiring the GIL!
-
-Function ``_PyUnicode_AsString`` is unavailable and was replaced by a macro
-that calls ``_PepUnicode_AsString``. The implementation was a bit involved,
-and it would be better to change the code and replace this function.
-
-
-bytesobject.h
--------------
-
-The macros ``PyBytes_AS_STRING`` and ``PyBytes_GET_SIZE`` were redefined to call
-the according functions.
-
-
-floatobject.h
--------------
-
-``PyFloat_AS_DOUBLE`` now calls ``PyFloat_AsDouble``.
-
-
-tupleobject.h
--------------
-
-``PyTuple_GET_ITEM``, ``PyTuple_SET_ITEM`` and ``PyTuple_GET_SIZE`` were redefined as
-function calls.
-
-
-listobject.h
-------------
-
-``PyList_GET_ITEM``, ``PyList_SET_ITEM`` and ``PyList_GET_SIZE`` were redefined as
-function calls.
-
-
-dictobject.h
-------------
-
-``PyDict_GetItem`` also exists in a ``PyDict_GetItemWithError`` version that does
-not suppress errors. This suppression has the side effect of touching global
-structures. This function exists in Python 2 only since Python 2.7.12 and has
-a different name. We simply implemented the function.
-Needed to avoid the GIL when accessing dictionaries.
-
-
-methodobject.h
---------------
-
-``PyCFunction_GET_FUNCTION``, ``PyCFunction_GET_SELF`` and ``PyCFunction_GET_FLAGS``
-were redefined as function calls.
-
-Direct access to the methoddef structure is not available, and we defined
-``PepCFunction_GET_NAMESTR`` as accessor for name strings.
-
-
-pythonrun.h
------------
-
-The simple function ``PyRun_String`` is not available. It was re-implemented
-in a simplified version for the signature module.
-
-
-funcobject.h
-------------
-
-The definitions of funcobject.h are completely missing, although there
-are extra ``#ifdef`` conditional defines inside, too. This suggests that the exclusion
-was unintended.
-
-We therefore redefined ``PyFunctionObject`` as an opaque type.
-
-The missing macro ``PyFunction_Check`` was defined, and the macro
-``PyFunction_GET_CODE`` calls the according function.
-
-There is no equivalent for function name access, therefore we introduced
-``PepFunction_GetName`` either as a function or as a macro.
-
-*TODO: We should fix funcobject.h*
-
-
-classobject.h
--------------
-
-Classobject is also completely not imported, instead of defining an opaque type.
-
-We defined the missing functions ``PyMethod_New``, ``PyMethod_Function`` and
-``PyMethod_Self`` and also redefined ``PyMethod_GET_SELF`` and
-``PyMethod_GET_FUNCTION`` as calls to these functions.
-
-*TODO: We should fix classobject.h*
-
-
-code.h
-------
-
-The whole code.c code is gone, although it may make sense to
-define some minimum accessibility. This will be clarified on
-`Python-Dev`_. We needed access to code objects and defined the missing
-PepCode_GET_FLAGS and PepCode_GET_ARGCOUNT either as function or macro.
-We further added the missing flags, although few are used:
-
-``CO_OPTIMIZED`` ``CO_NEWLOCALS`` ``CO_VARARGS`` ``CO_VARKEYWORDS`` ``CO_NESTED``
-``CO_GENERATOR``
-
-*TODO: We should maybe fix code.h*
-
-.. _`Python-Dev`: https://mail.python.org/mailman/listinfo/python-dev
-
-datetime.h
-----------
-
-The DateTime module is explicitly not included in the limited API.
-We defined all the needed functions but called them via Python instead
-of direct call macros. This has a slight performance impact.
-
-The performance could be easily improved by providing an interface
-that fetches all attributes at once, instead of going through the object
-protocol every time.
-
-The re-defined macros and methods are::
-
- PyDateTime_GET_YEAR
- PyDateTime_GET_MONTH
- PyDateTime_GET_DAY
- PyDateTime_DATE_GET_HOUR
- PyDateTime_DATE_GET_MINUTE
- PyDateTime_DATE_GET_SECOND
- PyDateTime_DATE_GET_MICROSECOND
- PyDateTime_DATE_GET_FOLD
- PyDateTime_TIME_GET_HOUR
- PyDateTime_TIME_GET_MINUTE
- PyDateTime_TIME_GET_SECOND
- PyDateTime_TIME_GET_MICROSECOND
- PyDateTime_TIME_GET_FOLD
-
- PyDate_Check
- PyDateTime_Check
- PyTime_Check
-
- PyDate_FromDate
- PyDateTime_FromDateAndTime
- PyTime_FromTime
-
-*XXX: We should maybe provide an optimized interface to datetime*
-
-
-object.h
---------
-
-The file object.h contains the ``PyTypeObject`` structure, which is supposed
-to be completely opaque. All access to types should be done through
-``PyType_GetSlot`` calls. Due to bugs and deficiencies in the limited API
-implementation, it was not possible to do that. Instead, we have defined
-a simplified structure for ``PyTypeObject`` that has only the fields that
-are used in PySide.
-
-We will explain later why and how this was done. Here is the reduced
-structure::
-
- typedef struct _typeobject {
- PyVarObject ob_base;
- const char *tp_name;
- Py_ssize_t tp_basicsize;
- void *X03; // Py_ssize_t tp_itemsize;
- void *X04; // destructor tp_dealloc;
- void *X05; // printfunc tp_print;
- void *X06; // getattrfunc tp_getattr;
- void *X07; // setattrfunc tp_setattr;
- void *X08; // PyAsyncMethods *tp_as_async;
- void *X09; // reprfunc tp_repr;
- void *X10; // PyNumberMethods *tp_as_number;
- void *X11; // PySequenceMethods *tp_as_sequence;
- void *X12; // PyMappingMethods *tp_as_mapping;
- void *X13; // hashfunc tp_hash;
- ternaryfunc tp_call;
- reprfunc tp_str;
- void *X16; // getattrofunc tp_getattro;
- void *X17; // setattrofunc tp_setattro;
- void *X18; // PyBufferProcs *tp_as_buffer;
- void *X19; // unsigned long tp_flags;
- void *X20; // const char *tp_doc;
- traverseproc tp_traverse;
- inquiry tp_clear;
- void *X23; // richcmpfunc tp_richcompare;
- Py_ssize_t tp_weaklistoffset;
- void *X25; // getiterfunc tp_iter;
- void *X26; // iternextfunc tp_iternext;
- struct PyMethodDef *tp_methods;
- void *X28; // struct PyMemberDef *tp_members;
- void *X29; // struct PyGetSetDef *tp_getset;
- struct _typeobject *tp_base;
- PyObject *tp_dict;
- descrgetfunc tp_descr_get;
- void *X33; // descrsetfunc tp_descr_set;
- Py_ssize_t tp_dictoffset;
- initproc tp_init;
- allocfunc tp_alloc;
- newfunc tp_new;
- freefunc tp_free;
- inquiry tp_is_gc; /* For PyObject_IS_GC */
- PyObject *tp_bases;
- PyObject *tp_mro; /* method resolution order */
- } PyTypeObject;
-
-Function ``PyIndex_Check`` had to be defined in an unwanted way due to
-a Python issue. See file pep384_issue33738.cpp .
-
-There are extension structures which have been isolated as special macros that
-dynamically compute the right offsets of the extended type structures:
-
-* ``PepType_SOTP`` for ``SbkObjectTypePrivate``
-* ``PepType_SETP`` for ``SbkEnumTypePrivate``
-* ``PepType_PFTP`` for ``PySideQFlagsTypePrivate``
-* ``PepType_SGTP`` for ``_SbkGenericTypePrivate``
-
-How these extension structures are used can best be seen by searching
-``PepType_{four}`` in the source.
-
-Due to the new heaptype interface, the names of certain types contain
-now the module name in the ``tp_name`` field. To have a compatible way
-to access simple type names as C string, ``PepType_GetNameStr`` has been
-written that skips over dotted name parts.
-
-Finally, the function ``_PyObject_Dump`` was excluded from the limited API.
-This is a useful debugging aid that we always want to have available,
-so it is added back, again. Anyway, we did not reimplement it, and so
-Windows is not supported.
-Therefore, a forgotten debugging call of this functions will break COIN. :-)
-
-
-Using The New Type API
-======================
-
-After converting everything but the object.h file, we were a little
-bit shocked: it suddenly was clear that we would have no more
-access to type objects, and even more scary that all types which we
-use have to be heap types, only!
-
-For PySide with its intense use of heap type extensions in various
-flavors, the situation looked quite unsolvable. In the end, it was
-nicely solved, but it took almost 3.5 months to get that right.
-
-Before we see how this is done, we will explain the differences
-between the APIs and their consequences.
-
-
-The Interface
--------------
-
-The old type API of Python knows static types and heap types.
-Static types are written down as a declaration of a ``PyTypeObject``
-structure with all its fields filled in. Here is for example
-the definition of the Python type ``object`` (Python 3.6)::
-
- PyTypeObject PyBaseObject_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "object", /* tp_name */
- sizeof(PyObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- object_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- object_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)_Py_HashPointer, /* tp_hash */
- 0, /* tp_call */
- object_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- object_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- object_methods, /* tp_methods */
- 0, /* tp_members */
- object_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- object_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- object_new, /* tp_new */
- PyObject_Del, /* tp_free */
- };
-
-We can write the same structure in form of a ``PyType_Spec`` structure,
-and there is even an incomplete tool *abitype.py* that does this conversion
-for us. With a few corrections, the result looks like this::
-
- static PyType_Slot PyBaseObject_Type_slots[] = {
- {Py_tp_dealloc, (void *)object_dealloc},
- {Py_tp_repr, (void *)object_repr},
- {Py_tp_hash, (void *)_Py_HashPointer},
- {Py_tp_str, (void *)object_str},
- {Py_tp_getattro, (void *)PyObject_GenericGetAttr},
- {Py_tp_setattro, (void *)PyObject_GenericSetAttr},
- {Py_tp_richcompare, (void *)object_richcompare},
- {Py_tp_methods, (void *)object_methods},
- {Py_tp_getset, (void *)object_getsets},
- {Py_tp_init, (void *)object_init},
- {Py_tp_alloc, (void *)PyType_GenericAlloc},
- {Py_tp_new, (void *)object_new},
- {Py_tp_free, (void *)PyObject_Del},
- {0, 0},
- };
- static PyType_Spec PyBaseObject_Type_spec = {
- "object",
- sizeof(PyObject),
- 0,
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- PyBaseObject_Type_slots,
- };
-
-This new structure is almost compatible with the old one, but there
-are some subtle differences.
-
-* The new types are generated in one step
-
-This seems to be no problem, but it was very much, due to the way the
-types were built in PySide. Types were assembled piece by piece, and
-finally the ``PyType_Ready`` function was called.
-
-With the new API, ``PyType_Ready`` is called already at the end of
-``PyType_FromSpec``, and that meant that the logic of type creation became
-completely turned upside down.
-
-* The new types are always heaptypes
-
-With the new type creation functions, it is no longer possible to
-create "normal" types. Instead, they all have to be allocated on the
-heap and garbage collected. The user should normally not recognize this.
-But type creation is more constrained, and you cannot create a subtype
-if the ``Py_TPFLAGS_BASETYPE`` is not set. This constraint was already
-violated by PySide and needed a quite profound fix.
-
-* The new types always need a module
-
-While this is not a problem per se, the above new type spec will not create
-a usable new type, but complain with::
-
- DeprecationWarning: builtin type object has no __module__ attribute
-
-But there are more problems:
-
-* The new types have unexpected defaults
-
-When fields are empty, you would usually assume that they stay empty.
-There are just a few corrections that ``PyType_Ready`` will do to a type.
-
-But there is the following clause in ``PyType_FromSpec`` that can give you
-many headaches::
-
- if (type->tp_dealloc == NULL) {
- /* It's a heap type, so needs the heap types' dealloc.
- subtype_dealloc will call the base type's tp_dealloc, if
- necessary. */
- type->tp_dealloc = subtype_dealloc;
- }
-
-In fact, before the move to the new API, the ``PyType_Ready`` function
-filled empty ``tp_dealloc`` fields with ``object_dealloc``. And the code
-that has been written with that in mind now becomes pretty wrong if suddenly
-``subtype_dealloc`` is used.
-
-The way out was to explicitly provide an ``object_dealloc`` function.
-This would then again impose a problem, because ``object_dealloc`` is not
-public. Writing our own version is easy, but it again needs access to
-type objects. But fortunately, we have broken this rule, already...
-
-
-* The new types are only partially allocated
-
-The structures used in ``PyType_FromSpec`` are almost all allocated,
-only the name field is static. This is no problem for types which are
-statically created once. But if you want to parameterize things and
-create multiple types with a single slots and spec definition, the name
-field that is used for tp_name must be allocated dynamically.
-This is misleading, since all the slots already are copies.
-
-* The new types don't support special offsets
-
-The special fields ``tp_weaklistoffset`` and ``tp_dictoffset`` are not supported
-by ``PyType_FromSpec``. Unfortunately the documentation does not tell you
-if you are allowed to set these fields manually after creating the type or not.
-We finally did it and it worked, but we are not sure about correctness.
-
-See basewrapper.cpp function ``SbkObject_TypeF()`` as the only reference to
-these fields in PySide. This single reference is absolutely necessary and
-very important, since all derived types invisibly inherit these two fields.
-
-
-Future Versions Of The Limited API
-==================================
-
-As we have seen, the current version of the limited API does a bit of
-cheating, because it uses parts of the data structure that should be
-an opaque type. At the moment, this works fine because the data is
-still way more compatible as it could be.
-
-But what if this is changed in the future?
-
-We know that the data structures are stable until Python 3.8 comes out.
-Until then, the small bugs and omissions will hopefully all be solved.
-Then it will be possible to replace the current small tricks by calls
-to ``PyType_GetSlot`` in the way things should be.
-
-At the very moment when the current assumptions about the data structure
-are no longer true, we will rewrite the direct attribute access with
-calls to ``PyType_GetSlot``. After that, no more changes will be necessary.
-
-
-Appendix A: The Transition To Simpler Types
-===========================================
-
-After all code had been converted to the limited API, there was a
-remaining problem with the ``PyHeapTypeObject``.
-
-Why a problem? Well, all the type structures in shiboken use
-special extra fields at the end of the heap type object. This
-currently enforces extra knowledge at compile time about how large the
-heap type object is. In a clean implementation, we would only use
-the ``PyTypeObject`` itself and access the fields *behind* the type
-by a pointer that is computed at runtime.
-
-
-Restricted PyTypeObject
------------------------
-
-Before we are going into details, let us motivate the existence of
-the restricted ``PyTypeObject``:
-
-Originally, we wanted to use ``PyTypeObject`` as an opaque type and
-restrict ourselves to only use the access function ``PyType_GetSlot``.
-This function allows access to all fields which are supported by
-the limited API.
-
-But this is a restriction, because we get no access to ``tp_dict``,
-which we need to support the signature extension. But we can work
-around that.
-
-The real restriction is that ``PyType_GetSlot`` only works for heap
-types. This makes the function quite useless, because we have
-no access to ``PyType_Type``, which is the most important type ``type``
-in Python. We need that for instance to compute the size of
-``PyHeapTypeObject`` dynamically.
-
-With much effort, it is possible to clone ``PyType_Type`` as a heap
-type. But due to a bug in the Pep 384 support, we need
-access to the ``nb_index`` field of a normal type. Cloning does not
-help because ``PyNumberMethods`` fields are *not* inherited.
-
-After we realized this dead end, we changed concept and did not
-use ``PyType_GetSlot`` at all (except in function ``copyNumberMethods``),
-but created a restricted ``PyTypeObject`` with only those fields
-defined that are needed in PySide.
-
-Is this breakage of the limited API? I don't think so. A special
-function runs on program startup that checks the correct position
-of the fields of ``PyTypeObject``, although a change in those fields is
-more than unlikely.
-The really crucial thing is to no longer use ``PyHeapTypeObject``
-explicitly because that *does* change its layout over time.
-
-
-Diversification
----------------
-
-There were multiple ``Sbk{something}`` structures which all used a "d" field
-for their private data. This made it not easy to find the right
-fields when switching between objects and types::
-
- struct LIBSHIBOKEN_API SbkObject
- {
- PyObject_HEAD
- PyObject *ob_dict;
- PyObject *weakreflist;
- SbkObjectPrivate *d;
- };
-
- struct LIBSHIBOKEN_API SbkObjectType
- {
- PyHeapTypeObject super;
- SbkObjectTypePrivate *d;
- };
-
-The first step was to rename the SbkObjectTypePrivate part from "d" to
-"sotp". It was chosen to be short but easy to remember as abbreviation
-of "SbkObjectTypePrivate", leading to::
-
- struct LIBSHIBOKEN_API SbkObjectType
- {
- PyHeapTypeObject super;
- SbkObjectTypePrivate *sotp;
- };
-
-After renaming, it was easier to do the following transformations.
-
-
-Abstraction
------------
-
-After renaming the type extension pointers to ``sotp``, I replaced
-them by function-like macros which did the special access *behind*
-the types, instead of those explicit fields. For instance, the
-expression::
-
- type->sotp->converter
-
-became::
-
- PepType_SOTP(type)->converter
-
-The macro expansion can be seen here::
-
- #define PepHeapType_SIZE \
- (reinterpret_cast<PyTypeObject *>(&PyType_Type)->tp_basicsize)
-
- #define _genericTypeExtender(etype) \
- (reinterpret_cast<char *>(etype) + PepHeapType_SIZE)
-
- #define PepType_SOTP(etype) \
- (*reinterpret_cast<SbkObjectTypePrivate **>(_genericTypeExtender(etype)))
-
-This looks complicated, but in the end there is only a single new
-indirection via ``PyType_Type``, which happens at runtime. This is the
-key to fulfil what Pep 384 wants to achieve: *No more version-dependent fields*.
-
-
-Simplification
---------------
-
-After all type extension fields were replaced by macro calls, we
-could remove the following version dependent re-definition of ``PyHeapTypeObject``
-::
-
- typedef struct _pyheaptypeobject {
- union {
- PyTypeObject ht_type;
- void *opaque[PY_HEAPTYPE_SIZE];
- };
- } PyHeapTypeObject;
-
-, and the version dependent structure::
-
- struct LIBSHIBOKEN_API SbkObjectType
- {
- PyHeapTypeObject super;
- SbkObjectTypePrivate *sotp;
- };
-
-could be replaced by the simplified::
-
- struct LIBSHIBOKEN_API SbkObjectType
- {
- PyTypeObject type;
- };
-
-which is no longer version-dependent.
-Note that we tried to replace the above struct directly by ``PyTypeObject``,
-but that was too much. The distinction between ``SbkObjectType`` and
-``PyTypeObject`` is still needed.
-
-
-Appendix B: Verification Of PyTypeObject
-========================================
-
-We have introduced a limited PyTypeObject in the same place
-as the original PyTypeObject, and now we need to prove that
-we are allowed to do so.
-
-When using the limited API as intended, then types are completely
-opaque, and access is only through ``PyType_FromSpec`` and (from
-version 3.5 upwards) through ``PyType_GetSlot``.
-
-Python then uses all the slot definitions in the type description
-and produces a regular heap type object.
-
-
-Unused Information
-------------------
-
-We know many things about types that are not explicitly said,
-but they are inherently clear:
-
-(a) The basic structure of a type is always the same, regardless
- if it is a static type or a heap type.
-
-(b) types are evolving very slowly, and a field is never replaced
- by another field with different semantics.
-
-Inherent rule (a) gives us the following information: If we calculate
-the offsets of the basic fields, then this info is also usable for non-heap
-types.
-
-The validation checks if rule (b) is still valid.
-
-
-How it Works
-------------
-
-The basic idea of the validation is to produce a new type using
-``PyType_FromSpec`` and to see where in the type structure these fields
-show up. So we build a ``PyType_Slot`` structure with all the fields we
-are using and make sure that these values are all unique in the
-type.
-
-Most fields are not interrogated by ``PyType_FromSpec``, and so we
-simply used some numeric value. Some fields are interpreted, like
-``tp_members``. This field must really be a ``PyMemberDef``. And there are
-``tp_base`` and ``tp_bases`` which have to be type objects and lists
-thereof. It was easiest to not produce these fields from scratch
-but use them from the ``type`` object ``PyType_Type``.
-
-Then one would think to write a function that searches the known
-values in the opaque type structure.
-
-But we can do better and use optimistically the observation (b):
-We simply use the restricted ``PyTypeObject`` structure and assume that
-every field lands exactly where we are awaiting it.
-
-And that is the whole proof: If we find all the disjoint values at
-the places where we expect them, then verification is done.
-
-
-About ``tp_dict``
------------------
-
-One word about the ``tp_dict`` field: This field is a bit special in
-the proof, since it does not appear in the spec and cannot easily
-be checked by ``type.__dict__`` because that creates a *dictproxy*
-object. So how do we prove that is really the right dict?
-
-We have to create that ``PyMethodDef`` structure anyway, and instead of
-leaving it empty, we insert a dummy function. Then we ask the
-``tp_dict`` field if it has the awaited object in it, and that's it!
-
-#EOT
diff --git a/sources/shiboken2/libshiboken/python25compat.h b/sources/shiboken2/libshiboken/python25compat.h
deleted file mode 100644
index b8a4950d9..000000000
--- a/sources/shiboken2/libshiboken/python25compat.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PYTHON25COMPAT_H
-#define PYTHON25COMPAT_H
-#include "sbkpython.h"
-#include <cstring>
-
-/*
- *The #defines below were taken from Cython-generated code to allow shiboken to be used with python2.5.
- * Maybe not all of these defines are useful to us, time will tell which ones are really needed or not.
- */
-
-#if PY_VERSION_HEX < 0x02060000
-#define Py_REFCNT(ob) (((PyObject *)(ob))->ob_refcnt)
-#define Py_TYPE(ob) (((PyObject *)(ob))->ob_type)
-#define Py_SIZE(ob) (((PyVarObject *)(ob))->ob_size)
-#define PyVarObject_HEAD_INIT(type, size) \
- PyObject_HEAD_INIT(type) size,
-#define PyType_Modified(t)
-
-typedef struct {
- void *buf;
- PyObject *obj;
- Py_ssize_t len;
- Py_ssize_t itemsize;
- int readonly;
- int ndim;
- char *format;
- Py_ssize_t *shape;
- Py_ssize_t *strides;
- Py_ssize_t *suboffsets;
- void *internal;
-} Py_buffer;
-
-#define PyBUF_SIMPLE 0
-#define PyBUF_WRITABLE 0x0001
-#define PyBUF_LOCK 0x0002
-#define PyBUF_FORMAT 0x0004
-#define PyBUF_ND 0x0008
-#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
-#define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
-#define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
-#define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
-#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
-
-#define PyBytes_Check PyString_Check
-#define PyBytes_FromString PyString_FromString
-#define PyBytes_FromFormat PyString_FromFormat
-#define PyBytes_FromStringAndSize PyString_FromStringAndSize
-#define PyBytes_GET_SIZE PyString_GET_SIZE
-#define PyBytes_AS_STRING PyString_AS_STRING
-#define PyBytes_AsString PyString_AsString
-#define PyBytes_Concat PyString_Concat
-#define PyBytes_Size PyString_Size
-
-inline PyObject *PyUnicode_FromString(const char *s)
-{
- std::size_t len = std::strlen(s);
- return PyUnicode_DecodeUTF8(s, len, 0);
-}
-
-#define PyLong_FromSize_t _PyLong_FromSize_t
-#define PyLong_AsSsize_t _PyLong_AsSsize_t
-
-#endif
-
-#endif
diff --git a/sources/shiboken2/libshiboken/qapp_macro.cpp b/sources/shiboken2/libshiboken/qapp_macro.cpp
deleted file mode 100644
index 3ef3a51c6..000000000
--- a/sources/shiboken2/libshiboken/qapp_macro.cpp
+++ /dev/null
@@ -1,100 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "basewrapper.h"
-#include "autodecref.h"
-
-extern "C"
-{
-
-#include "qapp_macro.h"
-
-////////////////////////////////////////////////////////////////////////////
-//
-// Support for the qApp macro.
-//
-// qApp is a macro in Qt5. In Python, we simulate that a little by a
-// variable that monitors Q*Application.instance().
-// This variable is also able to destroy the app by qApp.shutdown().
-//
-
-static PyObject *qApp_var = nullptr;
-static PyObject *qApp_content = nullptr;
-
-static PyObject *
-monitor_qApp_var(PyObject *qApp)
-{
- static bool init_done;
- static PyObject *builtins = PyEval_GetBuiltins();
-
- if (!init_done) {
- qApp_var = Py_BuildValue("s", "qApp");
- if (qApp_var == nullptr)
- return nullptr;
- // This is a borrowed reference
- Py_INCREF(builtins);
- init_done = true;
- }
-
- if (PyDict_SetItem(builtins, qApp_var, qApp) < 0)
- return nullptr;
- qApp_content = qApp;
- Py_INCREF(qApp);
- return qApp;
-}
-
-PyObject *
-MakeQAppWrapper(PyTypeObject *type)
-{
- if (type == nullptr)
- type = Py_TYPE(Py_None);
- if (!(type == Py_TYPE(Py_None) || Py_TYPE(qApp_content) == Py_TYPE(Py_None))) {
- const char *res_name = PepType_GetNameStr(Py_TYPE(qApp_content));
- const char *type_name = PepType_GetNameStr(type);
- PyErr_Format(PyExc_RuntimeError, "Please destroy the %s singleton before"
- " creating a new %s instance.", res_name, type_name);
- return nullptr;
- }
- PyObject *self = type != Py_TYPE(Py_None) ? PyObject_New(PyObject, type) : Py_None;
- return monitor_qApp_var(self);
-}
-
-} //extern "C"
-
-// end of module
diff --git a/sources/shiboken2/libshiboken/qapp_macro.h b/sources/shiboken2/libshiboken/qapp_macro.h
deleted file mode 100644
index 9abd17c17..000000000
--- a/sources/shiboken2/libshiboken/qapp_macro.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QAPP_MACRO_H
-#define QAPP_MACRO_H
-
-#include "sbkpython.h"
-
-extern "C"
-{
-
-LIBSHIBOKEN_API PyObject *MakeQAppWrapper(PyTypeObject *type);
-
-} // extern "C"
-
-#endif // QAPP_MACRO_H
diff --git a/sources/shiboken2/libshiboken/qt_attribution.json b/sources/shiboken2/libshiboken/qt_attribution.json
deleted file mode 100644
index 071870780..000000000
--- a/sources/shiboken2/libshiboken/qt_attribution.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "Id": "python",
- "Name": "Python",
- "QDocModule": "QtForPython",
- "QtUsage": "Used for Qt for Python in the signature extension.",
- "Description": "Qt for Python is an add-on for Python. The libshiboken packages of PySide uses certain parts of the source files (typespec.cpp, typespec.h, bufferprocs_py37.cpp, bufferprocs_py37.h). See the folder sources/shiboken2/libshiboken .",
- "Homepage": "http://www.python.org/",
- "Version": "3.7.0",
- "License": "PSF LICENSE AGREEMENT FOR PYTHON 3.7.0",
- "LicenseFile": "bufferprocs_py37.h",
- "Copyright": "© Copyright 2001-2018, Python Software Foundation."
-}
diff --git a/sources/shiboken2/libshiboken/sbkarrayconverter.cpp b/sources/shiboken2/libshiboken/sbkarrayconverter.cpp
deleted file mode 100644
index fd09efdae..000000000
--- a/sources/shiboken2/libshiboken/sbkarrayconverter.cpp
+++ /dev/null
@@ -1,289 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkarrayconverter.h"
-#include "sbkarrayconverter_p.h"
-#include "helper.h"
-#include "sbkconverter.h"
-#include "sbkconverter_p.h"
-
-#include <longobject.h>
-#include <floatobject.h>
-
-#include <algorithm>
-
-static SbkArrayConverter *ArrayTypeConverters[Shiboken::Conversions::SBK_ARRAY_IDX_SIZE] [2] = {};
-
-namespace Shiboken {
-namespace Conversions {
-
-// Check whether Predicate is true for all elements of a sequence
-template <class Predicate>
-static bool sequenceAllOf(PyObject *pyIn, Predicate p)
-{
- const Py_ssize_t size = PySequence_Size(pyIn);
- for (Py_ssize_t i = 0; i < size; ++i) {
- PyObject *item = PySequence_GetItem(pyIn, i);
- const bool ok = p(item);
- Py_XDECREF(item);
- if (!ok)
- return false;
- }
- return true;
-}
-
-// Convert a sequence to output iterator
-template <class T, class Converter>
-inline void convertPySequence(PyObject *pyIn, Converter c, T *out)
-{
- const Py_ssize_t size = PySequence_Size(pyIn);
- for (Py_ssize_t i = 0; i < size; ++i) {
- PyObject *item = PySequence_GetItem(pyIn, i);
- *out++ = c(item);
- Py_XDECREF(item);
- }
-}
-
-// Internal, for usage by numpy
-SbkArrayConverter *createArrayConverter(IsArrayConvertibleToCppFunc toCppCheckFunc)
-{
- auto *result = new SbkArrayConverter;
- result->toCppConversions.push_back(toCppCheckFunc);
- return result;
-}
-
-static PythonToCppFunc unimplementedArrayCheck(PyObject *, int, int)
-{
- warning(PyExc_RuntimeWarning, 0, "SbkConverter: Unimplemented C++ array type.");
- return nullptr;
-}
-
-SbkArrayConverter *unimplementedArrayConverter()
-{
- static SbkArrayConverter *result = createArrayConverter(unimplementedArrayCheck);
- return result;
-}
-
-// Integers
-
-static inline bool intCheck(PyObject *pyIn)
-{
-#ifdef IS_PY3K
- return PyLong_Check(pyIn);
-#else
- return PyInt_Check(pyIn);
-#endif
-}
-
-static short toShort(PyObject *pyIn) { return short(PyLong_AsLong(pyIn)); }
-
-static void sequenceToCppShortArray(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<short> *>(cppOut);
- handle->allocate(PySequence_Size(pyIn));
- convertPySequence(pyIn, toShort, handle->data());
-}
-
-static inline bool sequenceSizeCheck(PyObject *pyIn, int expectedSize = -1)
-{
- if (expectedSize >= 0) {
- const int size = int(PySequence_Size(pyIn));
- if (size < expectedSize) {
- warning(PyExc_RuntimeWarning, 0, "A sequence of size %d was passed to a function that expects %d.",
- size, expectedSize);
- return false;
- }
- }
- return true;
-}
-
-static inline bool intArrayCheck(PyObject *pyIn, int expectedSize = -1)
-{
- return PySequence_Check(pyIn) && sequenceAllOf(pyIn, intCheck)
- && sequenceSizeCheck(pyIn, expectedSize);
-}
-
-static PythonToCppFunc sequenceToCppShortArrayCheck(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return intArrayCheck(pyIn, dim1) ? sequenceToCppShortArray : nullptr;
-}
-
-static short toUnsignedShort(PyObject *pyIn) { return static_cast<unsigned short>(PyLong_AsUnsignedLong(pyIn)); }
-
-static void sequenceToCppUnsignedShortArray(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<unsigned short> *>(cppOut);
- handle->allocate(PySequence_Size(pyIn));
- convertPySequence(pyIn, toUnsignedShort, handle->data());
-}
-
-static PythonToCppFunc sequenceToCppUnsignedShortArrayCheck(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return intArrayCheck(pyIn, dim1) ? sequenceToCppUnsignedShortArray : nullptr;
-}
-
-static void sequenceToCppIntArray(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<int> *>(cppOut);
- handle->allocate(PySequence_Size(pyIn));
- convertPySequence(pyIn, _PepLong_AsInt, handle->data());
-}
-
-static PythonToCppFunc sequenceToCppIntArrayCheck(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return intArrayCheck(pyIn, dim1) ? sequenceToCppIntArray : nullptr;
-}
-
-static void sequenceToCppUnsignedArray(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<unsigned> *>(cppOut);
- handle->allocate(PySequence_Size(pyIn));
- convertPySequence(pyIn, PyLong_AsUnsignedLong, handle->data());
-}
-
-static PythonToCppFunc sequenceToCppUnsignedArrayCheck(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return intArrayCheck(pyIn, dim1) ? sequenceToCppUnsignedArray : nullptr;
-}
-
-static void sequenceToCppLongLongArray(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<long long> *>(cppOut);
- handle->allocate(PySequence_Size(pyIn));
- convertPySequence(pyIn, PyLong_AsLongLong, handle->data());
-}
-
-static PythonToCppFunc sequenceToCppLongLongArrayCheck(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return intArrayCheck(pyIn, dim1) ? sequenceToCppLongLongArray : nullptr;
-}
-
-static void sequenceToCppUnsignedLongLongArray(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<unsigned long long> *>(cppOut);
- handle->allocate(PySequence_Size(pyIn));
- convertPySequence(pyIn, PyLong_AsUnsignedLongLong, handle->data());
-}
-
-static PythonToCppFunc sequenceToCppUnsignedLongLongArrayCheck(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return intArrayCheck(pyIn, dim1) ? sequenceToCppUnsignedLongLongArray : nullptr;
-}
-
-// Float
-
-static inline bool floatCheck(PyObject *pyIn) { return PyFloat_Check(pyIn); }
-
-static inline bool floatArrayCheck(PyObject *pyIn, int expectedSize = -1)
-{
- return PySequence_Check(pyIn) && sequenceAllOf(pyIn, floatCheck)
- && sequenceSizeCheck(pyIn, expectedSize);
-}
-
-static void sequenceToCppDoubleArray(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<double> *>(cppOut);
- handle->allocate(PySequence_Size(pyIn));
- convertPySequence(pyIn, PyFloat_AsDouble, handle->data());
-}
-
-static inline float pyToFloat(PyObject *pyIn) { return float(PyFloat_AsDouble(pyIn)); }
-
-static void sequenceToCppFloatArray(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<float> *>(cppOut);
- handle->allocate(PySequence_Size(pyIn));
- convertPySequence(pyIn, pyToFloat, handle->data());
-}
-
-static PythonToCppFunc sequenceToCppFloatArrayCheck(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return floatArrayCheck(pyIn, dim1) ? sequenceToCppFloatArray : nullptr;
-}
-
-static PythonToCppFunc sequenceToCppDoubleArrayCheck(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return floatArrayCheck(pyIn, dim1) ? sequenceToCppDoubleArray : nullptr;
-}
-
-#ifdef HAVE_NUMPY
-void initNumPyArrayConverters();
-#endif
-
-void initArrayConverters()
-{
- SbkArrayConverter **start = &ArrayTypeConverters[0][0];
- std::fill(start, start + sizeof(ArrayTypeConverters) / sizeof(ArrayTypeConverters[0][0]), nullptr);
- // Populate 1-dimensional sequence converters
- ArrayTypeConverters[SBK_DOUBLE_ARRAY_IDX][0] =
- createArrayConverter(sequenceToCppDoubleArrayCheck);
- ArrayTypeConverters[SBK_FLOAT_ARRAY_IDX][0] =
- createArrayConverter(sequenceToCppFloatArrayCheck);
- ArrayTypeConverters[SBK_SHORT_ARRAY_IDX][0] =
- createArrayConverter(sequenceToCppShortArrayCheck);
- ArrayTypeConverters[SBK_UNSIGNEDSHORT_ARRAY_IDX][0] =
- createArrayConverter(sequenceToCppUnsignedShortArrayCheck);
- ArrayTypeConverters[SBK_INT_ARRAY_IDX][0] =
- createArrayConverter(sequenceToCppIntArrayCheck);
- ArrayTypeConverters[SBK_UNSIGNEDINT_ARRAY_IDX][0] =
- createArrayConverter(sequenceToCppUnsignedArrayCheck);
- ArrayTypeConverters[SBK_LONGLONG_ARRAY_IDX][0] =
- createArrayConverter(sequenceToCppLongLongArrayCheck);
- ArrayTypeConverters[SBK_UNSIGNEDLONGLONG_ARRAY_IDX][0] =
- createArrayConverter(sequenceToCppUnsignedLongLongArrayCheck);
-
-#ifdef HAVE_NUMPY
- initNumPyArrayConverters();
-#endif
-}
-
-SbkArrayConverter *arrayTypeConverter(int index, int dimension)
-{
- SbkArrayConverter *c = ArrayTypeConverters[index][dimension - 1];
- return c ? c : unimplementedArrayConverter();
-}
-
-// Internal, for usage by numpy
-void setArrayTypeConverter(int index, int dimension, SbkArrayConverter *c)
-{
- ArrayTypeConverters[index][dimension - 1] = c;
-}
-
-} // namespace Conversions
-} // namespace Shiboken
diff --git a/sources/shiboken2/libshiboken/sbkarrayconverter.h b/sources/shiboken2/libshiboken/sbkarrayconverter.h
deleted file mode 100644
index 84cb2f57f..000000000
--- a/sources/shiboken2/libshiboken/sbkarrayconverter.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKARRAYCONVERTERS_H
-#define SBKARRAYCONVERTERS_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-extern "C" {
-struct SbkArrayConverter;
-}
-
-namespace Shiboken {
-namespace Conversions {
-
-enum : int {
- SBK_UNIMPLEMENTED_ARRAY_IDX,
- SBK_DOUBLE_ARRAY_IDX,
- SBK_FLOAT_ARRAY_IDX,
- SBK_SHORT_ARRAY_IDX,
- SBK_UNSIGNEDSHORT_ARRAY_IDX,
- SBK_INT_ARRAY_IDX,
- SBK_UNSIGNEDINT_ARRAY_IDX,
- SBK_LONGLONG_ARRAY_IDX,
- SBK_UNSIGNEDLONGLONG_ARRAY_IDX,
- SBK_ARRAY_IDX_SIZE
-};
-
-/**
- * ArrayHandle is the type expected by shiboken2's array converter
- * functions. It provides access to array data which it may own
- * (in the case of conversions from PySequence) or a flat pointer
- * to internal data (in the case of array modules like numpy).
- */
-
-template <class T>
-class ArrayHandle
-{
-public:
- ArrayHandle(const ArrayHandle &) = delete;
- ArrayHandle& operator=(const ArrayHandle &) = delete;
- ArrayHandle(ArrayHandle &&) = delete;
- ArrayHandle& operator=(ArrayHandle &&) = delete;
-
- ArrayHandle() = default;
- ~ArrayHandle() { destroy(); }
-
- void allocate(Py_ssize_t size);
- void setData(T *d, size_t size);
-
- size_t size() const { return m_size; }
- T *data() const { return m_data; }
- operator T *() const { return m_data; }
-
-private:
- void destroy();
-
- T *m_data = nullptr;
- Py_ssize_t m_size = 0;
- bool m_owned = false;
-};
-
-/**
- * Similar to ArrayHandle for fixed size 2 dimensional arrays.
- * columns is the size of the last dimension
- * It only has a setData() methods since it will be used for numpy only.
- */
-
-template <class T, int columns>
-class Array2Handle
-{
-public:
- typedef T RowType[columns];
-
- Array2Handle() = default;
-
- operator RowType *() const { return m_rows; }
-
- void setData(RowType *d) { m_rows = d; }
-
-private:
- RowType *m_rows = nullptr;
-};
-
-/// Returns the converter for an array type.
-LIBSHIBOKEN_API SbkArrayConverter *arrayTypeConverter(int index, int dimension = 1);
-
-template <class T>
-struct ArrayTypeIndex{
- enum : int { index = SBK_UNIMPLEMENTED_ARRAY_IDX };
-};
-
-template <> struct ArrayTypeIndex<double> { enum : int { index = SBK_DOUBLE_ARRAY_IDX }; };
-template <> struct ArrayTypeIndex<float> { enum : int { index = SBK_FLOAT_ARRAY_IDX };};
-template <> struct ArrayTypeIndex<short> { enum : int { index = SBK_SHORT_ARRAY_IDX };};
-template <> struct ArrayTypeIndex<unsigned short> { enum : int { index = SBK_UNSIGNEDSHORT_ARRAY_IDX };};
-template <> struct ArrayTypeIndex<int> { enum : int { index = SBK_INT_ARRAY_IDX };};
-template <> struct ArrayTypeIndex<unsigned> { enum : int { index = SBK_UNSIGNEDINT_ARRAY_IDX };};
-template <> struct ArrayTypeIndex<long long> { enum : int { index = SBK_LONGLONG_ARRAY_IDX };};
-template <> struct ArrayTypeIndex<unsigned long long> { enum : int { index = SBK_UNSIGNEDLONGLONG_ARRAY_IDX };};
-
-template<typename T> SbkArrayConverter *ArrayTypeConverter(int dimension)
-{ return arrayTypeConverter(ArrayTypeIndex<T>::index, dimension); }
-
-// ArrayHandle methods
-template<class T>
-void ArrayHandle<T>::allocate(Py_ssize_t size)
-{
- destroy();
- m_data = new T[size];
- m_size = size;
- m_owned = true;
-}
-
-template<class T>
-void ArrayHandle<T>::setData(T *d, size_t size)
-{
- destroy();
- m_data = d;
- m_size = size;
- m_owned = false;
-}
-
-template<class T>
-void ArrayHandle<T>::destroy()
-{
- if (m_owned)
- delete [] m_data;
- m_data = nullptr;
- m_size = 0;
- m_owned = false;
-}
-
-} // namespace Conversions
-} // namespace Shiboken
-
-#endif // SBKARRAYCONVERTERS_H
diff --git a/sources/shiboken2/libshiboken/sbkarrayconverter_p.h b/sources/shiboken2/libshiboken/sbkarrayconverter_p.h
deleted file mode 100644
index a7b46702b..000000000
--- a/sources/shiboken2/libshiboken/sbkarrayconverter_p.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKARRAYCONVERTER_P_H
-#define SBKARRAYCONVERTER_P_H
-
-#include "sbkconverter_p.h"
-#include <vector>
-
-extern "C"
-{
-
-typedef PythonToCppFunc (*IsArrayConvertibleToCppFunc)(PyObject *, int dim1, int dim2);
-/**
- * \internal
- * Private structure of SbkArrayConverter.
- */
-
-struct SbkArrayConverter
-{
- std::vector<IsArrayConvertibleToCppFunc> toCppConversions;
-};
-
-} // extern "C"
-
-#endif // SBKARRAYCONVERTER_P_H
diff --git a/sources/shiboken2/libshiboken/sbkconverter.cpp b/sources/shiboken2/libshiboken/sbkconverter.cpp
deleted file mode 100644
index 29eb19715..000000000
--- a/sources/shiboken2/libshiboken/sbkconverter.cpp
+++ /dev/null
@@ -1,597 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkconverter.h"
-#include "sbkconverter_p.h"
-#include "sbkarrayconverter_p.h"
-#include "basewrapper_p.h"
-#include "bindingmanager.h"
-#include "autodecref.h"
-#include "sbkdbg.h"
-#include "helper.h"
-#include "voidptr.h"
-
-#include <unordered_map>
-
-static SbkConverter **PrimitiveTypeConverters;
-
-using ConvertersMap = std::unordered_map<std::string, SbkConverter *>;
-static ConvertersMap converters;
-
-namespace Shiboken {
-namespace Conversions {
-
-void initArrayConverters();
-
-void init()
-{
- static SbkConverter *primitiveTypeConverters[] = {
- Primitive<PY_LONG_LONG>::createConverter(),
- Primitive<bool>::createConverter(),
- Primitive<char>::createConverter(),
- Primitive<const char *>::createConverter(),
- Primitive<double>::createConverter(),
- Primitive<float>::createConverter(),
- Primitive<int>::createConverter(),
- Primitive<long>::createConverter(),
- Primitive<short>::createConverter(),
- Primitive<signed char>::createConverter(),
- Primitive<std::string>::createConverter(),
- Primitive<unsigned PY_LONG_LONG>::createConverter(),
- Primitive<unsigned char>::createConverter(),
- Primitive<unsigned int>::createConverter(),
- Primitive<unsigned long>::createConverter(),
- Primitive<unsigned short>::createConverter(),
- VoidPtr::createConverter(),
- Primitive<std::nullptr_t>::createConverter()
- };
- PrimitiveTypeConverters = primitiveTypeConverters;
-
- assert(converters.empty());
- converters["PY_LONG_LONG"] = primitiveTypeConverters[SBK_PY_LONG_LONG_IDX];
- converters["bool"] = primitiveTypeConverters[SBK_BOOL_IDX_1];
- converters["char"] = primitiveTypeConverters[SBK_CHAR_IDX];
- converters["const char *"] = primitiveTypeConverters[SBK_CONSTCHARPTR_IDX];
- converters["double"] = primitiveTypeConverters[SBK_DOUBLE_IDX];
- converters["float"] = primitiveTypeConverters[SBK_FLOAT_IDX];
- converters["int"] = primitiveTypeConverters[SBK_INT_IDX];
- converters["long"] = primitiveTypeConverters[SBK_LONG_IDX];
- converters["short"] = primitiveTypeConverters[SBK_SHORT_IDX];
- converters["signed char"] = primitiveTypeConverters[SBK_SIGNEDCHAR_IDX];
- converters["std::string"] = primitiveTypeConverters[SBK_STD_STRING_IDX];
- converters["unsigned PY_LONG_LONG"] = primitiveTypeConverters[SBK_UNSIGNEDPY_LONG_LONG_IDX];
- converters["unsigned char"] = primitiveTypeConverters[SBK_UNSIGNEDCHAR_IDX];
- converters["unsigned int"] = primitiveTypeConverters[SBK_UNSIGNEDINT_IDX];
- converters["unsigned long"] = primitiveTypeConverters[SBK_UNSIGNEDLONG_IDX];
- converters["unsigned short"] = primitiveTypeConverters[SBK_UNSIGNEDSHORT_IDX];
- converters["void*"] = primitiveTypeConverters[SBK_VOIDPTR_IDX];
- converters["std::nullptr_t"] = primitiveTypeConverters[SBK_NULLPTR_T_IDX];
-
- initArrayConverters();
-}
-
-SbkConverter *createConverterObject(PyTypeObject *type,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc,
- CppToPythonFunc pointerToPythonFunc,
- CppToPythonFunc copyToPythonFunc)
-{
- auto converter = new SbkConverter;
- converter->pythonType = type;
- // PYSIDE-595: All types are heaptypes now, so provide reference.
- Py_XINCREF(type);
-
- converter->pointerToPython = pointerToPythonFunc;
- converter->copyToPython = copyToPythonFunc;
-
- if (toCppPointerCheckFunc && toCppPointerConvFunc)
- converter->toCppPointerConversion = std::make_pair(toCppPointerCheckFunc, toCppPointerConvFunc);
- converter->toCppConversions.clear();
-
- return converter;
-}
-
-SbkConverter *createConverter(SbkObjectType *type,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc,
- CppToPythonFunc pointerToPythonFunc,
- CppToPythonFunc copyToPythonFunc)
-{
- SbkConverter *converter =
- createConverterObject(reinterpret_cast<PyTypeObject *>(type),
- toCppPointerConvFunc, toCppPointerCheckFunc,
- pointerToPythonFunc, copyToPythonFunc);
- PepType_SOTP(type)->converter = converter;
- return converter;
-}
-
-SbkConverter *createConverter(PyTypeObject *type, CppToPythonFunc toPythonFunc)
-{
- return createConverterObject(type, nullptr, nullptr, nullptr, toPythonFunc);
-}
-
-void deleteConverter(SbkConverter *converter)
-{
- if (converter) {
- converter->toCppConversions.clear();
- delete converter;
- }
-}
-
-void setCppPointerToPythonFunction(SbkConverter *converter, CppToPythonFunc pointerToPythonFunc)
-{
- converter->pointerToPython = pointerToPythonFunc;
-}
-
-void setPythonToCppPointerFunctions(SbkConverter *converter,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc)
-{
- converter->toCppPointerConversion = std::make_pair(toCppPointerCheckFunc, toCppPointerConvFunc);
-}
-
-void addPythonToCppValueConversion(SbkConverter *converter,
- PythonToCppFunc pythonToCppFunc,
- IsConvertibleToCppFunc isConvertibleToCppFunc)
-{
- converter->toCppConversions.push_back(std::make_pair(isConvertibleToCppFunc, pythonToCppFunc));
-}
-void addPythonToCppValueConversion(SbkObjectType *type,
- PythonToCppFunc pythonToCppFunc,
- IsConvertibleToCppFunc isConvertibleToCppFunc)
-{
- addPythonToCppValueConversion(PepType_SOTP(type)->converter, pythonToCppFunc, isConvertibleToCppFunc);
-}
-
-PyObject *pointerToPython(SbkObjectType *type, const void *cppIn)
-{
- return pointerToPython(PepType_SOTP(type)->converter, cppIn);
-}
-
-PyObject *pointerToPython(const SbkConverter *converter, const void *cppIn)
-{
- assert(converter);
- if (!cppIn)
- Py_RETURN_NONE;
- if (!converter->pointerToPython) {
- warning(PyExc_RuntimeWarning, 0, "pointerToPython(): SbkConverter::pointerToPython is null for \"%s\".",
- converter->pythonType->tp_name);
- Py_RETURN_NONE;
- }
- return converter->pointerToPython(cppIn);
-}
-
-PyObject *referenceToPython(SbkObjectType *type, const void *cppIn)
-{
- return referenceToPython(PepType_SOTP(type)->converter, cppIn);
-}
-
-PyObject *referenceToPython(const SbkConverter *converter, const void *cppIn)
-{
- assert(cppIn);
-
- auto *pyOut = reinterpret_cast<PyObject *>(BindingManager::instance().retrieveWrapper(cppIn));
- if (pyOut) {
- Py_INCREF(pyOut);
- return pyOut;
- }
- if (!converter->pointerToPython) {
- warning(PyExc_RuntimeWarning, 0, "referenceToPython(): SbkConverter::pointerToPython is null for \"%s\".",
- converter->pythonType->tp_name);
- Py_RETURN_NONE;
- }
- return converter->pointerToPython(cppIn);
-}
-
-static inline PyObject *CopyCppToPython(const SbkConverter *converter, const void *cppIn)
-{
- if (!cppIn)
- Py_RETURN_NONE;
- if (!converter->copyToPython) {
- warning(PyExc_RuntimeWarning, 0, "CopyCppToPython(): SbkConverter::copyToPython is null for \"%s\".",
- converter->pythonType->tp_name);
- Py_RETURN_NONE;
- }
- return converter->copyToPython(cppIn);
-}
-PyObject *copyToPython(SbkObjectType *type, const void *cppIn)
-{
- return CopyCppToPython(PepType_SOTP(type)->converter, cppIn);
-}
-PyObject *copyToPython(const SbkConverter *converter, const void *cppIn)
-{
- return CopyCppToPython(converter, cppIn);
-}
-
-PythonToCppFunc isPythonToCppPointerConvertible(SbkObjectType *type, PyObject *pyIn)
-{
- assert(pyIn);
- return PepType_SOTP(type)->converter->toCppPointerConversion.first(pyIn);
-}
-
-static inline PythonToCppFunc IsPythonToCppConvertible(const SbkConverter *converter, PyObject *pyIn)
-{
- assert(pyIn);
- for (const ToCppConversion &c : converter->toCppConversions) {
- if (PythonToCppFunc toCppFunc = c.first(pyIn))
- return toCppFunc;
- }
- return nullptr;
-}
-PythonToCppFunc isPythonToCppValueConvertible(SbkObjectType *type, PyObject *pyIn)
-{
- return IsPythonToCppConvertible(PepType_SOTP(type)->converter, pyIn);
-}
-PythonToCppFunc isPythonToCppConvertible(const SbkConverter *converter, PyObject *pyIn)
-{
- return IsPythonToCppConvertible(converter, pyIn);
-}
-
-PythonToCppFunc isPythonToCppConvertible(const SbkArrayConverter *converter,
- int dim1, int dim2, PyObject *pyIn)
-{
- assert(pyIn);
- for (IsArrayConvertibleToCppFunc f : converter->toCppConversions) {
- if (PythonToCppFunc c = f(pyIn, dim1, dim2))
- return c;
- }
- return nullptr;
-}
-
-PythonToCppFunc isPythonToCppReferenceConvertible(SbkObjectType *type, PyObject *pyIn)
-{
- if (pyIn != Py_None) {
- PythonToCppFunc toCpp = isPythonToCppPointerConvertible(type, pyIn);
- if (toCpp)
- return toCpp;
- }
- return isPythonToCppValueConvertible(type, pyIn);
-}
-
-void nonePythonToCppNullPtr(PyObject *, void *cppOut)
-{
- assert(cppOut);
- *static_cast<void **>(cppOut) = nullptr;
-}
-
-void *cppPointer(PyTypeObject *desiredType, SbkObject *pyIn)
-{
- assert(pyIn);
- if (!ObjectType::checkType(desiredType))
- return pyIn;
- auto *inType = reinterpret_cast<SbkObjectType *>(Py_TYPE(pyIn));
- if (ObjectType::hasCast(inType))
- return ObjectType::cast(inType, pyIn, desiredType);
- return Object::cppPointer(pyIn, desiredType);
-}
-
-void pythonToCppPointer(SbkObjectType *type, PyObject *pyIn, void *cppOut)
-{
- assert(type);
- assert(pyIn);
- assert(cppOut);
- *reinterpret_cast<void **>(cppOut) = pyIn == Py_None
- ? nullptr
- : cppPointer(reinterpret_cast<PyTypeObject *>(type), reinterpret_cast<SbkObject *>(pyIn));
-}
-
-void pythonToCppPointer(const SbkConverter *converter, PyObject *pyIn, void *cppOut)
-{
- assert(converter);
- assert(pyIn);
- assert(cppOut);
- *reinterpret_cast<void **>(cppOut) = pyIn == Py_None
- ? nullptr
- : cppPointer(reinterpret_cast<PyTypeObject *>(converter->pythonType), reinterpret_cast<SbkObject *>(pyIn));
-}
-
-static void _pythonToCppCopy(const SbkConverter *converter, PyObject *pyIn, void *cppOut)
-{
- assert(converter);
- assert(pyIn);
- assert(cppOut);
- PythonToCppFunc toCpp = IsPythonToCppConvertible(converter, pyIn);
- if (toCpp)
- toCpp(pyIn, cppOut);
-}
-
-void pythonToCppCopy(SbkObjectType *type, PyObject *pyIn, void *cppOut)
-{
- assert(type);
- _pythonToCppCopy(PepType_SOTP(type)->converter, pyIn, cppOut);
-}
-
-void pythonToCppCopy(const SbkConverter *converter, PyObject *pyIn, void *cppOut)
-{
- _pythonToCppCopy(converter, pyIn, cppOut);
-}
-
-bool isImplicitConversion(SbkObjectType *type, PythonToCppFunc toCppFunc)
-{
- // This is the Object Type or Value Type conversion that only
- // retrieves the C++ pointer held in the Python wrapper.
- if (toCppFunc == PepType_SOTP(type)->converter->toCppPointerConversion.second)
- return false;
-
- // Object Types doesn't have any kind of value conversion,
- // only C++ pointer retrieval.
- if (PepType_SOTP(type)->converter->toCppConversions.empty())
- return false;
-
- // The first conversion of the non-pointer conversion list is
- // a Value Type's copy to C++ function, which is not an implicit
- // conversion.
- // Otherwise it must be one of the implicit conversions.
- // Note that we don't check if the Python to C++ conversion is in
- // the list of the type's conversions, for it is expected that the
- // caller knows what he's doing.
- const auto conv = PepType_SOTP(type)->converter->toCppConversions.cbegin();
- return toCppFunc != (*conv).second;
-}
-
-void registerConverterName(SbkConverter *converter , const char *typeName)
-{
- auto iter = converters.find(typeName);
- if (iter == converters.end())
- converters.insert(std::make_pair(typeName, converter));
-}
-
-SbkConverter *getConverter(const char *typeName)
-{
- ConvertersMap::const_iterator it = converters.find(typeName);
- if (it != converters.end())
- return it->second;
- if (Py_VerboseFlag > 0)
- SbkDbg() << "Can't find type resolver for type '" << typeName << "'.";
- return nullptr;
-}
-
-SbkConverter *primitiveTypeConverter(int index)
-{
- return PrimitiveTypeConverters[index];
-}
-
-bool checkSequenceTypes(PyTypeObject *type, PyObject *pyIn)
-{
- assert(type);
- assert(pyIn);
- if (PySequence_Size(pyIn) < 0) {
- // clear the error if < 0 which means no length at all
- PyErr_Clear();
- return false;
- }
- const Py_ssize_t size = PySequence_Size(pyIn);
- for (Py_ssize_t i = 0; i < size; ++i) {
- if (!PyObject_TypeCheck(AutoDecRef(PySequence_GetItem(pyIn, i)), type))
- return false;
- }
- return true;
-}
-bool convertibleSequenceTypes(const SbkConverter *converter, PyObject *pyIn)
-{
- assert(converter);
- assert(pyIn);
- if (!PySequence_Check(pyIn))
- return false;
- const Py_ssize_t size = PySequence_Size(pyIn);
- for (Py_ssize_t i = 0; i < size; ++i) {
- if (!isPythonToCppConvertible(converter, AutoDecRef(PySequence_GetItem(pyIn, i))))
- return false;
- }
- return true;
-}
-bool convertibleSequenceTypes(SbkObjectType *type, PyObject *pyIn)
-{
- assert(type);
- return convertibleSequenceTypes(PepType_SOTP(type)->converter, pyIn);
-}
-
-bool checkPairTypes(PyTypeObject *firstType, PyTypeObject *secondType, PyObject *pyIn)
-{
- assert(firstType);
- assert(secondType);
- assert(pyIn);
- if (!PySequence_Check(pyIn))
- return false;
- if (PySequence_Size(pyIn) != 2)
- return false;
- if (!PyObject_TypeCheck(AutoDecRef(PySequence_GetItem(pyIn, 0)), firstType))
- return false;
- if (!PyObject_TypeCheck(AutoDecRef(PySequence_GetItem(pyIn, 1)), secondType))
- return false;
- return true;
-}
-bool convertiblePairTypes(const SbkConverter *firstConverter, bool firstCheckExact,
- const SbkConverter *secondConverter, bool secondCheckExact,
- PyObject *pyIn)
-{
- assert(firstConverter);
- assert(secondConverter);
- assert(pyIn);
- if (!PySequence_Check(pyIn))
- return false;
- if (PySequence_Size(pyIn) != 2)
- return false;
- AutoDecRef firstItem(PySequence_GetItem(pyIn, 0));
- if (firstCheckExact) {
- if (!PyObject_TypeCheck(firstItem, firstConverter->pythonType))
- return false;
- } else if (!isPythonToCppConvertible(firstConverter, firstItem)) {
- return false;
- }
- AutoDecRef secondItem(PySequence_GetItem(pyIn, 1));
- if (secondCheckExact) {
- if (!PyObject_TypeCheck(secondItem, secondConverter->pythonType))
- return false;
- } else if (!isPythonToCppConvertible(secondConverter, secondItem)) {
- return false;
- }
-
- return true;
-}
-
-bool checkDictTypes(PyTypeObject *keyType, PyTypeObject *valueType, PyObject *pyIn)
-{
- assert(keyType);
- assert(valueType);
- assert(pyIn);
- if (!PyDict_Check(pyIn))
- return false;
-
- PyObject *key;
- PyObject *value;
- Py_ssize_t pos = 0;
- while (PyDict_Next(pyIn, &pos, &key, &value)) {
- if (!PyObject_TypeCheck(key, keyType))
- return false;
- if (!PyObject_TypeCheck(value, valueType))
- return false;
- }
- return true;
-}
-
-bool convertibleDictTypes(const SbkConverter *keyConverter, bool keyCheckExact, const SbkConverter *valueConverter,
- bool valueCheckExact, PyObject *pyIn)
-{
- assert(keyConverter);
- assert(valueConverter);
- assert(pyIn);
- if (!PyDict_Check(pyIn))
- return false;
- PyObject *key;
- PyObject *value;
- Py_ssize_t pos = 0;
- while (PyDict_Next(pyIn, &pos, &key, &value)) {
- if (keyCheckExact) {
- if (!PyObject_TypeCheck(key, keyConverter->pythonType))
- return false;
- } else if (!isPythonToCppConvertible(keyConverter, key)) {
- return false;
- }
- if (valueCheckExact) {
- if (!PyObject_TypeCheck(value, valueConverter->pythonType))
- return false;
- } else if (!isPythonToCppConvertible(valueConverter, value)) {
- return false;
- }
- }
- return true;
-}
-
-PyTypeObject *getPythonTypeObject(const SbkConverter *converter)
-{
- if (converter)
- return converter->pythonType;
- return nullptr;
-}
-
-PyTypeObject *getPythonTypeObject(const char *typeName)
-{
- return getPythonTypeObject(getConverter(typeName));
-}
-
-bool pythonTypeIsValueType(const SbkConverter *converter)
-{
- // Unlikely to happen but for multi-inheritance SbkObjs
- // the converter is not defined, hence we need a default return.
- if (!converter)
- return false;
- return converter->pointerToPython && converter->copyToPython;
-}
-
-bool pythonTypeIsObjectType(const SbkConverter *converter)
-{
- return converter->pointerToPython && !converter->copyToPython;
-}
-
-bool pythonTypeIsWrapperType(const SbkConverter *converter)
-{
- return converter->pointerToPython != nullptr;
-}
-
-SpecificConverter::SpecificConverter(const char *typeName)
- : m_type(InvalidConversion)
-{
- m_converter = getConverter(typeName);
- if (!m_converter)
- return;
- const Py_ssize_t len = strlen(typeName);
- char lastChar = typeName[len -1];
- if (lastChar == '&') {
- m_type = ReferenceConversion;
- } else if (lastChar == '*' || pythonTypeIsObjectType(m_converter)) {
- m_type = PointerConversion;
- } else {
- m_type = CopyConversion;
- }
-}
-
-PyObject *SpecificConverter::toPython(const void *cppIn)
-{
- switch (m_type) {
- case CopyConversion:
- return copyToPython(m_converter, cppIn);
- case PointerConversion:
- return pointerToPython(m_converter, *static_cast<const void * const *>(cppIn));
- case ReferenceConversion:
- return referenceToPython(m_converter, cppIn);
- default:
- PyErr_SetString(PyExc_RuntimeError, "tried to use invalid converter in 'C++ to Python' conversion");
- }
- return nullptr;
-}
-
-void SpecificConverter::toCpp(PyObject *pyIn, void *cppOut)
-{
- switch (m_type) {
- case CopyConversion:
- pythonToCppCopy(m_converter, pyIn, cppOut);
- break;
- case PointerConversion:
- pythonToCppPointer(m_converter, pyIn, cppOut);
- break;
- case ReferenceConversion:
- pythonToCppPointer(m_converter, pyIn, &cppOut);
- break;
- default:
- PyErr_SetString(PyExc_RuntimeError, "tried to use invalid converter in 'Python to C++' conversion");
- }
-}
-
-} } // namespace Shiboken::Conversions
diff --git a/sources/shiboken2/libshiboken/sbkconverter.h b/sources/shiboken2/libshiboken/sbkconverter.h
deleted file mode 100644
index 6c7a29300..000000000
--- a/sources/shiboken2/libshiboken/sbkconverter.h
+++ /dev/null
@@ -1,405 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBK_CONVERTER_H
-#define SBK_CONVERTER_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-#include <limits>
-#include <string>
-
-struct SbkObject;
-struct SbkObjectType;
-
-/**
- * This is a convenience macro identical to Python's PyObject_TypeCheck,
- * except that the arguments have swapped places, for the great convenience
- * of generator.
- */
-#define SbkObject_TypeCheck(tp, ob) \
- (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
-
-extern "C"
-{
-
-/**
- * SbkConverter is used to perform type conversions from C++
- * to Python and vice-versa;.and it is also used for type checking.
- * SbkConverter is a private structure that must be accessed
- * using the functions provided by the converter API.
- */
-struct SbkConverter;
-struct SbkArrayConverter;
-
-/**
- * Given a void pointer to a C++ object, this function must return
- * the proper Python object. It may be either an existing wrapper
- * for the C++ object, or a newly create one. Or even the Python
- * equivalent of the C++ value passed in the argument.
- *
- * C++ -> Python
- */
-typedef PyObject *(*CppToPythonFunc)(const void *);
-
-/**
- * This function converts a Python object to a C++ value, it may be
- * a pointer, value, class, container or primitive type, passed via
- * a void pointer, that will be cast properly inside the function.
- * This function is usually returned by an IsConvertibleToCppFunc
- * function, or obtained knowing the type of the Python object input,
- * thus it will not check the Python object type, and will expect
- * the void pointer to be pointing to a proper variable.
- *
- * Python -> C++
- */
-typedef void (*PythonToCppFunc)(PyObject *,void *);
-
-/**
- * Checks if the Python object passed in the argument is convertible to a
- * C++ type defined inside the function, it returns the converter function
- * that will transform a Python argument into a C++ value.
- * It returns NULL if the Python object is not convertible to the C++ type
- * that the function represents.
- *
- * Python -> C++ ?
- */
-typedef PythonToCppFunc (*IsConvertibleToCppFunc)(PyObject *);
-
-} // extern "C"
-
-namespace Shiboken {
-namespace Conversions {
-
-
-class LIBSHIBOKEN_API SpecificConverter
-{
-public:
- enum Type
- {
- InvalidConversion,
- CopyConversion,
- PointerConversion,
- ReferenceConversion
- };
-
- explicit SpecificConverter(const char *typeName);
-
- inline SbkConverter *converter() { return m_converter; }
- inline operator SbkConverter *() const { return m_converter; }
-
- inline bool isValid() { return m_type != InvalidConversion; }
- inline operator bool() const { return m_type != InvalidConversion; }
-
- inline Type conversionType() { return m_type; }
-
- PyObject *toPython(const void *cppIn);
- void toCpp(PyObject *pyIn, void *cppOut);
-private:
- SbkConverter *m_converter;
- Type m_type;
-};
-
-
-/**
- * Creates a converter for a wrapper type.
- * \param type A Shiboken.ObjectType that will receive the new converter.
- * \param toCppPointerConvFunc Function to retrieve the C++ pointer held by a Python wrapper.
- * \param toCppPointerCheckFunc Check and return the retriever function of the C++ pointer held by a Python wrapper.
- * \param pointerToPythonFunc Function to convert a C++ object to a Python \p type wrapper, keeping their identity.
- * \param copyToPythonFunc Function to convert a C++ object to a Python \p type, copying the object.
- * \returns The new converter referred by the wrapper \p type.
- */
-LIBSHIBOKEN_API SbkConverter *createConverter(SbkObjectType *type,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc,
- CppToPythonFunc pointerToPythonFunc,
- CppToPythonFunc copyToPythonFunc = nullptr);
-
-/**
- * Creates a converter for a non wrapper type (primitive or container type).
- * \param type Python type representing to the new converter.
- * \param toPythonFunc Function to convert a C++ object to a Python \p type.
- * \returns A new type converter.
- */
-LIBSHIBOKEN_API SbkConverter *createConverter(PyTypeObject *type, CppToPythonFunc toPythonFunc);
-
-LIBSHIBOKEN_API void deleteConverter(SbkConverter *converter);
-
-/// Sets the Python object to C++ pointer conversion function.
-LIBSHIBOKEN_API void setCppPointerToPythonFunction(SbkConverter *converter, CppToPythonFunc pointerToPythonFunc);
-
-/// Sets the C++ pointer to Python object conversion functions.
-LIBSHIBOKEN_API void setPythonToCppPointerFunctions(SbkConverter *converter,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc);
-
-/**
- * Adds a new conversion of a Python object to a C++ value.
- * This is used in copy and implicit conversions.
- */
-LIBSHIBOKEN_API void addPythonToCppValueConversion(SbkConverter *converter,
- PythonToCppFunc pythonToCppFunc,
- IsConvertibleToCppFunc isConvertibleToCppFunc);
-LIBSHIBOKEN_API void addPythonToCppValueConversion(SbkObjectType *type,
- PythonToCppFunc pythonToCppFunc,
- IsConvertibleToCppFunc isConvertibleToCppFunc);
-
-// C++ -> Python ---------------------------------------------------------------------------
-
-/**
- * Retrieves the Python wrapper object for the given \p cppIn C++ pointer object.
- * This function is used only for Value and Object Types.
- * Example usage:
- * TYPE *var;
- * PyObject *pyVar = pointerToPython(SBKTYPE, &var);
- */
-LIBSHIBOKEN_API PyObject *pointerToPython(SbkObjectType *type, const void *cppIn);
-LIBSHIBOKEN_API PyObject *pointerToPython(const SbkConverter *converter, const void *cppIn);
-
-/**
- * For the given \p cppIn C++ reference it returns the Python wrapper object,
- * always for Object Types, and when they already exist for reference types;
- * for when the latter doesn't have an existing wrapper type, the C++ object
- * is copied to Python.
- * Example usage:
- * TYPE &var = SOMETHING;
- * PyObject *pyVar = referenceToPython(SBKTYPE, &var);
- */
-LIBSHIBOKEN_API PyObject *referenceToPython(SbkObjectType *type, const void *cppIn);
-LIBSHIBOKEN_API PyObject *referenceToPython(const SbkConverter *converter, const void *cppIn);
-
-/**
- * Retrieves the Python wrapper object for the given C++ value pointed by \p cppIn.
- * This function is used only for Value Types.
- * Example usage:
- * TYPE var;
- * PyObject *pyVar = copyToPython(SBKTYPE, &var);
- */
-LIBSHIBOKEN_API PyObject *copyToPython(SbkObjectType *type, const void *cppIn);
-LIBSHIBOKEN_API PyObject *copyToPython(const SbkConverter *converter, const void *cppIn);
-
-// Python -> C++ ---------------------------------------------------------------------------
-
-/**
- * Returns a Python to C++ conversion function if the Python object is convertible to a C++ pointer.
- * It returns NULL if the Python object is not convertible to \p type.
- */
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppPointerConvertible(SbkObjectType *type, PyObject *pyIn);
-
-/**
- * Returns a Python to C++ conversion function if the Python object is convertible to a C++ value.
- * The resulting converter function will create a copy of the Python object in C++, or implicitly
- * convert the object to the expected \p type.
- * It returns NULL if the Python object is not convertible to \p type.
- */
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppValueConvertible(SbkObjectType *type, PyObject *pyIn);
-
-/**
- * Returns a Python to C++ conversion function if the Python object is convertible to a C++ reference.
- * The resulting converter function will return the underlying C++ object held by the Python wrapper,
- * or a new C++ value if it must be a implicit conversion.
- * It returns NULL if the Python object is not convertible to \p type.
- */
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppReferenceConvertible(SbkObjectType *type, PyObject *pyIn);
-
-/// This is the same as isPythonToCppValueConvertible function.
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppConvertible(const SbkConverter *converter, PyObject *pyIn);
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppConvertible(const SbkArrayConverter *converter,
- int dim1, int dim2, PyObject *pyIn);
-
-/**
- * Returns the C++ pointer for the \p pyIn object cast to the type passed via \p desiredType.
- * It differs from Shiboken::Object::cppPointer because it casts the pointer to a proper
- * memory offset depending on the desired type.
- */
-LIBSHIBOKEN_API void *cppPointer(PyTypeObject *desiredType, SbkObject *pyIn);
-
-/// Converts a Python object \p pyIn to C++ and stores the result in the C++ pointer passed in \p cppOut.
-LIBSHIBOKEN_API void pythonToCppPointer(SbkObjectType *type, PyObject *pyIn, void *cppOut);
-LIBSHIBOKEN_API void pythonToCppPointer(const SbkConverter *converter, PyObject *pyIn, void *cppOut);
-
-/// Converts a Python object \p pyIn to C++, and copies the result in the C++ variable passed in \p cppOut.
-LIBSHIBOKEN_API void pythonToCppCopy(SbkObjectType *type, PyObject *pyIn, void *cppOut);
-LIBSHIBOKEN_API void pythonToCppCopy(const SbkConverter *converter, PyObject *pyIn, void *cppOut);
-
-/**
- * Helper function returned by generated convertible checking functions
- * that returns a C++ NULL when the input Python object is None.
- */
-LIBSHIBOKEN_API void nonePythonToCppNullPtr(PyObject *, void *cppOut);
-
-/**
- * Returns true if the \p toCpp function passed is an implicit conversion of Python \p type.
- * It is used when C++ expects a reference argument, so it may be the same object received
- * from Python, or another created through implicit conversion.
- */
-LIBSHIBOKEN_API bool isImplicitConversion(SbkObjectType *type, PythonToCppFunc toCpp);
-
-/// Registers a converter with a type name that may be used to retrieve the converter.
-LIBSHIBOKEN_API void registerConverterName(SbkConverter *converter, const char *typeName);
-
-/// Returns the converter for a given type name, or NULL if it wasn't registered before.
-LIBSHIBOKEN_API SbkConverter *getConverter(const char *typeName);
-
-/// Returns the converter for a primitive type.
-LIBSHIBOKEN_API SbkConverter *primitiveTypeConverter(int index);
-
-/// Returns true if a Python sequence is comprised of objects of the given \p type.
-LIBSHIBOKEN_API bool checkSequenceTypes(PyTypeObject *type, PyObject *pyIn);
-
-/// Returns true if a Python sequence is comprised of objects of a type convertible to the one represented by the given \p converter.
-LIBSHIBOKEN_API bool convertibleSequenceTypes(const SbkConverter *converter, PyObject *pyIn);
-
-/// Returns true if a Python sequence is comprised of objects of a type convertible to \p type.
-LIBSHIBOKEN_API bool convertibleSequenceTypes(SbkObjectType *type, PyObject *pyIn);
-
-/// Returns true if a Python sequence can be converted to a C++ pair.
-LIBSHIBOKEN_API bool checkPairTypes(PyTypeObject *firstType, PyTypeObject *secondType, PyObject *pyIn);
-
-/// Returns true if a Python sequence can be converted to a C++ pair.
-LIBSHIBOKEN_API bool convertiblePairTypes(const SbkConverter *firstConverter, bool firstCheckExact,
- const SbkConverter *secondConverter, bool secondCheckExact,
- PyObject *pyIn);
-
-/// Returns true if a Python dictionary can be converted to a C++ hash or map.
-LIBSHIBOKEN_API bool checkDictTypes(PyTypeObject *keyType, PyTypeObject *valueType, PyObject *pyIn);
-
-/// Returns true if a Python dictionary can be converted to a C++ hash or map.
-LIBSHIBOKEN_API bool convertibleDictTypes(const SbkConverter *keyConverter, bool keyCheckExact,
- const SbkConverter *valueConverter, bool valueCheckExact,
- PyObject *pyIn);
-
-/// Returns the Python type object associated with the given \p converter.
-LIBSHIBOKEN_API PyTypeObject *getPythonTypeObject(const SbkConverter *converter);
-
-/// Returns the Python type object for the given \p typeName.
-LIBSHIBOKEN_API PyTypeObject *getPythonTypeObject(const char *typeName);
-
-/// Returns true if the Python type associated with the converter is a value type.
-LIBSHIBOKEN_API bool pythonTypeIsValueType(const SbkConverter *converter);
-
-/// Returns true if the Python type associated with the converter is an object type.
-LIBSHIBOKEN_API bool pythonTypeIsObjectType(const SbkConverter *converter);
-
-/// Returns true if the Python type associated with the converter is a wrapper type.
-LIBSHIBOKEN_API bool pythonTypeIsWrapperType(const SbkConverter *converter);
-
-#define SBK_PY_LONG_LONG_IDX 0
-// Qt5: name collision in QtCore after QBool is replaced by bool
-#define SBK_BOOL_IDX_1 1
-#define SBK_CHAR_IDX 2
-#define SBK_CONSTCHARPTR_IDX 3
-#define SBK_DOUBLE_IDX 4
-#define SBK_FLOAT_IDX 5
-#define SBK_INT_IDX 6
-#define SBK_SIGNEDINT_IDX 6
-#define SBK_LONG_IDX 7
-#define SBK_SHORT_IDX 8
-#define SBK_SIGNEDCHAR_IDX 9
-#define SBK_STD_STRING_IDX 10
-#define SBK_UNSIGNEDPY_LONG_LONG_IDX 11
-#define SBK_UNSIGNEDCHAR_IDX 12
-#define SBK_UNSIGNEDINT_IDX 13
-#define SBK_UNSIGNEDLONG_IDX 14
-#define SBK_UNSIGNEDSHORT_IDX 15
-#define SBK_VOIDPTR_IDX 16
-#define SBK_NULLPTR_T_IDX 17
-
-template<typename T> SbkConverter *PrimitiveTypeConverter() { return nullptr; }
-template<> inline SbkConverter *PrimitiveTypeConverter<PY_LONG_LONG>() { return primitiveTypeConverter(SBK_PY_LONG_LONG_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<bool>() { return primitiveTypeConverter(SBK_BOOL_IDX_1); }
-template<> inline SbkConverter *PrimitiveTypeConverter<char>() { return primitiveTypeConverter(SBK_CHAR_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<const char *>() { return primitiveTypeConverter(SBK_CONSTCHARPTR_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<double>() { return primitiveTypeConverter(SBK_DOUBLE_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<float>() { return primitiveTypeConverter(SBK_FLOAT_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<int>() { return primitiveTypeConverter(SBK_INT_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<long>() { return primitiveTypeConverter(SBK_LONG_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<short>() { return primitiveTypeConverter(SBK_SHORT_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<signed char>() { return primitiveTypeConverter(SBK_SIGNEDCHAR_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<std::string>() { return primitiveTypeConverter(SBK_STD_STRING_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<unsigned PY_LONG_LONG>() { return primitiveTypeConverter(SBK_UNSIGNEDPY_LONG_LONG_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<unsigned char>() { return primitiveTypeConverter(SBK_UNSIGNEDCHAR_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<unsigned int>() { return primitiveTypeConverter(SBK_UNSIGNEDINT_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<unsigned long>() { return primitiveTypeConverter(SBK_UNSIGNEDLONG_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<unsigned short>() { return primitiveTypeConverter(SBK_UNSIGNEDSHORT_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<void *>() { return primitiveTypeConverter(SBK_VOIDPTR_IDX); }
-template<> inline SbkConverter *PrimitiveTypeConverter<std::nullptr_t>() { return primitiveTypeConverter(SBK_NULLPTR_T_IDX); }
-
-} // namespace Shiboken::Conversions
-
-/**
-* This function template is used to get the PyTypeObject of a C++ type T.
-* All implementations should be provided by template specializations generated by the generator when
-* T isn't a C++ primitive type.
-* \see SpecialCastFunction
-*/
-template<typename T> PyTypeObject *SbkType() { return nullptr; }
-
-// Below are the template specializations for C++ primitive types.
-template<> inline PyTypeObject *SbkType<PY_LONG_LONG>() { return &PyLong_Type; }
-template<> inline PyTypeObject *SbkType<bool>() { return &PyBool_Type; }
-template<> inline PyTypeObject *SbkType<char>() { return &PyInt_Type; }
-template<> inline PyTypeObject *SbkType<double>() { return &PyFloat_Type; }
-template<> inline PyTypeObject *SbkType<float>() { return &PyFloat_Type; }
-template<> inline PyTypeObject *SbkType<int>() { return &PyInt_Type; }
-template<> inline PyTypeObject *SbkType<long>() { return &PyLong_Type; }
-template<> inline PyTypeObject *SbkType<short>() { return &PyInt_Type; }
-template<> inline PyTypeObject *SbkType<signed char>() { return &PyInt_Type; }
-template<> inline PyTypeObject *SbkType<unsigned PY_LONG_LONG>() { return &PyLong_Type; }
-template<> inline PyTypeObject *SbkType<unsigned char>() { return &PyInt_Type; }
-template<> inline PyTypeObject *SbkType<unsigned int>() { return &PyLong_Type; }
-template<> inline PyTypeObject *SbkType<unsigned long>() { return &PyLong_Type; }
-template<> inline PyTypeObject *SbkType<unsigned short>() { return &PyInt_Type; }
-template<> inline PyTypeObject *SbkType<std::nullptr_t>() { return Py_TYPE(&_Py_NoneStruct); }
-
-} // namespace Shiboken
-
-// When the user adds a function with an argument unknown for the typesystem, the generator writes type checks as
-// TYPENAME_Check, so this macro allows users to add PyObject arguments to their added functions.
-#define PyObject_Check(X) true
-#define SbkChar_Check(X) (SbkNumber_Check(X) || Shiboken::String::checkChar(X))
-
-struct _SbkGenericTypePrivate {
- SbkConverter **converter;
-};
-
-
-#endif // SBK_CONVERTER_H
diff --git a/sources/shiboken2/libshiboken/sbkconverter_p.h b/sources/shiboken2/libshiboken/sbkconverter_p.h
deleted file mode 100644
index d87162071..000000000
--- a/sources/shiboken2/libshiboken/sbkconverter_p.h
+++ /dev/null
@@ -1,575 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBK_CONVERTER_P_H
-#define SBK_CONVERTER_P_H
-
-#include "sbkpython.h"
-#include "sbkconverter.h"
-#include "sbkstring.h"
-#include <limits>
-#include <typeinfo>
-#include <sstream>
-#include <iostream>
-#include <vector>
-
-#include "sbkdbg.h"
-
-extern "C"
-{
-
-using ToCppConversion = std::pair<IsConvertibleToCppFunc, PythonToCppFunc>;
-using ToCppConversionVector = std::vector<ToCppConversion>;
-
-/**
- * \internal
- * Private structure of SbkConverter.
- */
-struct SbkConverter
-{
- /**
- * Python type associated with this converter. If the type is a Shiboken
- * wrapper, then it must be a SbkObjectType; otherwise it will be the
- * Python type to which the C++ value will be converted (note that the
- * C++ type could be produced from various Python types).
- */
- PyTypeObject *pythonType;
- /**
- * This function converts a C++ object to a Python object of the type
- * indicated in pythonType. The identity of the C++ object is kept,
- * because it looks for an already existing Python wrapper associated
- * with the C++ instance.
- * It is used to convert C++ pointers and references to Python objects.
- */
- CppToPythonFunc pointerToPython;
- /**
- * This function converts a C++ object to a Python object of the type
- * indicated in pythonType. The identity of the object is not kept,
- * because a new instance of the C++ object is created.
- * It is used to convert objects passed by value, or reference, if said
- * reference can't be traced to an object that already has a Python
- * wrapper assigned for it.
- */
- CppToPythonFunc copyToPython;
- /**
- * This is a special case of a Python to C++ conversion. It returns
- * the underlying C++ pointer of a Python wrapper passed as parameter
- * or NULL if the Python object is a None value.
- * It comes separated from the other toCppConversions because if you
- * have a Python object representing a Value Type the type checking
- * for both ValueType and ValueType *would be the same, thus the first
- * check would be true and the second would never be reached.
- */
- ToCppConversion toCppPointerConversion;
- /**
- * This is a list of type checking functions that return the
- * proper Python to C++ conversion function, for the given Python
- * object.
- * For Object Types, that never have implicit conversions, this
- * list is always empty.
- */
- ToCppConversionVector toCppConversions;
-};
-
-} // extern "C"
-
-template<typename T, typename MaxLimitType, bool isSigned>
-struct OverFlowCheckerBase {
- static void formatOverFlowMessage(const MaxLimitType &value,
- const std::string *valueAsString = nullptr)
- {
- std::ostringstream str;
- str << "libshiboken: Overflow: Value ";
- if (valueAsString != nullptr && !valueAsString->empty())
- str << *valueAsString;
- else
- str << value;
- str << " exceeds limits of type "
- << " [" << (isSigned ? "signed" : "unsigned")
- << "] \"" << typeid(T).name()
- << "\" (" << sizeof(T) << "bytes).";
- const std::string message = str.str();
- PyErr_WarnEx(PyExc_RuntimeWarning, message.c_str(), 0);
- }
-
- // Checks if an overflow occurred inside Python code.
- // Precondition: use after calls like PyLong_AsLongLong or PyLong_AsUnsignedLongLong.
- // Postcondition: if error ocurred, sets the string reference to the string representation of
- // the passed value.
- static bool checkForInternalPyOverflow(PyObject *pyIn, std::string &valueAsString)
- {
- if (PyErr_Occurred()) {
- PyErr_Print();
- PyObject *stringRepresentation = PyObject_Str(pyIn);
- const char *cString = Shiboken::String::toCString(stringRepresentation);
- valueAsString.assign(cString);
- Py_DECREF(stringRepresentation);
- return true;
- }
- return false;
- }
-};
-
-// Helper template for checking if a value overflows when cast to type T.
-// The MaxLimitType size is usually >= than type T size, so that it can still represent values that
-// can't be stored in T (unless the types are of course the same).
-// TLDR: MaxLimitType is either long long or unsigned long long.
-template<typename T, typename MaxLimitType = PY_LONG_LONG,
- bool isSigned = std::numeric_limits<T>::is_signed >
-struct OverFlowChecker;
-
-template<typename T, typename MaxLimitType>
-struct OverFlowChecker<T, MaxLimitType, true> :
- public OverFlowCheckerBase<T, MaxLimitType, true> {
- static bool check(const MaxLimitType &value, PyObject *pyIn)
- {
- std::string valueAsString;
- const bool isOverflow =
- OverFlowChecker::checkForInternalPyOverflow(pyIn, valueAsString)
- || value < std::numeric_limits<T>::min()
- || value > std::numeric_limits<T>::max();
- if (isOverflow)
- OverFlowChecker::formatOverFlowMessage(value, &valueAsString);
- return isOverflow;
- }
-};
-
-template<typename T, typename MaxLimitType>
-struct OverFlowChecker<T, MaxLimitType, false>
- : public OverFlowCheckerBase<T, MaxLimitType, false> {
- static bool check(const MaxLimitType &value, PyObject *pyIn)
- {
- std::string valueAsString;
- const bool isOverflow =
- OverFlowChecker::checkForInternalPyOverflow(pyIn, valueAsString)
- || value < 0
- || static_cast<unsigned long long>(value) > std::numeric_limits<T>::max();
- if (isOverflow)
- OverFlowChecker::formatOverFlowMessage(value, &valueAsString);
- return isOverflow;
- }
-};
-template<>
-struct OverFlowChecker<PY_LONG_LONG, PY_LONG_LONG, true> :
- public OverFlowCheckerBase<PY_LONG_LONG, PY_LONG_LONG, true> {
- static bool check(const PY_LONG_LONG &value, PyObject *pyIn) {
- std::string valueAsString;
- const bool isOverflow = checkForInternalPyOverflow(pyIn, valueAsString);
- if (isOverflow)
- OverFlowChecker::formatOverFlowMessage(value, &valueAsString);
- return isOverflow;
-
- }
-};
-template<>
-struct OverFlowChecker<double, PY_LONG_LONG, true> {
- static bool check(const double &, PyObject *) { return false; }
-};
-template<>
-struct OverFlowChecker<float, PY_LONG_LONG, true> :
- public OverFlowCheckerBase<float, PY_LONG_LONG, true> {
- static bool check(const double &value, PyObject *)
- {
- const bool result = value < std::numeric_limits<float>::min()
- || value > std::numeric_limits<float>::max();
- if (result)
- formatOverFlowMessage(value);
- return result;
- }
-};
-
-// Basic primitive type converters ---------------------------------------------------------
-
-template <typename T> struct Primitive {};
-
-template <typename T>
-struct OnePrimitive
-{
- static PyObject *toPython(const void *) { return nullptr; }
- static PythonToCppFunc isConvertible(PyObject *) { return nullptr; }
- static void toCpp(PyObject *, void *) {}
- static SbkConverter *createConverter()
- {
- SbkConverter *converter = Shiboken::Conversions::createConverter(Shiboken::SbkType<T>(),
- Primitive<T>::toPython);
- Shiboken::Conversions::addPythonToCppValueConversion(converter,
- Primitive<T>::toCpp,
- Primitive<T>::isConvertible);
- return converter;
- }
-};
-template <typename T>
-struct TwoPrimitive : OnePrimitive<T>
-{
- static PythonToCppFunc isOtherConvertible(PyObject *) { return nullptr; }
- static void otherToCpp(PyObject *, void *) {}
- static SbkConverter *createConverter()
- {
- SbkConverter *converter = OnePrimitive<T>::createConverter();
- Shiboken::Conversions::addPythonToCppValueConversion(converter, Primitive<T>::otherToCpp, Primitive<T>::isOtherConvertible);
- return converter;
- }
-};
-
-// Integers --------------------------------------------------------------------------------
-
-template <typename INT>
-struct IntPrimitive : TwoPrimitive<INT>
-{
- static PyObject *toPython(const void *cppIn)
- {
- return PyInt_FromLong(*reinterpret_cast<const INT *>(cppIn));
- }
- static void toCpp(PyObject *pyIn, void *cppOut)
- {
- double result = PyFloat_AS_DOUBLE(pyIn);
- // If cast to long directly it could overflow silently.
- if (OverFlowChecker<INT>::check(result, pyIn))
- PyErr_SetObject(PyExc_OverflowError, nullptr);
- *reinterpret_cast<INT * >(cppOut) = static_cast<INT>(result);
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (PyFloat_Check(pyIn))
- return toCpp;
- return nullptr;
- }
- static void otherToCpp(PyObject *pyIn, void *cppOut)
- {
- PY_LONG_LONG result = PyLong_AsLongLong(pyIn);
- if (OverFlowChecker<INT>::check(result, pyIn))
- PyErr_SetObject(PyExc_OverflowError, nullptr);
- *reinterpret_cast<INT * >(cppOut) = static_cast<INT>(result);
- }
- static PythonToCppFunc isOtherConvertible(PyObject *pyIn)
- {
- if (SbkNumber_Check(pyIn))
- return otherToCpp;
- return nullptr;
- }
-};
-template <> struct Primitive<int> : IntPrimitive<int> {};
-template <> struct Primitive<long> : IntPrimitive<long> {};
-template <> struct Primitive<short> : IntPrimitive<short> {};
-template <> struct Primitive<unsigned short> : IntPrimitive<unsigned short> {};
-
-// Unsigned Long Integers ------------------------------------------------------------------
-
-template <typename LONG>
-struct UnsignedLongPrimitive : IntPrimitive<LONG>
-{
- static PyObject *toPython(const void *cppIn)
- {
- return PyLong_FromUnsignedLong(*reinterpret_cast<const LONG *>(cppIn));
- }
-};
-template <> struct Primitive<unsigned int> : UnsignedLongPrimitive<unsigned int> {};
-template <> struct Primitive<unsigned long> : UnsignedLongPrimitive<unsigned long> {};
-
-// Big integers ----------------------------------------------------------------------------
-
-template <>
-struct Primitive<PY_LONG_LONG> : OnePrimitive<PY_LONG_LONG>
-{
- static PyObject *toPython(const void *cppIn)
- {
- return PyLong_FromLongLong(*reinterpret_cast<const PY_LONG_LONG *>(cppIn));
- }
- static void toCpp(PyObject *pyIn, void *cppOut)
- {
- PY_LONG_LONG result = PyLong_AsLongLong(pyIn);
- if (OverFlowChecker<PY_LONG_LONG>::check(result, pyIn))
- PyErr_SetObject(PyExc_OverflowError, 0);
- *reinterpret_cast<PY_LONG_LONG * >(cppOut) = result;
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (SbkNumber_Check(pyIn))
- return toCpp;
- return nullptr;
- }
-};
-
-template <>
-struct Primitive<unsigned PY_LONG_LONG> : OnePrimitive<unsigned PY_LONG_LONG>
-{
- static PyObject *toPython(const void *cppIn)
- {
- return PyLong_FromUnsignedLongLong(*static_cast<const unsigned PY_LONG_LONG *>(cppIn));
- }
- static void toCpp(PyObject *pyIn, void *cppOut)
- {
-#if PY_MAJOR_VERSION >= 3
- if (PyLong_Check(pyIn)) {
- unsigned PY_LONG_LONG result = PyLong_AsUnsignedLongLong(pyIn);
- if (OverFlowChecker<unsigned PY_LONG_LONG, unsigned PY_LONG_LONG>::check(result, pyIn))
- PyErr_SetObject(PyExc_OverflowError, nullptr);
- *reinterpret_cast<unsigned PY_LONG_LONG * >(cppOut) = result;
- }
- else {
- PyErr_SetString(PyExc_TypeError, "Invalid type for unsigned long long conversion");
- }
-#else
- if (PyInt_Check(pyIn)) {
- long result = PyInt_AsLong(pyIn);
- if (OverFlowChecker<unsigned PY_LONG_LONG>::check(result, pyIn))
- PyErr_SetObject(PyExc_OverflowError, 0);
- *reinterpret_cast<unsigned PY_LONG_LONG * >(cppOut) =
- static_cast<unsigned PY_LONG_LONG>(result);
- } else if (PyLong_Check(pyIn)) {
- unsigned PY_LONG_LONG result = PyLong_AsUnsignedLongLong(pyIn);
- if (OverFlowChecker<unsigned PY_LONG_LONG, unsigned PY_LONG_LONG>::check(result, pyIn))
- PyErr_SetObject(PyExc_OverflowError, 0);
- *reinterpret_cast<unsigned PY_LONG_LONG * >(cppOut) = result;
- } else {
- PyErr_SetString(PyExc_TypeError, "Invalid type for unsigned long long conversion");
- }
-#endif // Python 2
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (SbkNumber_Check(pyIn))
- return toCpp;
- return nullptr;
- }
-};
-
-// Floating point --------------------------------------------------------------------------
-
-template <typename FLOAT>
-struct FloatPrimitive : TwoPrimitive<FLOAT>
-{
- static PyObject *toPython(const void *cppIn)
- {
- return PyFloat_FromDouble(*reinterpret_cast<const FLOAT *>(cppIn));
- }
- static void toCpp(PyObject *pyIn, void *cppOut)
- {
- *reinterpret_cast<FLOAT *>(cppOut) = FLOAT(PyLong_AsLong(pyIn));
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (PyInt_Check(pyIn) || PyLong_Check(pyIn))
- return toCpp;
- return nullptr;
- }
- static void otherToCpp(PyObject *pyIn, void *cppOut)
- {
- *reinterpret_cast<FLOAT *>(cppOut) = FLOAT(PyFloat_AsDouble(pyIn));
- }
- static PythonToCppFunc isOtherConvertible(PyObject *pyIn)
- {
- if (SbkNumber_Check(pyIn))
- return otherToCpp;
- return nullptr;
- }
-};
-template <> struct Primitive<float> : FloatPrimitive<float> {};
-template <> struct Primitive<double> : FloatPrimitive<double> {};
-
-// Boolean ---------------------------------------------------------------------------------
-
-template <>
-struct Primitive<bool> : OnePrimitive<bool>
-{
- static PyObject *toPython(const void *cppIn)
- {
- return PyBool_FromLong(*reinterpret_cast<const bool *>(cppIn));
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (SbkNumber_Check(pyIn))
- return toCpp;
- return nullptr;
- }
- static void toCpp(PyObject *pyIn, void *cppOut)
- {
- *reinterpret_cast<bool *>(cppOut) = PyInt_AS_LONG(pyIn) != 0;
- }
-};
-
-// Characters ------------------------------------------------------------------------------
-
-template <typename CHAR>
-struct CharPrimitive : IntPrimitive<CHAR>
-{
- static void toCpp(PyObject *pyIn, void *cppOut)
- {
- *reinterpret_cast<CHAR *>(cppOut) = CHAR(Shiboken::String::toCString(pyIn)[0]);
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (Shiboken::String::checkChar(pyIn))
- return toCpp;
- return nullptr;
- }
- static void otherToCpp(PyObject *pyIn, void *cppOut)
- {
- PY_LONG_LONG result = PyLong_AsLongLong(pyIn);
- if (OverFlowChecker<CHAR>::check(result, pyIn))
- PyErr_SetObject(PyExc_OverflowError, nullptr);
- *reinterpret_cast<CHAR *>(cppOut) = CHAR(result);
- }
- static PythonToCppFunc isOtherConvertible(PyObject *pyIn)
- {
- if (SbkNumber_Check(pyIn))
- return otherToCpp;
- return nullptr;
- }
- static SbkConverter *createConverter()
- {
- SbkConverter *converter = IntPrimitive<CHAR>::createConverter();
- Shiboken::Conversions::addPythonToCppValueConversion(converter, CharPrimitive<CHAR>::otherToCpp, CharPrimitive<CHAR>::isOtherConvertible);
- return converter;
- }
-
-};
-template <> struct Primitive<signed char> : CharPrimitive<signed char> {};
-template <> struct Primitive<unsigned char> : CharPrimitive<unsigned char> {};
-template <> struct Primitive<char> : CharPrimitive<char> {
- using CharPrimitive<char>::toPython;
- static PyObject *toPython(const void *cppIn) {
- return Shiboken::String::fromCString(reinterpret_cast<const char *>(cppIn), 1);
- }
-};
-
-
-
-// Strings ---------------------------------------------------------------------------------
-
-template <>
-struct Primitive<const char *> : TwoPrimitive<const char *>
-{
- static PyObject *toPython(const void *cppIn)
- {
- if (!cppIn)
- Py_RETURN_NONE;
- return Shiboken::String::fromCString(reinterpret_cast<const char *>(cppIn));
- }
- static void toCpp(PyObject *, void *cppOut)
- {
- *((const char **)cppOut) = nullptr;
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (pyIn == Py_None)
- return toCpp;
- return nullptr;
- }
- static void otherToCpp(PyObject *pyIn, void *cppOut)
- {
- *reinterpret_cast<const char **>(cppOut) = Shiboken::String::toCString(pyIn);
- }
- static PythonToCppFunc isOtherConvertible(PyObject *pyIn)
- {
- if (Shiboken::String::check(pyIn))
- return otherToCpp;
- return nullptr;
- }
-};
-
-template <>
-struct Primitive<std::string> : TwoPrimitive<std::string>
-{
- static PyObject *toPython(const void *cppIn)
- {
- return Shiboken::String::fromCString(reinterpret_cast<const std::string *>(cppIn)->c_str());
- }
- static void toCpp(PyObject *, void *cppOut)
- {
- reinterpret_cast<std::string *>(cppOut)->clear();
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (pyIn == Py_None)
- return toCpp;
- return nullptr;
- }
- static void otherToCpp(PyObject *pyIn, void *cppOut)
- {
- reinterpret_cast<std::string *>(cppOut)->assign(Shiboken::String::toCString(pyIn));
- }
- static PythonToCppFunc isOtherConvertible(PyObject *pyIn)
- {
- if (Shiboken::String::check(pyIn))
- return otherToCpp;
- return nullptr;
- }
-};
-
-// nullptr_t
-template <>
-struct Primitive<std::nullptr_t> : TwoPrimitive<std::nullptr_t>
-{
- static PyObject *toPython(const void * /* cppIn */)
- {
- return Py_None;
- }
- static void toCpp(PyObject *, void *cppOut)
- {
- *reinterpret_cast<std::nullptr_t *>(cppOut) = nullptr;
- }
- static PythonToCppFunc isConvertible(PyObject *pyIn)
- {
- if (pyIn == Py_None)
- return toCpp;
- return nullptr;
- }
- static void otherToCpp(PyObject * /* pyIn */, void *cppOut)
- {
- *reinterpret_cast<std::nullptr_t *>(cppOut) = nullptr;
- }
- static PythonToCppFunc isOtherConvertible(PyObject *pyIn)
- {
- if (pyIn == nullptr)
- return otherToCpp;
- return nullptr;
- }
-};
-
-namespace Shiboken {
-namespace Conversions {
-SbkConverter *createConverterObject(PyTypeObject *type,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc,
- CppToPythonFunc pointerToPythonFunc,
- CppToPythonFunc copyToPythonFunc);
-} // namespace Conversions
-} // namespace Shiboken
-#endif // SBK_CONVERTER_P_H
diff --git a/sources/shiboken2/libshiboken/sbkdbg.h b/sources/shiboken2/libshiboken/sbkdbg.h
deleted file mode 100644
index 02ea773ac..000000000
--- a/sources/shiboken2/libshiboken/sbkdbg.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKDBG_H
-#define SBKDBG_H
-
-#include "sbkpython.h"
-#include "basewrapper.h"
-#include <iostream>
-
-#ifndef NOCOLOR
- #define COLOR_END "\033[0m"
- #define COLOR_WHITE "\033[1;37m"
- #define COLOR_YELLOW "\033[1;33m"
- #define COLOR_GREEN "\033[0;32m"
- #define COLOR_RED "\033[0;31m"
-#else
- #define COLOR_END ""
- #define COLOR_WHITE ""
- #define COLOR_YELLOW ""
- #define COLOR_GREEN ""
- #define COLOR_RED ""
-#endif
-
-#ifndef NDEBUG
-
-class BaseLogger
-{
-public:
- BaseLogger(const BaseLogger &) = delete;
- BaseLogger(BaseLogger &&) = delete;
- BaseLogger &operator=(const BaseLogger &) = delete;
- BaseLogger &operator=(BaseLogger &&) = delete;
-
- BaseLogger(std::ostream &output, const char *function, const char *context)
- : m_stream(output), m_function(function), m_context(context) {}
- ~BaseLogger()
- {
- m_stream << std::endl;
- }
- std::ostream &operator()() { return m_stream; };
- template <typename T>
- std::ostream &operator<<(const T &t)
- {
- m_stream << '[';
- if (m_context[0])
- m_stream << COLOR_GREEN << m_context << COLOR_END << "|";
- return m_stream << COLOR_WHITE << m_function << COLOR_END << "] " << t;
- }
-private:
- std::ostream &m_stream;
- const char *m_function;
- const char *m_context;
-};
-
-inline std::ostream &operator<<(std::ostream &out, PyObject *obj)
-{
- PyObject *repr = Shiboken::Object::isValid(obj, false) ? PyObject_Repr(obj) : 0;
- if (repr) {
-#ifdef IS_PY3K
- PyObject *str = PyUnicode_AsUTF8String(repr);
- Py_DECREF(repr);
- repr = str;
-#endif
- out << PyBytes_AS_STRING(repr);
- Py_DECREF(repr);
- } else {
- out << reinterpret_cast<void *>(obj);
- }
- return out;
-}
-
-class _SbkDbg : public BaseLogger
-{
-public:
- _SbkDbg(const char *function, const char *context = "") : BaseLogger(std::cout, function, context) {}
-};
-
-#ifdef __GNUG__
-#define SbkDbg(X) _SbkDbg(__PRETTY_FUNCTION__, X"")
-#else
-#define SbkDbg(X) _SbkDbg(__FUNCTION__, X"")
-#endif
-
-#else
-
-struct SbkDbg {
- template <typename T>
- SbkDbg &operator<<(const T &) { return *this; }
-};
-
-#endif
-#endif // LOGGER_H
diff --git a/sources/shiboken2/libshiboken/sbkenum.cpp b/sources/shiboken2/libshiboken/sbkenum.cpp
deleted file mode 100644
index 36f2f48f9..000000000
--- a/sources/shiboken2/libshiboken/sbkenum.cpp
+++ /dev/null
@@ -1,802 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkenum.h"
-#include "sbkstring.h"
-#include "sbkstaticstrings.h"
-#include "sbkstaticstrings_p.h"
-#include "sbkconverter.h"
-#include "basewrapper.h"
-#include "sbkdbg.h"
-#include "autodecref.h"
-#include "sbkpython.h"
-
-#include <string.h>
-#include <cstring>
-#include <vector>
-
-#define SBK_ENUM(ENUM) reinterpret_cast<SbkEnumObject *>(ENUM)
-#define SBK_TYPE_CHECK(o) (strcmp(Py_TYPE(Py_TYPE(o))->tp_name, "Shiboken.EnumType") == 0)
-typedef PyObject *(*enum_func)(PyObject *, PyObject *);
-
-extern "C"
-{
-
-struct SbkEnumTypePrivate
-{
- SbkConverter **converterPtr;
- SbkConverter *converter;
- const char *cppName;
-};
-
-struct SbkEnumType
-{
- PyTypeObject type;
-};
-
-struct SbkEnumObject
-{
- PyObject_HEAD
- long ob_value;
- PyObject *ob_name;
-};
-
-static PyObject *SbkEnumObject_repr(PyObject *self)
-{
- const SbkEnumObject *enumObj = SBK_ENUM(self);
- if (enumObj->ob_name)
- return Shiboken::String::fromFormat("%s.%s", (Py_TYPE(self))->tp_name, PyBytes_AS_STRING(enumObj->ob_name));
- else
- return Shiboken::String::fromFormat("%s(%ld)", (Py_TYPE(self))->tp_name, enumObj->ob_value);
-}
-
-static PyObject *SbkEnumObject_name(PyObject *self, void *)
-{
- auto *enum_self = SBK_ENUM(self);
-
- if (enum_self->ob_name == nullptr)
- Py_RETURN_NONE;
-
- Py_INCREF(enum_self->ob_name);
- return enum_self->ob_name;
-}
-
-static PyObject *SbkEnum_tp_new(PyTypeObject *type, PyObject *args, PyObject *)
-{
- long itemValue = 0;
- if (!PyArg_ParseTuple(args, "|l:__new__", &itemValue))
- return nullptr;
-
- SbkEnumObject *self = PyObject_New(SbkEnumObject, type);
- if (!self)
- return nullptr;
- self->ob_value = itemValue;
- Shiboken::AutoDecRef item(Shiboken::Enum::getEnumItemFromValue(type, itemValue));
- self->ob_name = item.object() ? SbkEnumObject_name(item, nullptr) : nullptr;
- return reinterpret_cast<PyObject *>(self);
-}
-
-void enum_object_dealloc(PyObject *ob)
-{
- auto self = reinterpret_cast<SbkEnumObject *>(ob);
- Py_XDECREF(self->ob_name);
- Sbk_object_dealloc(ob);
-}
-
-static PyObject *enum_op(enum_func f, PyObject *a, PyObject *b) {
- PyObject *valA = a;
- PyObject *valB = b;
- PyObject *result = nullptr;
- bool enumA = false;
- bool enumB = false;
-
- // We are not allowing floats
- if (!PyFloat_Check(valA) && !PyFloat_Check(valB)) {
- // Check if both variables are SbkEnumObject
- if (SBK_TYPE_CHECK(valA)) {
- valA = PyLong_FromLong(SBK_ENUM(valA)->ob_value);
- enumA = true;
- }
- if (SBK_TYPE_CHECK(valB)) {
- valB = PyLong_FromLong(SBK_ENUM(valB)->ob_value);
- enumB = true;
- }
- }
-
- // Without an enum we are not supporting the operation
- if (!(enumA || enumB)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- } else {
- result = f(valA, valB);
- }
-
- // Decreasing the reference of the used variables a and b.
- if (enumA)
- Py_DECREF(valA);
- if (enumB)
- Py_DECREF(valB);
-
- return result;
-}
-
-/* Notes:
- * On Py3k land we use long type when using integer numbers. However, on older
- * versions of Python (version 2) we need to convert it to int type,
- * respectively.
- *
- * Thus calling PyInt_FromLong() will result in calling PyLong_FromLong in
- * Py3k.
- */
-static PyObject *enum_int(PyObject *v)
-{
- return PyInt_FromLong(SBK_ENUM(v)->ob_value);
-}
-
-static PyObject *enum_and(PyObject *self, PyObject *b)
-{
- return enum_op(PyNumber_And, self, b);
-}
-
-static PyObject *enum_or(PyObject *self, PyObject *b)
-{
-return enum_op(PyNumber_Or, self, b);
-}
-
-static PyObject *enum_xor(PyObject *self, PyObject *b)
-{
- return enum_op(PyNumber_Xor, self, b);
-}
-
-static int enum_bool(PyObject *v)
-{
- return (SBK_ENUM(v)->ob_value > 0);
-}
-
-static PyObject *enum_add(PyObject *self, PyObject *v)
-{
- return enum_op(PyNumber_Add, self, v);
-}
-
-static PyObject *enum_subtract(PyObject *self, PyObject *v)
-{
- return enum_op(PyNumber_Subtract, self, v);
-}
-
-static PyObject *enum_multiply(PyObject *self, PyObject *v)
-{
-return enum_op(PyNumber_Multiply, self, v);
-}
-
-#ifndef IS_PY3K
-static PyObject *enum_divide(PyObject *self, PyObject *v)
-{
- return enum_op(PyNumber_Divide, self, v);
-}
-#endif
-
-static PyObject *enum_richcompare(PyObject *self, PyObject *other, int op)
-{
- PyObject *valA = self;
- PyObject *valB = other;
- PyObject *result = nullptr;
- bool enumA = false;
- bool enumB = false;
-
- // We are not allowing floats
- if (!PyFloat_Check(valA) && !PyFloat_Check(valB)) {
-
- // Check if both variables are SbkEnumObject
- if (SBK_TYPE_CHECK(valA)) {
- valA = PyLong_FromLong(SBK_ENUM(valA)->ob_value);
- enumA = true;
- }
- if (SBK_TYPE_CHECK(valB)) {
- valB = PyLong_FromLong(SBK_ENUM(valB)->ob_value);
- enumB =true;
- }
- }
-
- // Without an enum we are not supporting the operation
- if (!(enumA || enumB)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- result = PyObject_RichCompare(valA, valB, op);
-
- // Decreasing the reference of the used variables a and b.
- if (enumA)
- Py_DECREF(valA);
- if (enumB)
- Py_DECREF(valB);
-
- return result;
-}
-
-static Py_hash_t enum_hash(PyObject *pyObj)
-{
- Py_hash_t val = reinterpret_cast<SbkEnumObject *>(pyObj)->ob_value;
- if (val == -1)
- val = -2;
- return val;
-}
-
-static PyGetSetDef SbkEnumGetSetList[] = {
- {const_cast<char *>("name"), &SbkEnumObject_name, nullptr, nullptr, nullptr},
- {nullptr, nullptr, nullptr, nullptr, nullptr} // Sentinel
-};
-
-#if PY_VERSION_HEX < 0x03000000
-
-static PyObject *SbkEnumType_repr(PyObject *type)
-{
- Shiboken::AutoDecRef mod(PyObject_GetAttr(type, Shiboken::PyMagicName::module()));
- if (mod.isNull())
- return nullptr;
- Shiboken::AutoDecRef name(PyObject_GetAttr(type, Shiboken::PyMagicName::qualname()));
- if (name.isNull())
- return nullptr;
- return PyString_FromFormat("<class '%s.%s'>",
- PyString_AS_STRING(mod.object()),
- PyString_AS_STRING(name.object()));
-}
-
-#endif // PY_VERSION_HEX < 0x03000000
-
-static void SbkEnumTypeDealloc(PyObject *pyObj);
-static PyObject *SbkEnumTypeTpNew(PyTypeObject *metatype, PyObject *args, PyObject *kwds);
-
-static PyType_Slot SbkEnumType_Type_slots[] = {
- {Py_tp_dealloc, (void *)SbkEnumTypeDealloc},
- {Py_nb_add, (void *)enum_add},
- {Py_nb_subtract, (void *)enum_subtract},
- {Py_nb_multiply, (void *)enum_multiply},
-#ifndef IS_PY3K
- {Py_nb_divide, (void *)enum_divide},
-#endif
- {Py_nb_positive, (void *)enum_int},
-#ifdef IS_PY3K
- {Py_nb_bool, (void *)enum_bool},
-#else
- {Py_nb_nonzero, (void *)enum_bool},
- {Py_nb_long, (void *)enum_int},
-#endif
- {Py_nb_and, (void *)enum_and},
- {Py_nb_xor, (void *)enum_xor},
- {Py_nb_or, (void *)enum_or},
- {Py_nb_int, (void *)enum_int},
- {Py_nb_index, (void *)enum_int},
- {Py_tp_base, (void *)&PyType_Type},
- {Py_tp_alloc, (void *)PyType_GenericAlloc},
- {Py_tp_new, (void *)SbkEnumTypeTpNew},
- {Py_tp_free, (void *)PyObject_GC_Del},
-#if PY_VERSION_HEX < 0x03000000
- {Py_tp_repr, (void *)SbkEnumType_repr},
-#endif
- {0, nullptr}
-};
-static PyType_Spec SbkEnumType_Type_spec = {
- "1:Shiboken.EnumType",
- 0, // filled in later
- sizeof(PyMemberDef),
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES,
- SbkEnumType_Type_slots,
-};
-
-
-PyTypeObject *SbkEnumType_TypeF(void)
-{
- static PyTypeObject *type = nullptr;
- if (!type) {
- SbkEnumType_Type_spec.basicsize =
- PepHeapType_SIZE + sizeof(SbkEnumTypePrivate);
- type = reinterpret_cast<PyTypeObject *>(SbkType_FromSpec(&SbkEnumType_Type_spec));
- }
- return type;
-}
-
-void SbkEnumTypeDealloc(PyObject *pyObj)
-{
- auto sbkType = reinterpret_cast<SbkEnumType *>(pyObj);
-
- PyObject_GC_UnTrack(pyObj);
-#ifndef Py_LIMITED_API
- Py_TRASHCAN_SAFE_BEGIN(pyObj);
-#endif
- if (PepType_SETP(sbkType)->converter) {
- Shiboken::Conversions::deleteConverter(PepType_SETP(sbkType)->converter);
- }
-#ifndef Py_LIMITED_API
- Py_TRASHCAN_SAFE_END(pyObj);
-#endif
- if (PepRuntime_38_flag) {
- // PYSIDE-939: Handling references correctly.
- // This was not needed before Python 3.8 (Python issue 35810)
- Py_DECREF(Py_TYPE(pyObj));
- }
-}
-
-PyObject *SbkEnumTypeTpNew(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
-{
- auto type_new = reinterpret_cast<newfunc>(PyType_GetSlot(&PyType_Type, Py_tp_new));
- auto newType = reinterpret_cast<SbkEnumType *>(type_new(metatype, args, kwds));
- if (!newType)
- return nullptr;
- return reinterpret_cast<PyObject *>(newType);
-}
-
-} // extern "C"
-
-///////////////////////////////////////////////////////////////
-//
-// PYSIDE-15: Pickling Support for Qt Enum objects
-// This works very well and fixes the issue.
-//
-extern "C" {
-
-static void init_enum(); // forward
-
-static PyObject *enum_unpickler = nullptr;
-
-// Pickling: reduce the Qt Enum object
-static PyObject *enum___reduce__(PyObject *obj)
-{
- init_enum();
- return Py_BuildValue("O(Ni)",
- enum_unpickler,
- Py_BuildValue("s", Py_TYPE(obj)->tp_name),
- PyInt_AS_LONG(obj));
-}
-
-} // extern "C"
-
-namespace Shiboken { namespace Enum {
-
-// Unpickling: rebuild the Qt Enum object
-PyObject *unpickleEnum(PyObject *enum_class_name, PyObject *value)
-{
- Shiboken::AutoDecRef parts(PyObject_CallMethod(enum_class_name,
- const_cast<char *>("split"), const_cast<char *>("s"), "."));
- if (parts.isNull())
- return nullptr;
- PyObject *top_name = PyList_GetItem(parts, 0); // borrowed ref
- if (top_name == nullptr)
- return nullptr;
- PyObject *module = PyImport_GetModule(top_name);
- if (module == nullptr) {
- PyErr_Format(PyExc_ImportError, "could not import module %.200s",
- Shiboken::String::toCString(top_name));
- return nullptr;
- }
- Shiboken::AutoDecRef cur_thing(module);
- int len = PyList_Size(parts);
- for (int idx = 1; idx < len; ++idx) {
- PyObject *name = PyList_GetItem(parts, idx); // borrowed ref
- PyObject *thing = PyObject_GetAttr(cur_thing, name);
- if (thing == nullptr) {
- PyErr_Format(PyExc_ImportError, "could not import Qt Enum type %.200s",
- Shiboken::String::toCString(enum_class_name));
- return nullptr;
- }
- cur_thing.reset(thing);
- }
- PyObject *klass = cur_thing;
- return PyObject_CallFunctionObjArgs(klass, value, nullptr);
-}
-
-} // namespace Enum
-} // namespace Shiboken
-
-extern "C" {
-
-// Initialization
-static bool _init_enum()
-{
- static PyObject *shiboken_name = Py_BuildValue("s", "shiboken2");
- if (shiboken_name == nullptr)
- return false;
- Shiboken::AutoDecRef shibo(PyImport_GetModule(shiboken_name));
- if (shibo.isNull())
- return false;
- Shiboken::AutoDecRef sub(PyObject_GetAttr(shibo, shiboken_name));
- PyObject *mod = sub.object();
- if (mod == nullptr) {
- // We are in the build dir and already in shiboken.
- PyErr_Clear();
- mod = shibo.object();
- }
- enum_unpickler = PyObject_GetAttrString(mod, "_unpickle_enum");
- if (enum_unpickler == nullptr)
- return false;
- return true;
-}
-
-static void init_enum()
-{
- if (!(enum_unpickler || _init_enum()))
- Py_FatalError("could not load enum pickling helper function");
-}
-
-static PyMethodDef SbkEnumObject_Methods[] = {
- {const_cast<char *>("__reduce__"), reinterpret_cast<PyCFunction>(enum___reduce__),
- METH_NOARGS, nullptr},
- {nullptr, nullptr, 0, nullptr} // Sentinel
-};
-
-} // extern "C"
-
-//
-///////////////////////////////////////////////////////////////
-
-namespace Shiboken {
-
-class DeclaredEnumTypes
-{
-public:
- DeclaredEnumTypes(const DeclaredEnumTypes &) = delete;
- DeclaredEnumTypes(DeclaredEnumTypes &&) = delete;
- DeclaredEnumTypes &operator=(const DeclaredEnumTypes &) = delete;
- DeclaredEnumTypes &operator=(DeclaredEnumTypes &&) = delete;
-
- DeclaredEnumTypes();
- ~DeclaredEnumTypes();
- static DeclaredEnumTypes &instance();
- void addEnumType(PyTypeObject *type);
-
-private:
- std::vector<PyTypeObject *> m_enumTypes;
-};
-
-namespace Enum {
-
-bool check(PyObject *pyObj)
-{
- return Py_TYPE(Py_TYPE(pyObj)) == SbkEnumType_TypeF();
-}
-
-PyObject *getEnumItemFromValue(PyTypeObject *enumType, long itemValue)
-{
- PyObject *key, *value;
- Py_ssize_t pos = 0;
- PyObject *values = PyDict_GetItem(enumType->tp_dict, Shiboken::PyName::values());
-
- while (PyDict_Next(values, &pos, &key, &value)) {
- auto *obj = reinterpret_cast<SbkEnumObject *>(value);
- if (obj->ob_value == itemValue) {
- Py_INCREF(value);
- return value;
- }
- }
- return nullptr;
-}
-
-static PyTypeObject *createEnum(const char *fullName, const char *cppName,
- const char */* shortName */,
- PyTypeObject *flagsType)
-{
- PyTypeObject *enumType = newTypeWithName(fullName, cppName, flagsType);
- if (PyType_Ready(enumType) < 0) {
- Py_XDECREF(enumType);
- return nullptr;
- }
- return enumType;
-}
-
-PyTypeObject *createGlobalEnum(PyObject *module, const char *name, const char *fullName, const char *cppName, PyTypeObject *flagsType)
-{
- PyTypeObject *enumType = createEnum(fullName, cppName, name, flagsType);
- if (enumType && PyModule_AddObject(module, name, reinterpret_cast<PyObject *>(enumType)) < 0) {
- Py_DECREF(enumType);
- return nullptr;
- }
- if (flagsType && PyModule_AddObject(module, PepType_GetNameStr(flagsType),
- reinterpret_cast<PyObject *>(flagsType)) < 0) {
- Py_DECREF(enumType);
- return nullptr;
- }
- return enumType;
-}
-
-PyTypeObject *createScopedEnum(SbkObjectType *scope, const char *name, const char *fullName, const char *cppName, PyTypeObject *flagsType)
-{
- PyTypeObject *enumType = createEnum(fullName, cppName, name, flagsType);
- if (enumType && PyDict_SetItemString(reinterpret_cast<PyTypeObject *>(scope)->tp_dict, name,
- reinterpret_cast<PyObject *>(enumType)) < 0) {
- Py_DECREF(enumType);
- return nullptr;
- }
- if (flagsType && PyDict_SetItemString(reinterpret_cast<PyTypeObject *>(scope)->tp_dict,
- PepType_GetNameStr(flagsType),
- reinterpret_cast<PyObject *>(flagsType)) < 0) {
- Py_DECREF(enumType);
- return nullptr;
- }
- return enumType;
-}
-
-static PyObject *createEnumItem(PyTypeObject *enumType, const char *itemName, long itemValue)
-{
- PyObject *enumItem = newItem(enumType, itemValue, itemName);
- if (PyDict_SetItemString(enumType->tp_dict, itemName, enumItem) < 0) {
- Py_DECREF(enumItem);
- return nullptr;
- }
- return enumItem;
-}
-
-bool createGlobalEnumItem(PyTypeObject *enumType, PyObject *module, const char *itemName, long itemValue)
-{
- PyObject *enumItem = createEnumItem(enumType, itemName, itemValue);
- if (!enumItem)
- return false;
- int ok = PyModule_AddObject(module, itemName, enumItem);
- Py_DECREF(enumItem);
- return ok >= 0;
-}
-
-bool createScopedEnumItem(PyTypeObject *enumType, PyTypeObject *scope,
- const char *itemName, long itemValue)
-{
- PyObject *enumItem = createEnumItem(enumType, itemName, itemValue);
- if (!enumItem)
- return false;
- int ok = PyDict_SetItemString(reinterpret_cast<PyTypeObject *>(scope)->tp_dict, itemName, enumItem);
- Py_DECREF(enumItem);
- return ok >= 0;
-}
-
-bool createScopedEnumItem(PyTypeObject *enumType, SbkObjectType *scope, const char *itemName, long itemValue)
-{
- return createScopedEnumItem(enumType, reinterpret_cast<PyTypeObject *>(scope), itemName, itemValue);
-}
-
-PyObject *
-newItem(PyTypeObject *enumType, long itemValue, const char *itemName)
-{
- bool newValue = true;
- SbkEnumObject *enumObj;
- if (!itemName) {
- enumObj = reinterpret_cast<SbkEnumObject *>(
- getEnumItemFromValue(enumType, itemValue));
- if (enumObj)
- return reinterpret_cast<PyObject *>(enumObj);
-
- newValue = false;
- }
-
- enumObj = PyObject_New(SbkEnumObject, enumType);
- if (!enumObj)
- return nullptr;
-
- enumObj->ob_name = itemName ? PyBytes_FromString(itemName) : nullptr;
- enumObj->ob_value = itemValue;
-
- if (newValue) {
- PyObject *values = PyDict_GetItem(enumType->tp_dict, Shiboken::PyName::values());
- if (!values) {
- values = PyDict_New();
- PyDict_SetItem(enumType->tp_dict, Shiboken::PyName::values(), values);
- Py_DECREF(values); // ^ values still alive, because setitem increfs it
- }
- PyDict_SetItemString(values, itemName, reinterpret_cast<PyObject *>(enumObj));
- }
-
- return reinterpret_cast<PyObject *>(enumObj);
-}
-
-static PyType_Slot SbkNewType_slots[] = {
- {Py_tp_repr, (void *)SbkEnumObject_repr},
- {Py_tp_str, (void *)SbkEnumObject_repr},
- {Py_tp_getset, (void *)SbkEnumGetSetList},
- {Py_tp_methods, (void *)SbkEnumObject_Methods},
- {Py_tp_new, (void *)SbkEnum_tp_new},
- {Py_nb_add, (void *)enum_add},
- {Py_nb_subtract, (void *)enum_subtract},
- {Py_nb_multiply, (void *)enum_multiply},
-#ifndef IS_PY3K
- {Py_nb_divide, (void *)enum_divide},
-#endif
- {Py_nb_positive, (void *)enum_int},
-#ifdef IS_PY3K
- {Py_nb_bool, (void *)enum_bool},
-#else
- {Py_nb_nonzero, (void *)enum_bool},
- {Py_nb_long, (void *)enum_int},
-#endif
- {Py_nb_and, (void *)enum_and},
- {Py_nb_xor, (void *)enum_xor},
- {Py_nb_or, (void *)enum_or},
- {Py_nb_int, (void *)enum_int},
- {Py_nb_index, (void *)enum_int},
- {Py_tp_richcompare, (void *)enum_richcompare},
- {Py_tp_hash, (void *)enum_hash},
- {Py_tp_dealloc, (void *)enum_object_dealloc},
- {0, nullptr}
-};
-static PyType_Spec SbkNewType_spec = {
- "missing Enum name", // to be inserted later
- sizeof(SbkEnumObject),
- 0,
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES,
- SbkNewType_slots,
-};
-
-static void
-copyNumberMethods(PyTypeObject *flagsType,
- PyType_Slot number_slots[],
- int *pidx)
-{
- int idx = *pidx;
-#define PUT_SLOT(name) \
- number_slots[idx].slot = (name); \
- number_slots[idx].pfunc = PyType_GetSlot(flagsType, (name)); \
- ++idx;
-
- PUT_SLOT(Py_nb_absolute);
- PUT_SLOT(Py_nb_add);
- PUT_SLOT(Py_nb_and);
-#ifdef IS_PY3K
- PUT_SLOT(Py_nb_bool);
-#else
- PUT_SLOT(Py_nb_nonzero);
-#endif
- PUT_SLOT(Py_nb_divmod);
- PUT_SLOT(Py_nb_float);
- PUT_SLOT(Py_nb_floor_divide);
- PUT_SLOT(Py_nb_index);
- PUT_SLOT(Py_nb_inplace_add);
- PUT_SLOT(Py_nb_inplace_and);
- PUT_SLOT(Py_nb_inplace_floor_divide);
- PUT_SLOT(Py_nb_inplace_lshift);
- PUT_SLOT(Py_nb_inplace_multiply);
- PUT_SLOT(Py_nb_inplace_or);
- PUT_SLOT(Py_nb_inplace_power);
- PUT_SLOT(Py_nb_inplace_remainder);
- PUT_SLOT(Py_nb_inplace_rshift);
- PUT_SLOT(Py_nb_inplace_subtract);
- PUT_SLOT(Py_nb_inplace_true_divide);
- PUT_SLOT(Py_nb_inplace_xor);
- PUT_SLOT(Py_nb_int);
- PUT_SLOT(Py_nb_invert);
- PUT_SLOT(Py_nb_lshift);
- PUT_SLOT(Py_nb_multiply);
- PUT_SLOT(Py_nb_negative);
- PUT_SLOT(Py_nb_or);
- PUT_SLOT(Py_nb_positive);
- PUT_SLOT(Py_nb_power);
- PUT_SLOT(Py_nb_remainder);
- PUT_SLOT(Py_nb_rshift);
- PUT_SLOT(Py_nb_subtract);
- PUT_SLOT(Py_nb_true_divide);
- PUT_SLOT(Py_nb_xor);
-#ifndef IS_PY3K
- PUT_SLOT(Py_nb_long);
- PUT_SLOT(Py_nb_divide);
-#endif
-#undef PUT_SLOT
- *pidx = idx;
-}
-
-PyTypeObject *
-newTypeWithName(const char *name,
- const char *cppName,
- PyTypeObject *numbers_fromFlag)
-{
- // Careful: SbkType_FromSpec does not allocate the string.
- PyType_Slot newslots[99] = {}; // enough but not too big for the stack
- auto *newspec = new PyType_Spec;
- newspec->name = strdup(name);
- newspec->basicsize = SbkNewType_spec.basicsize;
- newspec->itemsize = SbkNewType_spec.itemsize;
- newspec->flags = SbkNewType_spec.flags;
- // we must append all the number methods, so rebuild everything:
- int idx = 0;
- while (SbkNewType_slots[idx].slot) {
- newslots[idx].slot = SbkNewType_slots[idx].slot;
- newslots[idx].pfunc = SbkNewType_slots[idx].pfunc;
- ++idx;
- }
- if (numbers_fromFlag)
- copyNumberMethods(numbers_fromFlag, newslots, &idx);
- newspec->slots = newslots;
- auto *type = reinterpret_cast<PyTypeObject *>(SbkType_FromSpec(newspec));
- Py_TYPE(type) = SbkEnumType_TypeF();
-
- auto *enumType = reinterpret_cast<SbkEnumType *>(type);
- PepType_SETP(enumType)->cppName = cppName;
- PepType_SETP(enumType)->converterPtr = &PepType_SETP(enumType)->converter;
- DeclaredEnumTypes::instance().addEnumType(type);
- return type;
-}
-
-const char *getCppName(PyTypeObject *enumType)
-{
- assert(Py_TYPE(enumType) == SbkEnumType_TypeF());
- return PepType_SETP(reinterpret_cast<SbkEnumType *>(enumType))->cppName;
-}
-
-long int getValue(PyObject *enumItem)
-{
- assert(Shiboken::Enum::check(enumItem));
- return reinterpret_cast<SbkEnumObject *>(enumItem)->ob_value;
-}
-
-void setTypeConverter(PyTypeObject *enumType, SbkConverter *converter)
-{
- //reinterpret_cast<SbkEnumType *>(enumType)->converter = converter;
- *PepType_SGTP(enumType)->converter = converter;
-}
-
-SbkConverter *getTypeConverter(PyTypeObject *enumType)
-{
- //return reinterpret_cast<SbkEnumType *>(enumType)->converter;
- return *PepType_SGTP(enumType)->converter;
-}
-
-} // namespace Enum
-
-DeclaredEnumTypes &DeclaredEnumTypes::instance()
-{
- static DeclaredEnumTypes me;
- return me;
-}
-
-DeclaredEnumTypes::DeclaredEnumTypes() = default;
-
-DeclaredEnumTypes::~DeclaredEnumTypes()
-{
- /*
- * PYSIDE-595: This was "delete *it;" before introducing 'SbkType_FromSpec'.
- * XXX what should I do now?
- * Refcounts in tests are 30 or 0 at end.
- * When I add the default tp_dealloc, we get negative refcounts!
- * So right now I am doing nothing. Surely wrong but no crash.
- * See also the comment in function 'createGlobalEnumItem'.
- */
- // for (PyTypeObject *o : m_enumTypes)
- // fprintf(stderr, "ttt %d %s\n", Py_REFCNT(o), o->tp_name);
- m_enumTypes.clear();
-}
-
-void DeclaredEnumTypes::addEnumType(PyTypeObject *type)
-{
- m_enumTypes.push_back(type);
-}
-
-}
diff --git a/sources/shiboken2/libshiboken/sbkenum.h b/sources/shiboken2/libshiboken/sbkenum.h
deleted file mode 100644
index c294c17d9..000000000
--- a/sources/shiboken2/libshiboken/sbkenum.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKENUM_H
-#define SBKENUM_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-extern "C"
-{
-
-extern LIBSHIBOKEN_API PyTypeObject *SbkEnumType_TypeF(void);
-struct SbkObjectType;
-struct SbkConverter;
-struct SbkEnumType;
-struct SbkEnumTypePrivate;
-
-} // extern "C"
-
-namespace Shiboken
-{
-
-inline bool isShibokenEnum(PyObject *pyObj)
-{
- return Py_TYPE(Py_TYPE(pyObj)) == SbkEnumType_TypeF();
-}
-
-namespace Enum
-{
- LIBSHIBOKEN_API bool check(PyObject *obj);
- /**
- * Creates a new enum type (and its flags type, if any is given)
- * and registers it to Python and adds it to \p module.
- * \param module Module to where the new enum type will be added.
- * \param name Name of the enum.
- * \param fullName Name of the enum that includes all scope information (e.g.: "module.Enum").
- * \param cppName Full qualified C++ name of the enum.
- * \param flagsType Optional Python type for the flags associated with the enum.
- * \return The new enum type or NULL if it fails.
- */
- LIBSHIBOKEN_API PyTypeObject *createGlobalEnum(PyObject *module,
- const char *name,
- const char *fullName,
- const char *cppName,
- PyTypeObject *flagsType = nullptr);
- /// This function does the same as createGlobalEnum, but adds the enum to a Shiboken type or namespace.
- LIBSHIBOKEN_API PyTypeObject *createScopedEnum(SbkObjectType *scope,
- const char *name,
- const char *fullName,
- const char *cppName,
- PyTypeObject *flagsType = nullptr);
-
- /**
- * Creates a new enum item for a given enum type and adds it to \p module.
- * \param enumType Enum type to where the new enum item will be added.
- * \param module Module to where the enum type of the new enum item belongs.
- * \param itemName Name of the enum item.
- * \param itemValue Numerical value of the enum item.
- * \return true if everything goes fine, false if it fails.
- */
- LIBSHIBOKEN_API bool createGlobalEnumItem(PyTypeObject *enumType, PyObject *module, const char *itemName, long itemValue);
- /// This function does the same as createGlobalEnumItem, but adds the enum to a Shiboken type or namespace.
- LIBSHIBOKEN_API bool createScopedEnumItem(PyTypeObject *enumType, PyTypeObject *scope,
- const char *itemName, long itemValue);
- LIBSHIBOKEN_API bool createScopedEnumItem(PyTypeObject *enumType, SbkObjectType *scope, const char *itemName, long itemValue);
-
- LIBSHIBOKEN_API PyObject *newItem(PyTypeObject *enumType, long itemValue, const char *itemName = nullptr);
-
- LIBSHIBOKEN_API PyTypeObject *newTypeWithName(const char *name, const char *cppName,
- PyTypeObject *numbers_fromFlag=nullptr);
- LIBSHIBOKEN_API const char *getCppName(PyTypeObject *type);
-
- LIBSHIBOKEN_API long getValue(PyObject *enumItem);
- LIBSHIBOKEN_API PyObject *getEnumItemFromValue(PyTypeObject *enumType, long itemValue);
-
- /// Sets the enum's type converter.
- LIBSHIBOKEN_API void setTypeConverter(PyTypeObject *enumType, SbkConverter *converter);
- /// Returns the converter assigned to the enum \p type.
- LIBSHIBOKEN_API SbkConverter *getTypeConverter(PyTypeObject *enumType);
-
- LIBSHIBOKEN_API PyObject *unpickleEnum(PyObject *, PyObject *);
-}
-
-} // namespace Shiboken
-
-#endif // SKB_PYENUM_H
diff --git a/sources/shiboken2/libshiboken/sbkmodule.cpp b/sources/shiboken2/libshiboken/sbkmodule.cpp
deleted file mode 100644
index 9321725d6..000000000
--- a/sources/shiboken2/libshiboken/sbkmodule.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkmodule.h"
-#include "basewrapper.h"
-#include "bindingmanager.h"
-#include <unordered_map>
-
-/// This hash maps module objects to arrays of Python types.
-using ModuleTypesMap = std::unordered_map<PyObject *, PyTypeObject **> ;
-
-/// This hash maps module objects to arrays of converters.
-using ModuleConvertersMap = std::unordered_map<PyObject *, SbkConverter **>;
-
-/// All types produced in imported modules are mapped here.
-static ModuleTypesMap moduleTypes;
-static ModuleConvertersMap moduleConverters;
-
-namespace Shiboken
-{
-namespace Module
-{
-
-PyObject *import(const char *moduleName)
-{
- PyObject *sysModules = PyImport_GetModuleDict();
- PyObject *module = PyDict_GetItemString(sysModules, moduleName);
- if (module)
- Py_INCREF(module);
- else
- module = PyImport_ImportModule(moduleName);
-
- if (!module)
- PyErr_Format(PyExc_ImportError,"could not import module '%s'", moduleName);
-
- return module;
-}
-
-PyObject *create(const char *moduleName, void *moduleData)
-{
- Shiboken::init();
-#ifndef IS_PY3K
- return Py_InitModule(moduleName, reinterpret_cast<PyMethodDef *>(moduleData));
-#else
- return PyModule_Create(reinterpret_cast<PyModuleDef *>(moduleData));
-#endif
-}
-
-void registerTypes(PyObject *module, PyTypeObject **types)
-{
- auto iter = moduleTypes.find(module);
- if (iter == moduleTypes.end())
- moduleTypes.insert(std::make_pair(module, types));
-}
-
-PyTypeObject **getTypes(PyObject *module)
-{
- auto iter = moduleTypes.find(module);
- return (iter == moduleTypes.end()) ? 0 : iter->second;
-}
-
-void registerTypeConverters(PyObject *module, SbkConverter **converters)
-{
- auto iter = moduleConverters.find(module);
- if (iter == moduleConverters.end())
- moduleConverters.insert(std::make_pair(module, converters));
-}
-
-SbkConverter **getTypeConverters(PyObject *module)
-{
- auto iter = moduleConverters.find(module);
- return (iter == moduleConverters.end()) ? 0 : iter->second;
-}
-
-} } // namespace Shiboken::Module
diff --git a/sources/shiboken2/libshiboken/sbkmodule.h b/sources/shiboken2/libshiboken/sbkmodule.h
deleted file mode 100644
index 75eff5a79..000000000
--- a/sources/shiboken2/libshiboken/sbkmodule.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBK_MODULE_H
-#define SBK_MODULE_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-#if PY_MAJOR_VERSION >= 3
- #define SBK_MODULE_INIT_ERROR 0
- #define SBK_MODULE_INIT_FUNCTION_BEGIN(ModuleName) \
- extern "C" SBK_EXPORT_MODULE PyObject *PyInit_##ModuleName() {
-
- #define SBK_MODULE_INIT_FUNCTION_END \
- return module; }
-#else
- #define SBK_MODULE_INIT_ERROR
- #define SBK_MODULE_INIT_FUNCTION_BEGIN(ModuleName) \
- extern "C" SBK_EXPORT_MODULE void init##ModuleName() {
-
- #define SBK_MODULE_INIT_FUNCTION_END \
- }
-#endif
-
-extern "C"
-{
-struct SbkConverter;
-}
-
-namespace Shiboken {
-namespace Module {
-
-/**
- * Imports and returns the module named \p moduleName, or a NULL pointer in case of failure.
- * If the module is already imported, it increments its reference count before returning it.
- * \returns the module specified in \p moduleName or NULL if an error occurs.
- */
-LIBSHIBOKEN_API PyObject *import(const char *moduleName);
-
-/**
- * Creates a new Python module named \p moduleName using the information passed in \p moduleData.
- * In fact, \p moduleData expects a "PyMethodDef *" object, but that's for Python 2. A "void*"
- * was preferred to make this work with future Python 3 support.
- * \returns a newly created module.
- */
-LIBSHIBOKEN_API PyObject *create(const char *moduleName, void *moduleData);
-
-/**
- * Registers the list of types created by \p module.
- * \param module Module where the types were created.
- * \param types Array of PyTypeObject *objects representing the types created on \p module.
- */
-LIBSHIBOKEN_API void registerTypes(PyObject *module, PyTypeObject **types);
-
-/**
- * Retrieves the array of types.
- * \param module Module where the types were created.
- * \returns A pointer to the PyTypeObject *array of types.
- */
-LIBSHIBOKEN_API PyTypeObject **getTypes(PyObject *module);
-
-/**
- * Registers the list of converters created by \p module for non-wrapper types.
- * \param module Module where the converters were created.
- * \param converters Array of SbkConverter *objects representing the converters created on \p module.
- */
-LIBSHIBOKEN_API void registerTypeConverters(PyObject *module, SbkConverter **converters);
-
-/**
- * Retrieves the array of converters.
- * \param module Module where the converters were created.
- * \returns A pointer to the SbkConverter *array of converters.
- */
-LIBSHIBOKEN_API SbkConverter **getTypeConverters(PyObject *module);
-
-} } // namespace Shiboken::Module
-
-#endif // SBK_MODULE_H
diff --git a/sources/shiboken2/libshiboken/sbknumpyarrayconverter.cpp b/sources/shiboken2/libshiboken/sbknumpyarrayconverter.cpp
deleted file mode 100644
index 996968fa1..000000000
--- a/sources/shiboken2/libshiboken/sbknumpyarrayconverter.cpp
+++ /dev/null
@@ -1,308 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkarrayconverter.h"
-#include "helper.h"
-#include "sbkconverter.h"
-#include "sbkconverter_p.h"
-#include "sbkarrayconverter_p.h"
-
-#include <numpy/arrayobject.h>
-
-#include <algorithm>
-#include <iostream>
-#include <cstdint>
-
-enum { debugNumPy = 0 };
-
-struct TypeCharMapping
-{
- NPY_TYPES type;
- const char *name;
-};
-
-static const TypeCharMapping typeCharMappings[] = {
-{NPY_BYTE, "NPY_BYTE"},
-{NPY_UBYTE, "NPY_UBYTE"},
-{NPY_SHORT, "NPY_SHORT"},
-{NPY_USHORT, "NPY_USHORT"},
-{NPY_INT, "NPY_INT"},
-{NPY_UINT, "NPY_UINT"},
-{NPY_LONG, "NPY_LONG"},
-{NPY_ULONG, "NPY_ULONG"},
-{NPY_LONGLONG, "NPY_LONGLONG"},
-{NPY_ULONGLONG, "NPY_ULONGLONG"},
-{NPY_FLOAT, "NPY_FLOAT"},
-{NPY_DOUBLE, "NPY_DOUBLE"}
-};
-
-const char *npTypeName(npy_intp t)
-{
- const TypeCharMapping *end = typeCharMappings + sizeof(typeCharMappings) / sizeof(typeCharMappings[0]);
- const TypeCharMapping *result =
- std::find_if(typeCharMappings, end,
- [t] (const TypeCharMapping &m) { return m.type == t; });
- return result != end ? result->name : nullptr;
-}
-
-std::ostream &operator<<(std::ostream &str, PyArrayObject *o)
-{
- str << "PyArrayObject(";
- if (o) {
- const npy_intp npType = PyArray_TYPE(o);
- if (const char *name = npTypeName(npType))
- str << name;
- else
- str << "type=" << npType;
- const int nDim = PyArray_NDIM(o);
- const npy_intp *dims = PyArray_DIMS(o);
- for (int d = 0; d < nDim; ++d)
- str << '[' << dims[d] << ']';
- str << ", ";
- const int flags = PyArray_FLAGS(o);
- if ((flags & NPY_ARRAY_C_CONTIGUOUS) != 0)
- str << " NPY_ARRAY_C_CONTIGUOUS";
- if ((flags & NPY_ARRAY_F_CONTIGUOUS) != 0)
- str << " NPY_ARRAY_F_CONTIGUOUS";
- if ((flags & NPY_ARRAY_OWNDATA) != 0)
- str << " NPY_ARRAY_OWNDATA";
- if ((flags & NPY_ARRAY_FORCECAST) != 0)
- str << " NPY_ARRAY_FORCECAST";
- if ((flags & NPY_ARRAY_ENSURECOPY) != 0)
- str << " NPY_ARRAY_ENSURECOPY";
- if ((flags & NPY_ARRAY_ENSUREARRAY) != 0)
- str << " NPY_ARRAY_ENSUREARRAY";
- if ((flags & NPY_ARRAY_ELEMENTSTRIDES) != 0)
- str << " NPY_ARRAY_ELEMENTSTRIDES";
- if ((flags & NPY_ARRAY_ALIGNED) != 0)
- str << " NPY_ARRAY_ALIGNED";
- if ((flags & NPY_ARRAY_NOTSWAPPED) != 0)
- str << " NPY_ARRAY_NOTSWAPPED";
- if ((flags & NPY_ARRAY_WRITEABLE) != 0)
- str << " NPY_ARRAY_WRITEABLE";
- if ((flags & NPY_ARRAY_UPDATEIFCOPY) != 0)
- str << " NPY_ARRAY_UPDATEIFCOPY";
- } else {
- str << '0';
- }
- str << ')';
- return str;
-}
-
-namespace Shiboken {
-namespace Conversions {
-
-// Internals from sbkarrayconverter.cpp
-SbkArrayConverter *createArrayConverter(IsArrayConvertibleToCppFunc toCppCheckFunc);
-void setArrayTypeConverter(int index, int dimension, SbkArrayConverter *c);
-SbkArrayConverter *unimplementedArrayConverter();
-
-template <int dimension>
-static bool isPrimitiveArray(PyObject *pyIn, int expectedNpType)
-{
- if (!PyArray_Check(pyIn))
- return false;
- auto *pya = reinterpret_cast<PyArrayObject *>(pyIn);
- if (debugNumPy) {
- std::cerr << __FUNCTION__ << "(expectedNpType=" << expectedNpType;
- if (const char *name = npTypeName(expectedNpType))
- std::cerr << " (" << name << ')';
- std::cerr << ' ' << pya << '\n';
- }
-
- const int dim = PyArray_NDIM(pya);
- if (dim != dimension) {
- warning(PyExc_RuntimeWarning, 0,
- "%d dimensional numpy array passed to a function expecting a %d dimensional array.",
- dim, dimension);
- return false;
- }
- if ((PyArray_FLAGS(pya) & NPY_ARRAY_C_CONTIGUOUS) == 0) {
- warning(PyExc_RuntimeWarning, 0,
- "Cannot handle numpy arrays that do not have NPY_ARRAY_C_CONTIGUOUS set.");
- return false;
- }
- const int actualNpType = PyArray_TYPE(pya);
- if (actualNpType != expectedNpType) {
- const char *actualName = npTypeName(actualNpType);
- const char *expectedName = npTypeName(expectedNpType);
- warning(PyExc_RuntimeWarning, 0,
- "A numpy array of type %d (%s) was passed to a function expecting type %d (%s).",
- actualNpType, actualName ? actualName : "",
- expectedNpType, expectedName ? expectedName : "");
- return false;
- }
- return true;
-}
-
-static inline bool primitiveArrayCheck1(PyObject *pyIn, int expectedNpType, int expectedSize)
-{
- if (!isPrimitiveArray<1>(pyIn, expectedNpType))
- return false;
- if (expectedSize >= 0) {
- auto *pya = reinterpret_cast<PyArrayObject *>(pyIn);
- const int size = int(PyArray_DIMS(pya)[0]);
- if (size < expectedSize) {
- warning(PyExc_RuntimeWarning, 0, "A numpy array of size %d was passed to a function expects %d.",
- size, expectedSize);
- return false;
- }
- }
- return true;
-}
-
-// Convert one-dimensional array
-template <class T>
-static void convertArray1(PyObject *pyIn, void *cppOut)
-{
- auto *handle = reinterpret_cast<ArrayHandle<T> *>(cppOut);
- auto *pya = reinterpret_cast<PyArrayObject *>(pyIn);
- const npy_intp size = PyArray_DIMS(pya)[0];
- if (debugNumPy)
- std::cerr << __FUNCTION__ << ' ' << size << '\n';
- handle->setData(reinterpret_cast<T *>(PyArray_DATA(pya)), size_t(size));
-}
-
-// Convert 2 dimensional array
-template <class T>
-static void convertArray2(PyObject *pyIn, void *cppOut)
-{
- typedef typename Array2Handle<T, 1>::RowType RowType;
- auto *handle = reinterpret_cast<Array2Handle<T, 1> *>(cppOut);
- auto *pya = reinterpret_cast<PyArrayObject *>(pyIn);
- handle->setData(reinterpret_cast<RowType *>(PyArray_DATA(pya)));
-}
-
-template <class T, int NumPyType>
-static PythonToCppFunc checkArray1(PyObject *pyIn, int dim1, int /* dim2 */)
-{
- return primitiveArrayCheck1(pyIn, NumPyType, dim1) ? convertArray1<T> : nullptr;
-}
-
-static inline bool primitiveArrayCheck2(PyObject *pyIn, int expectedNpType, int expectedDim1, int expectedDim2)
-{
- if (!isPrimitiveArray<2>(pyIn, expectedNpType))
- return false;
- if (expectedDim2 >= 0) {
- auto *pya = reinterpret_cast<PyArrayObject *>(pyIn);
- const int dim1 = int(PyArray_DIMS(pya)[0]);
- const int dim2 = int(PyArray_DIMS(pya)[1]);
- if (dim1 != expectedDim1 || dim2 != expectedDim2) {
- warning(PyExc_RuntimeWarning, 0, "A numpy array of size %dx%d was passed to a function that expects %dx%d.",
- dim1, dim2, expectedDim1, expectedDim2);
- return false;
- }
- }
- return true;
-}
-
-template <class T, int NumPyType>
-static PythonToCppFunc checkArray2(PyObject *pyIn, int dim1, int dim2)
-{
- return primitiveArrayCheck2(pyIn, NumPyType, dim1, dim2) ? convertArray2<T> : nullptr;
-}
-
-template <class T>
-static void setOrExtendArrayConverter(int dimension, IsArrayConvertibleToCppFunc toCppCheckFunc)
-{
- SbkArrayConverter *arrayConverter = ArrayTypeConverter<T>(dimension);
- if (arrayConverter == unimplementedArrayConverter()) {
- arrayConverter = createArrayConverter(toCppCheckFunc);
- setArrayTypeConverter(ArrayTypeIndex<T>::index, dimension, arrayConverter);
- } else {
- arrayConverter->toCppConversions.push_back(toCppCheckFunc);
- }
-}
-
-// Extend the converters for primitive type one-dimensional arrays by NumPy ones.
-template <class T, int NumPyType>
-static inline void extendArrayConverter1()
-{
- setOrExtendArrayConverter<T>(1, checkArray1<T, NumPyType>);
-}
-
-// Extend the converters for primitive type one-dimensional arrays by NumPy ones.
-template <class T, int NumPyType>
-static inline void extendArrayConverter2()
-{
- setOrExtendArrayConverter<T>(2, checkArray2<T, NumPyType>);
-}
-
-void initNumPyArrayConverters()
-{
- // Expanded from macro "import_array" in __multiarray_api.h
- // Make sure to read about the magic defines PY_ARRAY_UNIQUE_SYMBOL etc.,
- // when changing this or spreading the code over several source files.
- if (_import_array() < 0) {
- if (debugNumPy)
- PyErr_Print();
- PyErr_Clear();
- return;
- }
- // Extend the converters for primitive types by NumPy ones.
- extendArrayConverter1<short, NPY_SHORT>();
- extendArrayConverter2<short, NPY_SHORT>();
- extendArrayConverter1<unsigned short, NPY_SHORT>();
- extendArrayConverter2<unsigned short, NPY_SHORT>();
- extendArrayConverter1<int, NPY_INT>();
- extendArrayConverter2<int, NPY_INT>();
- extendArrayConverter1<unsigned int, NPY_UINT>();
- extendArrayConverter2<unsigned int, NPY_UINT>();
- extendArrayConverter1<long long, NPY_LONGLONG>();
- extendArrayConverter2<long long, NPY_LONGLONG>();
- extendArrayConverter1<unsigned long long, NPY_ULONGLONG>();
- if (sizeof(long) == 8) { // UNIX/LP64: ints typically come as long
- extendArrayConverter1<long long, NPY_LONG>();
- extendArrayConverter2<long long, NPY_LONG>();
- extendArrayConverter1<unsigned long long, NPY_ULONG>();
- extendArrayConverter2<unsigned long long, NPY_ULONG>();
- } else if (sizeof(long) == sizeof(int)) {
- extendArrayConverter1<int, NPY_LONG>();
- extendArrayConverter1<unsigned, NPY_ULONG>();
- extendArrayConverter2<int, NPY_LONG>();
- extendArrayConverter2<unsigned, NPY_ULONG>();
- }
- extendArrayConverter1<float, NPY_FLOAT>();
- extendArrayConverter2<float, NPY_FLOAT>();
- extendArrayConverter1<double, NPY_DOUBLE>();
- extendArrayConverter2<double, NPY_DOUBLE>();
-}
-
-} // namespace Conversions
-} // namespace Shiboken
diff --git a/sources/shiboken2/libshiboken/sbkpython.h b/sources/shiboken2/libshiboken/sbkpython.h
deleted file mode 100644
index 9dd1e712e..000000000
--- a/sources/shiboken2/libshiboken/sbkpython.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKPYTHON_H
-#define SBKPYTHON_H
-
-#include "sbkversion.h"
-
-// Qt's "slots" macro collides with the "slots" member variables
-// used in some Python structs. For compilers that support push_macro,
-// temporarily undefine it.
-#if defined(slots) && (defined(__GNUC__) || defined(_MSC_VER) || defined(__clang__))
-# pragma push_macro("slots")
-# undef slots
-/*
- * Python 2 has function _Py_Mangle directly in Python.h .
- * This creates wrong language binding unless we define 'extern "C"' here.
- */
-extern "C" {
-/*
- * Python 2 uses the "register" keyword, which is deprecated in C++ 11
- * and forbidden in C++17.
- */
-# if defined(__clang__)
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wdeprecated-register"
-# endif
-
-# include <Python.h>
-
-# if defined(__clang__)
-# pragma clang diagnostic pop
-# endif
-}
-# include <structmember.h>
-// Now we have the usual variables from Python.h .
-# include "python25compat.h"
-# include "shibokenmacros.h"
-// "pep384impl.h" may nowhere be included but in this file.
-# include "pep384impl.h"
-# include "typespec.h"
-# pragma pop_macro("slots")
-
-#else
-
-extern "C" {
-/*
- * Python 2 uses the "register" keyword, which is deprecated in C++ 11
- * and forbidden in C++17.
- */
-# if defined(__clang__)
-# pragma clang diagnostic push
-# pragma clang diagnostic ignored "-Wdeprecated-register"
-# endif
-
-# include <Python.h>
-
-# if defined(__clang__)
-# pragma clang diagnostic pop
-# endif
-}
-# include <structmember.h>
-// Now we have the usual variables from Python.h .
-# include "python25compat.h"
-# include "shibokenmacros.h"
-// "pep384impl.h" may nowhere be included but in this file.
-# include "pep384impl.h"
-# include "typespec.h"
-#endif
-
-#if PY_MAJOR_VERSION >= 3
- #define IS_PY3K
-
- #define PyInt_Type PyLong_Type
- #define PyInt_Check PyLong_Check
- #define PyInt_CheckExact PyLong_CheckExact
- #define PyInt_FromString PyLong_FromString
- #define PyInt_FromSsize_t PyLong_FromSsize_t
- #define PyInt_FromSize_t PyLong_FromSize_t
- #define PyInt_AS_LONG PyLong_AS_LONG
- #define PyInt_AsUnsignedLongLongMask PyLong_AsLongLong
- #define PyInt_FromLong PyLong_FromLong
- #define PyInt_AsLong PyLong_AsLong
- #define SbkNumber_Check PyNumber_Check
- #define Py_TPFLAGS_CHECKTYPES 0
-
- #define SBK_NB_BOOL(x) (x).nb_bool
- #define SBK_PyMethod_New PyMethod_New
- #define PyInt_AsSsize_t(x) PyLong_AsSsize_t(x)
- #define PyString_Type PyUnicode_Type
-
- // In Python 3, Py_TPFLAGS_DEFAULT contains Py_TPFLAGS_HAVE_VERSION_TAG,
- // which will trigger the attribute cache, which is not intended in Qt for Python.
- // Use a customized Py_TPFLAGS_DEFAULT by defining Py_TPFLAGS_HAVE_VERSION_TAG = 0.
- #undef Py_TPFLAGS_HAVE_VERSION_TAG
- #define Py_TPFLAGS_HAVE_VERSION_TAG (0)
-
-#else
- // Note: if there wasn't for the old-style classes, only a PyNumber_Check would suffice.
- #define SbkNumber_Check(X) \
- (PyNumber_Check(X) && (!PyInstance_Check(X) || PyObject_HasAttrString(X, "__trunc__")))
- #define SBK_NB_BOOL(x) (x).nb_nonzero
- #define SBK_PyMethod_New(X, Y) PyMethod_New(X, Y, reinterpret_cast<PyObject *>(Py_TYPE(Y)))
-
- #define Py_hash_t long
-#endif
-
-#endif
diff --git a/sources/shiboken2/libshiboken/sbkstaticstrings.cpp b/sources/shiboken2/libshiboken/sbkstaticstrings.cpp
deleted file mode 100644
index c19665176..000000000
--- a/sources/shiboken2/libshiboken/sbkstaticstrings.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkstaticstrings.h"
-#include "sbkstaticstrings_p.h"
-#include "sbkstring.h"
-
-#define STATIC_STRING_IMPL(funcName, value) \
-PyObject *funcName() \
-{ \
- static PyObject *const s = Shiboken::String::createStaticString(value); \
- return s; \
-}
-
-namespace Shiboken
-{
-namespace PyName {
-// exported:
-STATIC_STRING_IMPL(dumps, "dumps")
-STATIC_STRING_IMPL(loads, "loads")
-STATIC_STRING_IMPL(result, "result")
-STATIC_STRING_IMPL(values, "values")
-
-// Internal:
-STATIC_STRING_IMPL(classmethod, "classmethod")
-STATIC_STRING_IMPL(compile, "compile");
-STATIC_STRING_IMPL(function, "function")
-STATIC_STRING_IMPL(marshal, "marshal")
-STATIC_STRING_IMPL(method, "method")
-STATIC_STRING_IMPL(mro, "mro")
-STATIC_STRING_IMPL(overload, "overload")
-STATIC_STRING_IMPL(staticmethod, "staticmethod")
-} // namespace PyName
-
-namespace PyMagicName {
-// exported:
-STATIC_STRING_IMPL(class_, "__class__")
-STATIC_STRING_IMPL(ecf, "__ecf__")
-STATIC_STRING_IMPL(file, "__file__")
-STATIC_STRING_IMPL(module, "__module__")
-STATIC_STRING_IMPL(name, "__name__")
-STATIC_STRING_IMPL(qualname, "__qualname__")
-
-// Internal:
-STATIC_STRING_IMPL(base, "__base__")
-STATIC_STRING_IMPL(bases, "__bases__")
-STATIC_STRING_IMPL(builtins, "__builtins__")
-STATIC_STRING_IMPL(code, "__code__")
-STATIC_STRING_IMPL(dictoffset, "__dictoffset__")
-STATIC_STRING_IMPL(func, "__func__")
-STATIC_STRING_IMPL(func_kind, "__func_kind__")
-STATIC_STRING_IMPL(iter, "__iter__")
-STATIC_STRING_IMPL(mro, "__mro__")
-STATIC_STRING_IMPL(new_, "__new__")
-STATIC_STRING_IMPL(objclass, "__objclass__")
-STATIC_STRING_IMPL(self, "__self__")
-STATIC_STRING_IMPL(signature, "__signature__")
-STATIC_STRING_IMPL(weakrefoffset, "__weakrefoffset__")
-} // namespace PyMagicName
-} // namespace Shiboken
diff --git a/sources/shiboken2/libshiboken/sbkstaticstrings.h b/sources/shiboken2/libshiboken/sbkstaticstrings.h
deleted file mode 100644
index 07d6cc60a..000000000
--- a/sources/shiboken2/libshiboken/sbkstaticstrings.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKSTATICSTRINGS_H
-#define SBKSTATICSTRINGS_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-namespace Shiboken
-{
-// Some often-used strings
-namespace PyName
-{
-LIBSHIBOKEN_API PyObject *dumps();
-LIBSHIBOKEN_API PyObject *loads();
-LIBSHIBOKEN_API PyObject *result();
-LIBSHIBOKEN_API PyObject *values();
-} // namespace PyName
-
-namespace PyMagicName
-{
-LIBSHIBOKEN_API PyObject *class_();
-LIBSHIBOKEN_API PyObject *ecf();
-LIBSHIBOKEN_API PyObject *file();
-LIBSHIBOKEN_API PyObject *module();
-LIBSHIBOKEN_API PyObject *name();
-LIBSHIBOKEN_API PyObject *qualname();
-} // namespace PyMagicName
-} // namespace Shiboken
-
-#endif // SBKSTATICSTRINGS_H
diff --git a/sources/shiboken2/libshiboken/sbkstaticstrings_p.h b/sources/shiboken2/libshiboken/sbkstaticstrings_p.h
deleted file mode 100644
index 12c11376f..000000000
--- a/sources/shiboken2/libshiboken/sbkstaticstrings_p.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-namespace Shiboken
-{
-namespace PyName
-{
-PyObject *classmethod();
-PyObject *compile();
-PyObject *function();
-PyObject *marshal();
-PyObject *method();
-PyObject *mro();
-PyObject *overload();
-PyObject *staticmethod();
-} // namespace PyName
-namespace PyMagicName
-{
-PyObject *base();
-PyObject *bases();
-PyObject *builtins();
-PyObject *code();
-PyObject *dictoffset();
-PyObject *func();
-PyObject *func_kind();
-PyObject *iter();
-PyObject *module();
-PyObject *mro();
-PyObject *new_();
-PyObject *objclass();
-PyObject *self();
-PyObject *signature();
-PyObject *weakrefoffset();
-} // namespace PyMagicName
-} // namespace Shiboken
diff --git a/sources/shiboken2/libshiboken/sbkstring.cpp b/sources/shiboken2/libshiboken/sbkstring.cpp
deleted file mode 100644
index 38bb105d0..000000000
--- a/sources/shiboken2/libshiboken/sbkstring.cpp
+++ /dev/null
@@ -1,272 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkstring.h"
-#include "sbkstaticstrings_p.h"
-#include "autodecref.h"
-
-#include <vector>
-
-namespace Shiboken
-{
-
-namespace String
-{
-
-// PYSIDE-795: Redirecting PySequence to Iterable
-bool checkIterable(PyObject *obj)
-{
- return PyObject_HasAttr(obj, Shiboken::PyMagicName::iter());
-}
-
-bool checkType(PyTypeObject *type)
-{
- return type == &PyUnicode_Type
-#if PY_MAJOR_VERSION < 3
- || type == &PyString_Type
-#endif
- ;
-}
-
-bool check(PyObject *obj)
-{
- return obj == Py_None ||
-#if PY_MAJOR_VERSION < 3
- PyString_Check(obj) ||
-#endif
- PyUnicode_Check(obj);
-}
-
-bool checkChar(PyObject *pyobj)
-{
- return check(pyobj) && (len(pyobj) == 1);
-}
-
-bool isConvertible(PyObject *obj)
-{
- return check(obj);
-}
-
-PyObject *fromCString(const char *value)
-{
-#ifdef IS_PY3K
- return PyUnicode_FromString(value);
-#else
- return PyBytes_FromString(value);
-#endif
-}
-
-PyObject *fromCString(const char *value, int len)
-{
-#ifdef IS_PY3K
- return PyUnicode_FromStringAndSize(value, len);
-#else
- return PyBytes_FromStringAndSize(value, len);
-#endif
-}
-
-const char *toCString(PyObject *str, Py_ssize_t *len)
-{
- if (str == Py_None)
- return nullptr;
- if (PyUnicode_Check(str)) {
- if (len) {
- // We need to encode the unicode string into utf8 to know the size of returned char *.
- Shiboken::AutoDecRef uniStr(PyUnicode_AsUTF8String(str));
- *len = PyBytes_GET_SIZE(uniStr.object());
- }
-#ifdef IS_PY3K
- // Return unicode from str instead of uniStr, because the lifetime of the returned pointer
- // depends on the lifetime of str.
- return _PepUnicode_AsString(str);
-#else
- str = PyUnicode_AsUTF8String(str);
- if (str == NULL) {
- return NULL;
- }
- return PyString_AsString(str);
-#endif
- }
- if (PyBytes_Check(str)) {
- if (len)
- *len = PyBytes_GET_SIZE(str);
- return PyBytes_AS_STRING(str);
- }
- return nullptr;
-}
-
-bool concat(PyObject **val1, PyObject *val2)
-{
- if (PyUnicode_Check(*val1) && PyUnicode_Check(val2)) {
- PyObject *result = PyUnicode_Concat(*val1, val2);
- Py_DECREF(*val1);
- *val1 = result;
- return true;
- }
-
- if (PyBytes_Check(*val1) && PyBytes_Check(val2)) {
- PyBytes_Concat(val1, val2);
- return true;
- }
-
-#if PY_MAJOR_VERSION < 3
- if (PyString_Check(*val1) && PyString_Check(val2)) {
- PyString_Concat(val1, val2);
- return true;
- }
-#endif
- return false;
-}
-
-PyObject *fromFormat(const char *format, ...)
-{
- va_list argp;
- va_start(argp, format);
- PyObject *result = nullptr;
-#ifdef IS_PY3K
- result = PyUnicode_FromFormatV(format, argp);
-#else
- result = PyString_FromFormatV(format, argp);
-#endif
- va_end(argp);
- return result;
-}
-
-PyObject *fromStringAndSize(const char *str, Py_ssize_t size)
-{
-#ifdef IS_PY3K
- return PyUnicode_FromStringAndSize(str, size);
-#else
- return PyString_FromStringAndSize(str, size);
-#endif
-}
-
-int compare(PyObject *val1, const char *val2)
-{
- if (PyUnicode_Check(val1))
-#ifdef IS_PY3K
- return PyUnicode_CompareWithASCIIString(val1, val2);
-#else
- {
- PyObject *uVal2 = PyUnicode_FromString(val2);
- bool result = PyUnicode_Compare(val1, uVal2);
- Py_XDECREF(uVal2);
- return result;
- }
- if (PyString_Check(val1))
- return strcmp(PyString_AS_STRING(val1), val2);
-#endif
- return 0;
-
-}
-
-Py_ssize_t len(PyObject *str)
-{
- if (str == Py_None)
- return 0;
-
- if (PyUnicode_Check(str))
- return PepUnicode_GetLength(str);
-
- if (PyBytes_Check(str))
- return PyBytes_GET_SIZE(str);
- return 0;
-}
-
-///////////////////////////////////////////////////////////////////////
-//
-// Implementation of efficient Python strings
-// ------------------------------------------
-//
-// Instead of repetitively executing
-//
-// PyObject *attr = PyObject_GetAttrString(obj, "__name__");
-//
-// a helper of the form
-//
-// PyObject *name()
-// {
-// static PyObject *const s = Shiboken::String::createStaticString("__name__");
-// return result;
-// }
-//
-// can now be implemented, which registers the string into a static set avoiding
-// repetitive string creation. The resulting code looks like:
-//
-// PyObject *attr = PyObject_GetAttr(obj, name());
-//
-// Missing:
-// There is no finalization for the string structures, yet.
-// But this is a global fault in shiboken. We are missing a true
-// finalization like in all other modules.
-
-using StaticStrings = std::vector<PyObject *>;
-
-static StaticStrings &staticStrings()
-{
- static StaticStrings result;
- return result;
-}
-
-PyObject *createStaticString(const char *str)
-{
-#if PY_VERSION_HEX >= 0x03000000
- PyObject *result = PyUnicode_InternFromString(str);
-#else
- PyObject *result = PyString_InternFromString(str);
-#endif
- if (result == nullptr) {
- // This error is never checked, but also very unlikely. Report and exit.
- PyErr_Print();
- Py_FatalError("unexpected error in createStaticString()");
- }
- staticStrings().push_back(result);
- return result;
-}
-
-void finalizeStaticStrings() // Currently unused
-{
- auto &list = staticStrings();
- for (auto s : list)
- Py_DECREF(s);
- list.clear();
-}
-
-} // namespace String
-} // namespace Shiboken
diff --git a/sources/shiboken2/libshiboken/sbkstring.h b/sources/shiboken2/libshiboken/sbkstring.h
deleted file mode 100644
index 84d7768c5..000000000
--- a/sources/shiboken2/libshiboken/sbkstring.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKSTRING_H
-#define SBKSTRING_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-namespace Shiboken
-{
-namespace String
-{
- LIBSHIBOKEN_API bool check(PyObject *obj);
- LIBSHIBOKEN_API bool checkIterable(PyObject *obj);
- LIBSHIBOKEN_API bool checkType(PyTypeObject *obj);
- LIBSHIBOKEN_API bool checkChar(PyObject *obj);
- LIBSHIBOKEN_API bool isConvertible(PyObject *obj);
- LIBSHIBOKEN_API PyObject *fromCString(const char *value);
- LIBSHIBOKEN_API PyObject *fromCString(const char *value, int len);
- LIBSHIBOKEN_API const char *toCString(PyObject *str, Py_ssize_t *len = nullptr);
- LIBSHIBOKEN_API bool concat(PyObject **val1, PyObject *val2);
- LIBSHIBOKEN_API PyObject *fromFormat(const char *format, ...);
- LIBSHIBOKEN_API PyObject *fromStringAndSize(const char *str, Py_ssize_t size);
- LIBSHIBOKEN_API int compare(PyObject *val1, const char *val2);
- LIBSHIBOKEN_API Py_ssize_t len(PyObject *str);
- LIBSHIBOKEN_API PyObject *createStaticString(const char *str);
-
-} // namespace String
-} // namespace Shiboken
-
-
-#endif
-
-
diff --git a/sources/shiboken2/libshiboken/sbkversion.h.in b/sources/shiboken2/libshiboken/sbkversion.h.in
deleted file mode 100644
index 99ee7f93e..000000000
--- a/sources/shiboken2/libshiboken/sbkversion.h.in
+++ /dev/null
@@ -1,53 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKVERSION_H
-#define SBKVERSION_H
-
-#define SHIBOKEN_VERSION "@shiboken_MAJOR_VERSION@.@shiboken_MINOR_VERSION@.@shiboken_MICRO_VERSION@"
-#define SHIBOKEN_MAJOR_VERSION @shiboken_MAJOR_VERSION@
-#define SHIBOKEN_MINOR_VERSION @shiboken_MINOR_VERSION@
-#define SHIBOKEN_MICRO_VERSION @shiboken_MICRO_VERSION@
-#define SHIBOKEN_RELEASE_LEVEL "final"
-#define SHIBOKEN_SERIAL 0
-#define PYTHON_VERSION_MAJOR @PYTHON_VERSION_MAJOR@
-#define PYTHON_VERSION_MINOR @PYTHON_VERSION_MINOR@
-#define PYTHON_VERSION_PATCH @PYTHON_VERSION_PATCH@
-
-#endif
diff --git a/sources/shiboken2/libshiboken/shiboken.h b/sources/shiboken2/libshiboken/shiboken.h
deleted file mode 100644
index 0d2d6b0a6..000000000
--- a/sources/shiboken2/libshiboken/shiboken.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SHIBOKEN_H
-#define SHIBOKEN_H
-
-#include "sbkpython.h"
-#include "autodecref.h"
-#include "basewrapper.h"
-#include "bindingmanager.h"
-#include "gilstate.h"
-#include "threadstatesaver.h"
-#include "helper.h"
-#include "sbkarrayconverter.h"
-#include "sbkconverter.h"
-#include "sbkenum.h"
-#include "sbkmodule.h"
-#include "sbkstring.h"
-#include "sbkstaticstrings.h"
-#include "shibokenmacros.h"
-#include "shibokenbuffer.h"
-
-#endif // SHIBOKEN_H
-
diff --git a/sources/shiboken2/libshiboken/shibokenbuffer.cpp b/sources/shiboken2/libshiboken/shibokenbuffer.cpp
deleted file mode 100644
index dd6e46320..000000000
--- a/sources/shiboken2/libshiboken/shibokenbuffer.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "shibokenbuffer.h"
-#include <cstdlib>
-#include <cstring>
-
-bool Shiboken::Buffer::checkType(PyObject *pyObj)
-{
-#ifdef IS_PY3K
- return PyObject_CheckBuffer(pyObj) != 0;
-#else
- return PyObject_CheckReadBuffer(pyObj) != 0;
-#endif
-}
-
-void *Shiboken::Buffer::getPointer(PyObject *pyObj, Py_ssize_t *size)
-{
- const void *buffer = nullptr;
-#ifdef IS_PY3K
- Py_buffer view;
- if (PyObject_GetBuffer(pyObj, &view, PyBUF_ND) == 0) {
- if (size)
- *size = view.len;
- buffer = view.buf;
- PyBuffer_Release(&view);
- return view.buf;
- }
- return nullptr;
-#else
- Py_ssize_t bufferSize = 0;
-
- PyObject_AsReadBuffer(pyObj, &buffer, &bufferSize);
-
- if (size)
- *size = bufferSize;
-#endif
- return const_cast<void *>(buffer);
-}
-
-PyObject *Shiboken::Buffer::newObject(void *memory, Py_ssize_t size, Type type)
-{
- if (size == 0)
- Py_RETURN_NONE;
-#ifdef IS_PY3K
- Py_buffer view;
- memset(&view, 0, sizeof(Py_buffer));
- view.buf = memory;
- view.len = size;
- view.readonly = type == Shiboken::Buffer::ReadOnly;
- view.ndim = 1;
- view.itemsize = sizeof(char);
- Py_ssize_t shape[] = { size };
- view.shape = shape;
- // Pep384: This is way too complicated and impossible with the limited api:
- //return PyMemoryView_FromBuffer(&view);
- return PyMemoryView_FromMemory(reinterpret_cast<char *>(view.buf),
- size, type == ReadOnly ? PyBUF_READ : PyBUF_WRITE);
-#else
- return type == ReadOnly ? PyBuffer_FromMemory(memory, size) : PyBuffer_FromReadWriteMemory(memory, size);
-#endif
-}
-
-PyObject *Shiboken::Buffer::newObject(const void *memory, Py_ssize_t size)
-{
- return newObject(const_cast<void *>(memory), size, ReadOnly);
-}
diff --git a/sources/shiboken2/libshiboken/shibokenbuffer.h b/sources/shiboken2/libshiboken/shibokenbuffer.h
deleted file mode 100644
index dc9f8d89f..000000000
--- a/sources/shiboken2/libshiboken/shibokenbuffer.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SHIBOKEN_BUFFER_H
-#define SHIBOKEN_BUFFER_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-namespace Shiboken
-{
-
-namespace Buffer
-{
- enum Type {
- ReadOnly,
- WriteOnly,
- ReadWrite
- };
-
- /**
- * Creates a new Python buffer pointing to a contiguous memory block at
- * \p memory of size \p size.
- */
- LIBSHIBOKEN_API PyObject *newObject(void *memory, Py_ssize_t size, Type type);
-
- /**
- * Creates a new <b>read only</b> Python buffer pointing to a contiguous memory block at
- * \p memory of size \p size.
- */
- LIBSHIBOKEN_API PyObject *newObject(const void *memory, Py_ssize_t size);
-
- /**
- * Check if is ok to use \p pyObj as argument in all function under Shiboken::Buffer namespace.
- */
- LIBSHIBOKEN_API bool checkType(PyObject *pyObj);
-
- /**
- * Returns a pointer to the memory pointed by the buffer \p pyObj, \p size is filled with the buffer
- * size if not null.
- *
- * If the \p pyObj is a non-contiguous buffer a Python error is set.
- */
- LIBSHIBOKEN_API void *getPointer(PyObject *pyObj, Py_ssize_t *size = nullptr);
-
-} // namespace Buffer
-} // namespace Shiboken
-
-#endif
diff --git a/sources/shiboken2/libshiboken/shibokenmacros.h b/sources/shiboken2/libshiboken/shibokenmacros.h
deleted file mode 100644
index 7bebd85e4..000000000
--- a/sources/shiboken2/libshiboken/shibokenmacros.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SHIBOKENMACROS_H
-#define SHIBOKENMACROS_H
-
-// LIBSHIBOKEN_API macro is used for the public API symbols.
-#if defined _WIN32
- #if LIBSHIBOKEN_EXPORTS
- #define LIBSHIBOKEN_API __declspec(dllexport)
- #else
- #ifdef _MSC_VER
- #define LIBSHIBOKEN_API __declspec(dllimport)
- #endif
- #endif
- #define SBK_DEPRECATED(func) __declspec(deprecated) func
-#elif __GNUC__ >= 4
- #define LIBSHIBOKEN_API __attribute__ ((visibility("default")))
- #define SBK_DEPRECATED(func) func __attribute__ ((deprecated))
-#endif
-
-#ifndef LIBSHIBOKEN_API
- #define LIBSHIBOKEN_API
- #define SBK_DEPRECATED(func) func
-#endif
-
-#endif
diff --git a/sources/shiboken2/libshiboken/signature.cpp b/sources/shiboken2/libshiboken/signature.cpp
deleted file mode 100644
index ba1fc119e..000000000
--- a/sources/shiboken2/libshiboken/signature.cpp
+++ /dev/null
@@ -1,1262 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "basewrapper.h"
-#include "autodecref.h"
-#include "sbkstring.h"
-#include "sbkstaticstrings.h"
-#include "sbkstaticstrings_p.h"
-
-extern "C"
-{
-
-/*
- * The documentation is located in file signature_doc.rst
- */
-#include "signature.h"
-#include <structmember.h>
-
-// These constants were needed in former versions of the module:
-#define PYTHON_HAS_QUALNAME (PY_VERSION_HEX >= 0x03030000)
-#define PYTHON_HAS_WEAKREF_PYCFUNCTION (PY_VERSION_HEX >= 0x030500A0)
-#define PYTHON_IS_PYTHON3 (PY_VERSION_HEX >= 0x03000000)
-#define PYTHON_HAS_KEYWORDONLY (PYTHON_IS_PYTHON3)
-#define PYTHON_USES_PERCENT_V_FORMAT (PYTHON_IS_PYTHON3)
-#define PYTHON_USES_D_COMMON (PY_VERSION_HEX >= 0x03020000)
-#define PYTHON_HAS_DESCR_REDUCE (PY_VERSION_HEX >= 0x03040000)
-#define PYTHON_HAS_METH_REDUCE (PYTHON_HAS_DESCR_REDUCE)
-#define PYTHON_NEEDS_ITERATOR_FLAG (!PYTHON_IS_PYTHON3)
-#define PYTHON_EXPOSES_METHODDESCR (PYTHON_IS_PYTHON3)
-#define PYTHON_NO_TYPE_IN_FUNCTIONS (!PYTHON_IS_PYTHON3 || Py_LIMITED_API)
-#define PYTHON_HAS_INT_AND_LONG (!PYTHON_IS_PYTHON3)
-
-// These constants are still in use:
-#define PYTHON_USES_UNICODE (PY_VERSION_HEX >= 0x03000000)
-
-typedef struct safe_globals_struc {
- // init part 1: get arg_dict
- PyObject *helper_module;
- PyObject *arg_dict;
- PyObject *map_dict;
- PyObject *value_dict; // for writing signatures
- // init part 2: run module
- PyObject *pyside_type_init_func;
- PyObject *create_signature_func;
- PyObject *seterror_argument_func;
- PyObject *make_helptext_func;
- PyObject *finish_import_func;
-} safe_globals_struc, *safe_globals;
-
-static safe_globals pyside_globals = nullptr;
-
-static PyObject *GetTypeKey(PyObject *ob);
-
-static PyObject *GetSignature_Function(PyObject *, PyObject *);
-static PyObject *GetSignature_TypeMod(PyObject *, PyObject *);
-static PyObject *GetSignature_Wrapper(PyObject *, PyObject *);
-static PyObject *get_signature(PyObject *self, PyObject *args);
-static PyObject *get_signature_intern(PyObject *ob, PyObject *modifier);
-
-static PyObject *PySide_BuildSignatureProps(PyObject *class_mod);
-
-static void init_module_1(void);
-static void init_module_2(void);
-
-static PyObject *
-CreateSignature(PyObject *props, PyObject *key)
-{
- /*
- * Here is the new function to create all signatures. It simply calls
- * into Python and creates a signature object directly.
- * This is so much simpler than using all the attributes explicitly
- * to support '_signature_is_functionlike()'.
- */
- return PyObject_CallFunction(pyside_globals->create_signature_func,
- const_cast<char *>("(OO)"), props, key);
-}
-
-typedef PyObject *(*signaturefunc)(PyObject *, PyObject *);
-
-static PyObject *
-_get_written_signature(signaturefunc sf, PyObject *ob, PyObject *modifier)
-{
- /*
- * Be a writable Attribute, but have a computed value.
- *
- * If a signature has not been written, call the signature function.
- * If it has been written, return the written value.
- * After __del__ was called, the function value re-appears.
- *
- * Note: This serves also for the new version that does not allow any
- * assignment if we have a computed value. We only need to check if
- * a computed value exists and then forbid writing.
- * See pyside_set___signature
- */
- PyObject *ret = PyDict_GetItem(pyside_globals->value_dict, ob);
- if (ret == nullptr) {
- return ob == nullptr ? nullptr : sf(ob, modifier);
- }
- Py_INCREF(ret);
- return ret;
-}
-
-static PyObject *
-pyside_cf_get___signature__(PyObject *func, PyObject *modifier)
-{
- init_module_2();
- return _get_written_signature(GetSignature_Function, func, modifier);
-}
-
-static PyObject *
-pyside_sm_get___signature__(PyObject *sm, PyObject *modifier)
-{
- init_module_2();
- Shiboken::AutoDecRef func(PyObject_GetAttr(sm, Shiboken::PyMagicName::func()));
- if (Py_TYPE(func) == PepFunction_TypePtr)
- return PyObject_GetAttr(func, Shiboken::PyMagicName::signature());
- return _get_written_signature(GetSignature_Function, func, modifier);
-}
-
-static PyObject *
-_get_class_of_cf(PyObject *ob_cf)
-{
- PyObject *selftype = PyCFunction_GET_SELF(ob_cf);
- if (selftype == nullptr) {
- selftype = PyDict_GetItem(pyside_globals->map_dict, ob_cf);
- if (selftype == nullptr) {
- // This must be an overloaded function that we handled special.
- Shiboken::AutoDecRef special(Py_BuildValue("(OO)", ob_cf, Shiboken::PyName::overload()));
- selftype = PyDict_GetItem(pyside_globals->map_dict, special);
- if (selftype == nullptr) {
- // This is probably a module function. We will return type(None).
- selftype = Py_None;
- }
- }
- }
-
- PyObject *obtype_mod = (PyType_Check(selftype) || PyModule_Check(selftype))
- ? selftype : reinterpret_cast<PyObject *>(Py_TYPE(selftype));
- Py_INCREF(obtype_mod);
- return obtype_mod;
-}
-
-static PyObject *
-_get_class_of_sm(PyObject *ob_sm)
-{
- Shiboken::AutoDecRef func(PyObject_GetAttr(ob_sm, Shiboken::PyMagicName::func()));
- return _get_class_of_cf(func);
-}
-
-static PyObject *
-_get_class_of_descr(PyObject *ob)
-{
- return PyObject_GetAttr(ob, Shiboken::PyMagicName::objclass());
-}
-
-static PyObject *
-GetClassOrModOf(PyObject *ob)
-{
- /*
- * Return the type or module of a function or type.
- * The purpose is finally to use the name of the object.
- */
- if (PyType_Check(ob)) {
- // PySide-928: The type case must do refcounting like the others as well.
- Py_INCREF(ob);
- return ob;
- }
- if (PyType_IsSubtype(Py_TYPE(ob), &PyCFunction_Type))
- return _get_class_of_cf(ob);
- if (Py_TYPE(ob) == PepStaticMethod_TypePtr)
- return _get_class_of_sm(ob);
- if (Py_TYPE(ob) == PepMethodDescr_TypePtr)
- return _get_class_of_descr(ob);
- if (Py_TYPE(ob) == &PyWrapperDescr_Type)
- return _get_class_of_descr(ob);
- Py_FatalError("unexpected type in GetClassOrModOf");
- return nullptr;
-}
-
-static PyObject *
-get_funcname(PyObject *ob)
-{
- PyObject *func = ob;
- if (Py_TYPE(ob) == PepStaticMethod_TypePtr)
- func = PyObject_GetAttr(ob, Shiboken::PyMagicName::func());
- else
- Py_INCREF(func);
- PyObject *func_name = PyObject_GetAttr(func, Shiboken::PyMagicName::name());
- Py_DECREF(func);
- if (func_name == nullptr)
- Py_FatalError("unexpected name problem in compute_name_key");
- return func_name;
-}
-
-static PyObject *
-compute_name_key(PyObject *ob)
-{
- if (PyType_Check(ob))
- return GetTypeKey(ob);
- Shiboken::AutoDecRef func_name(get_funcname(ob));
- Shiboken::AutoDecRef type_key(GetTypeKey(GetClassOrModOf(ob)));
- return Py_BuildValue("(OO)", type_key.object(), func_name.object());
-}
-
-static int
-build_name_key_to_func(PyObject *obtype)
-{
- auto *type = reinterpret_cast<PyTypeObject *>(obtype);
- PyMethodDef *meth = type->tp_methods;
-
- if (meth == nullptr)
- return 0;
-
- Shiboken::AutoDecRef type_key(GetTypeKey(obtype));
- for (; meth->ml_name != nullptr; meth++) {
- Shiboken::AutoDecRef func(PyCFunction_NewEx(meth, obtype, nullptr));
- Shiboken::AutoDecRef func_name(get_funcname(func));
- Shiboken::AutoDecRef name_key(Py_BuildValue("(OO)", type_key.object(), func_name.object()));
- if (func.isNull() || name_key.isNull()
- || PyDict_SetItem(pyside_globals->map_dict, name_key, func) < 0)
- return -1;
- }
- return 0;
-}
-
-static PyObject *
-name_key_to_func(PyObject *ob)
-{
- /*
- * We build a mapping from name_key to function.
- * This could also be computed directly, but the Limited API
- * makes this impossible. So we always build our own mapping.
- */
- Shiboken::AutoDecRef name_key(compute_name_key(ob));
- if (name_key.isNull())
- Py_RETURN_NONE;
-
- PyObject *ret = PyDict_GetItem(pyside_globals->map_dict, name_key);
- if (ret == nullptr) {
- // do a lazy initialization
- Shiboken::AutoDecRef type_key(GetTypeKey(GetClassOrModOf(ob)));
- PyObject *type = PyDict_GetItem(pyside_globals->map_dict,
- type_key);
- if (type == nullptr)
- Py_RETURN_NONE;
- assert(PyType_Check(type));
- if (build_name_key_to_func(type) < 0)
- return nullptr;
- ret = PyDict_GetItem(pyside_globals->map_dict, name_key);
- }
- Py_XINCREF(ret);
- return ret;
-}
-
-static PyObject *
-pyside_md_get___signature__(PyObject *ob_md, PyObject *modifier)
-{
- init_module_2();
- Shiboken::AutoDecRef func(name_key_to_func(ob_md));
- if (func.object() == Py_None)
- return Py_None;
- if (func.isNull())
- Py_FatalError("missing mapping in MethodDescriptor");
- return pyside_cf_get___signature__(func, modifier);
-}
-
-static PyObject *
-pyside_wd_get___signature__(PyObject *ob, PyObject *modifier)
-{
- init_module_2();
- return _get_written_signature(GetSignature_Wrapper, ob, modifier);
-}
-
-static PyObject *
-pyside_tp_get___signature__(PyObject *obtype_mod, PyObject *modifier)
-{
- init_module_2();
- return _get_written_signature(GetSignature_TypeMod, obtype_mod, modifier);
-}
-
-// forward
-static PyObject *
-GetSignature_Cached(PyObject *props, PyObject *func_kind, PyObject *modifier);
-
-// Helper for __qualname__ which might not always exist in Python 2 (type).
-static PyObject *
-_get_qualname(PyObject *ob)
-{
- // We support __qualname__ for types, only.
- assert(PyType_Check(ob));
- PyObject *name = PyObject_GetAttr(ob, Shiboken::PyMagicName::qualname());
- if (name == nullptr) {
- PyErr_Clear();
- name = PyObject_GetAttr(ob, Shiboken::PyMagicName::name());
- }
- return name;
-}
-
-static PyObject *
-GetTypeKey(PyObject *ob)
-{
- assert(PyType_Check(ob) || PyModule_Check(ob));
- /*
- * We obtain a unique key using the module name and the type name.
- *
- * The type name is a bit funny when modules are nested.
- * Example:
- *
- * "sample.Photon.ValueIdentity" is a class.
- * name: "ValueIdentity"
- * module: "sample.Photon"
- *
- * This is the PyCFunction behavior, as opposed to Python functions.
- */
- // PYSIDE-1286: We use correct __module__ and __qualname__, now.
- Shiboken::AutoDecRef module_name(PyObject_GetAttr(ob, Shiboken::PyMagicName::module()));
- if (module_name.isNull()) {
- // We have no module_name because this is a module ;-)
- PyErr_Clear();
- module_name.reset(PyObject_GetAttr(ob, Shiboken::PyMagicName::name()));
- return Py_BuildValue("O", module_name.object());
- }
- Shiboken::AutoDecRef class_name(_get_qualname(ob));
- if (class_name.isNull()) {
- Py_FatalError("Signature: missing class name in GetTypeKey");
- return nullptr;
- }
- return Py_BuildValue("(OO)", module_name.object(), class_name.object());
-}
-
-static PyObject *empty_dict = nullptr;
-
-static PyObject *
-TypeKey_to_PropsDict(PyObject *type_key, PyObject *obtype)
-{
- PyObject *dict = PyDict_GetItem(pyside_globals->arg_dict, type_key);
- if (dict == nullptr) {
- if (empty_dict == nullptr)
- empty_dict = PyDict_New();
- dict = empty_dict;
- }
- if (!PyDict_Check(dict))
- dict = PySide_BuildSignatureProps(type_key);
- return dict;
-}
-
-static PyObject *
-GetSignature_Function(PyObject *obfunc, PyObject *modifier)
-{
- // make sure that we look into PyCFunction, only...
- if (Py_TYPE(obfunc) == PepFunction_TypePtr)
- Py_RETURN_NONE;
- Shiboken::AutoDecRef obtype_mod(GetClassOrModOf(obfunc));
- Shiboken::AutoDecRef type_key(GetTypeKey(obtype_mod));
- if (type_key.isNull())
- Py_RETURN_NONE;
- PyObject *dict = TypeKey_to_PropsDict(type_key, obtype_mod);
- if (dict == nullptr)
- return nullptr;
- Shiboken::AutoDecRef func_name(PyObject_GetAttr(obfunc, Shiboken::PyMagicName::name()));
- PyObject *props = !func_name.isNull() ? PyDict_GetItem(dict, func_name) : nullptr;
- if (props == nullptr)
- Py_RETURN_NONE;
-
- int flags = PyCFunction_GET_FLAGS(obfunc);
- PyObject *func_kind;
- if (PyModule_Check(obtype_mod))
- func_kind = Shiboken::PyName::function();
- else if (flags & METH_CLASS)
- func_kind = Shiboken::PyName::classmethod();
- else if (flags & METH_STATIC)
- func_kind = Shiboken::PyName::staticmethod();
- else
- func_kind = Shiboken::PyName::method();
- return GetSignature_Cached(props, func_kind, modifier);
-}
-
-static PyObject *
-GetSignature_Wrapper(PyObject *ob, PyObject *modifier)
-{
- Shiboken::AutoDecRef func_name(PyObject_GetAttr(ob, Shiboken::PyMagicName::name()));
- Shiboken::AutoDecRef objclass(PyObject_GetAttr(ob, Shiboken::PyMagicName::objclass()));
- Shiboken::AutoDecRef class_key(GetTypeKey(objclass));
- if (func_name.isNull() || objclass.isNull() || class_key.isNull())
- return nullptr;
- PyObject *dict = TypeKey_to_PropsDict(class_key, objclass);
- if (dict == nullptr)
- return nullptr;
- PyObject *props = PyDict_GetItem(dict, func_name);
- if (props == nullptr)
- Py_RETURN_NONE;
- return GetSignature_Cached(props, Shiboken::PyName::method(), modifier);
-}
-
-static PyObject *
-GetSignature_TypeMod(PyObject *ob, PyObject *modifier)
-{
- Shiboken::AutoDecRef ob_name(PyObject_GetAttr(ob, Shiboken::PyMagicName::name()));
- Shiboken::AutoDecRef ob_key(GetTypeKey(ob));
-
- PyObject *dict = TypeKey_to_PropsDict(ob_key, ob);
- if (dict == nullptr)
- return nullptr;
- PyObject *props = PyDict_GetItem(dict, ob_name);
- if (props == nullptr)
- Py_RETURN_NONE;
- return GetSignature_Cached(props, Shiboken::PyName::method(), modifier);
-}
-
-static PyObject *
-GetSignature_Cached(PyObject *props, PyObject *func_kind, PyObject *modifier)
-{
- // Special case: We want to know the func_kind.
- if (modifier) {
-#if PYTHON_USES_UNICODE
- PyUnicode_InternInPlace(&modifier);
-#else
- PyString_InternInPlace(&modifier);
-#endif
- if (modifier == Shiboken::PyMagicName::func_kind())
- return Py_BuildValue("O", func_kind);
- }
-
- Shiboken::AutoDecRef key(modifier == nullptr
- ? Py_BuildValue("O", func_kind)
- : Py_BuildValue("(OO)", func_kind, modifier));
- PyObject *value = PyDict_GetItem(props, key);
- if (value == nullptr) {
- // we need to compute a signature object
- value = CreateSignature(props, key);
- if (value != nullptr) {
- if (PyDict_SetItem(props, key, value) < 0)
- // this is an error
- return nullptr;
- }
- else {
- // key not found
- Py_RETURN_NONE;
- }
- }
- return Py_INCREF(value), value;
-}
-
-static const char *PySide_CompressedSignaturePackage[] = {
-#include "embed/signature_inc.h"
- };
-
-static const unsigned char PySide_SignatureLoader[] = {
-#include "embed/signature_bootstrap_inc.h"
- };
-
-static safe_globals_struc *
-init_phase_1(void)
-{
- {
- auto *p = reinterpret_cast<safe_globals_struc *>
- (malloc(sizeof(safe_globals_struc)));
- if (p == nullptr)
- goto error;
- /*
- * Initializing module signature_bootstrap.
- * Since we now have an embedding script, we can do this without any
- * Python strings in the C code.
- */
-#ifdef Py_LIMITED_API
- // We must work for multiple versions, so use source code.
-#else
- Shiboken::AutoDecRef marshal_module(PyImport_Import(Shiboken::PyName::marshal()));
- if (marshal_module.isNull())
- goto error;
- Shiboken::AutoDecRef loads(PyObject_GetAttr(marshal_module, Shiboken::PyName::loads()));
- if (loads.isNull())
- goto error;
-#endif
- char *bytes_cast = reinterpret_cast<char *>(
- const_cast<unsigned char *>(PySide_SignatureLoader));
- Shiboken::AutoDecRef bytes(PyBytes_FromStringAndSize(bytes_cast,
- sizeof(PySide_SignatureLoader)));
- if (bytes.isNull())
- goto error;
-#ifdef Py_LIMITED_API
- PyObject *builtins = PyEval_GetBuiltins();
- PyObject *compile = PyDict_GetItem(builtins, Shiboken::PyName::compile());
- if (compile == nullptr)
- goto error;
- Shiboken::AutoDecRef code_obj(PyObject_CallFunction(compile, "Oss",
- bytes.object(), "(builtin)", "exec"));
-#else
- Shiboken::AutoDecRef code_obj(PyObject_CallFunctionObjArgs(
- loads, bytes.object(), nullptr));
-#endif
- if (code_obj.isNull())
- goto error;
- p->helper_module = PyImport_ExecCodeModule(const_cast<char *>
- ("signature_bootstrap"), code_obj);
- if (p->helper_module == nullptr)
- goto error;
- // Initialize the module
- PyObject *mdict = PyModule_GetDict(p->helper_module);
- if (PyDict_SetItem(mdict, Shiboken::PyMagicName::builtins(), PyEval_GetBuiltins()) < 0)
- goto error;
- /*
- * Unpack an embedded ZIP file with more signature modules.
- * They will be loaded later with the zipimporter.
- * Due to MSVC's limitation to 64k strings, we need to assemble pieces.
- */
- const char **block_ptr = (const char **)PySide_CompressedSignaturePackage;
- int npieces = 0;
- PyObject *piece, *zipped_string_sequence = PyList_New(0);
- if (zipped_string_sequence == nullptr)
- return nullptr;
- for (; **block_ptr != 0; ++block_ptr) {
- npieces++;
- // we avoid the string/unicode dilemma by not using PyString_XXX:
- piece = Py_BuildValue("s", *block_ptr);
- if (piece == nullptr || PyList_Append(zipped_string_sequence, piece) < 0)
- goto error;
- }
- if (PyDict_SetItemString(mdict, "zipstring_sequence", zipped_string_sequence) < 0)
- goto error;
- Py_DECREF(zipped_string_sequence);
-
- // build a dict for diverse mappings
- p->map_dict = PyDict_New();
- if (p->map_dict == nullptr)
- goto error;
-
- // build a dict for the prepared arguments
- p->arg_dict = PyDict_New();
- if (p->arg_dict == nullptr
- || PyObject_SetAttrString(p->helper_module, "pyside_arg_dict", p->arg_dict) < 0)
- goto error;
-
- // build a dict for assigned signature values
- p->value_dict = PyDict_New();
- if (p->value_dict == nullptr)
- goto error;
-
- // This function will be disabled until phase 2 is done.
- p->finish_import_func = nullptr;
-
- return p;
- }
-error:
- PyErr_Print();
- Py_FatalError("could not initialize part 1");
- return nullptr;
-}
-
-static int
-init_phase_2(safe_globals_struc *p, PyMethodDef *methods)
-{
- {
- PyMethodDef *ml;
-
- // The single function to be called, but maybe more to come.
- for (ml = methods; ml->ml_name != nullptr; ml++) {
- PyObject *v = PyCFunction_NewEx(ml, nullptr, nullptr);
- if (v == nullptr
- || PyObject_SetAttrString(p->helper_module, ml->ml_name, v) != 0)
- goto error;
- Py_DECREF(v);
- }
- PyObject *bootstrap_func = PyObject_GetAttrString(p->helper_module, "bootstrap");
- if (bootstrap_func == nullptr)
- goto error;
- // The return value of the bootstrap function is the loader module.
- PyObject *loader = PyObject_CallFunction(bootstrap_func, const_cast<char *>("()"));
- if (loader == nullptr)
- goto error;
- // now the loader should be initialized
- p->pyside_type_init_func = PyObject_GetAttrString(loader, "pyside_type_init");
- if (p->pyside_type_init_func == nullptr)
- goto error;
- p->create_signature_func = PyObject_GetAttrString(loader, "create_signature");
- if (p->create_signature_func == nullptr)
- goto error;
- p->seterror_argument_func = PyObject_GetAttrString(loader, "seterror_argument");
- if (p->seterror_argument_func == nullptr)
- goto error;
- p->make_helptext_func = PyObject_GetAttrString(loader, "make_helptext");
- if (p->make_helptext_func == nullptr)
- goto error;
- p->finish_import_func = PyObject_GetAttrString(loader, "finish_import");
- if (p->finish_import_func == nullptr)
- goto error;
- return 0;
- }
-error:
- PyErr_Print();
- Py_FatalError("could not initialize part 2");
- return -1;
-}
-
-static int
-_fixup_getset(PyTypeObject *type, const char *name, PyGetSetDef *new_gsp)
-{
- /*
- * This function pre-fills all fields of the new gsp. We then
- * insert the changed values.
- */
- PyGetSetDef *gsp = type->tp_getset;
- if (gsp != nullptr) {
- for (; gsp->name != nullptr; gsp++) {
- if (strcmp(gsp->name, name) == 0) {
- new_gsp->set = gsp->set;
- new_gsp->doc = gsp->doc;
- new_gsp->closure = gsp->closure;
- return 1; // success
- }
- }
- }
- // staticmethod has just a __doc__ in the class
- assert(strcmp(type->tp_name, "staticmethod") == 0);
- return 0;
-}
-
-static int
-add_more_getsets(PyTypeObject *type, PyGetSetDef *gsp, PyObject **old_descr)
-{
- /*
- * This function is used to assign a new __signature__ attribute,
- * and also to override a __doc__ attribute.
- */
- assert(PyType_Check(type));
- PyType_Ready(type);
- PyObject *dict = type->tp_dict;
- for (; gsp->name != nullptr; gsp++) {
- PyObject *have_descr = PyDict_GetItemString(dict, gsp->name);
- if (have_descr != nullptr) {
- assert(strcmp(gsp->name, "__doc__") == 0);
- Py_INCREF(have_descr);
- *old_descr = have_descr;
- if (!_fixup_getset(type, gsp->name, gsp))
- continue;
- }
- Shiboken::AutoDecRef descr(PyDescr_NewGetSet(type, gsp));
- if (descr.isNull())
- return -1;
- if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
- return -1;
- }
- PyType_Modified(type);
- return 0;
-}
-
-////////////////////////////////////////////////////////////////////////////
-//
-// Augmenting builtin types with a __signature__ attribute.
-//
-// This is a harmless change to Python, similar like __text_signature__.
-// We could avoid it, but then we would need to copy quite some module
-// initialization functions which are pretty version- and word size
-// dependent. I think this little patch is the lesser of the two evils.
-//
-// Please note that in fact we are modifying 'type', the metaclass of all
-// objects, because we add new functionality.
-//
-// Addendum 2019-01-12: We now also compute a docstring from the signature.
-//
-
-// keep the original __doc__ functions
-static PyObject *old_cf_doc_descr = nullptr;
-static PyObject *old_sm_doc_descr = nullptr;
-static PyObject *old_md_doc_descr = nullptr;
-static PyObject *old_tp_doc_descr = nullptr;
-static PyObject *old_wd_doc_descr = nullptr;
-
-static int handle_doc_in_progress = 0;
-
-static PyObject *
-handle_doc(PyObject *ob, PyObject *old_descr)
-{
- init_module_1();
- init_module_2();
- Shiboken::AutoDecRef ob_type_mod(GetClassOrModOf(ob));
- const char *name;
- if (PyModule_Check(ob_type_mod))
- name = PyModule_GetName(ob_type_mod);
- else
- name = reinterpret_cast<PyTypeObject *>(ob_type_mod.object())->tp_name;
- if (handle_doc_in_progress || name == nullptr
- || strncmp(name, "PySide2.", 8) != 0)
- return PyObject_CallMethod(old_descr, const_cast<char *>("__get__"),
- const_cast<char *>("(O)"), ob);
- handle_doc_in_progress++;
- PyObject *res = PyObject_CallFunction(
- pyside_globals->make_helptext_func,
- const_cast<char *>("(O)"), ob);
- handle_doc_in_progress--;
- if (res == nullptr) {
- PyErr_Print();
- Py_FatalError("handle_doc did not receive a result");
- }
- return res;
-}
-
-static PyObject *
-pyside_cf_get___doc__(PyObject *cf) {
- return handle_doc(cf, old_cf_doc_descr);
-}
-
-static PyObject *
-pyside_sm_get___doc__(PyObject *sm) {
- return handle_doc(sm, old_sm_doc_descr);
-}
-
-static PyObject *
-pyside_md_get___doc__(PyObject *md) {
- return handle_doc(md, old_md_doc_descr);
-}
-
-static PyObject *
-pyside_tp_get___doc__(PyObject *tp) {
- return handle_doc(tp, old_tp_doc_descr);
-}
-
-static PyObject *
-pyside_wd_get___doc__(PyObject *wd) {
- return handle_doc(wd, old_wd_doc_descr);
-}
-
-// the default setter for all objects
-static int
-pyside_set___signature__(PyObject *op, PyObject *value)
-{
- // By this additional check, this function refuses write access.
- // We consider both nullptr and Py_None as not been written.
- Shiboken::AutoDecRef has_val(get_signature_intern(op, nullptr));
- if (!(has_val.isNull() || has_val == Py_None)) {
- PyErr_Format(PyExc_AttributeError,
- "Attribute '__signature__' of '%.50s' object is not writable",
- Py_TYPE(op)->tp_name);
- return -1;
- }
- int ret = value == nullptr
- ? PyDict_DelItem(pyside_globals->value_dict, op)
- : PyDict_SetItem(pyside_globals->value_dict, op, value);
- Py_XINCREF(value);
- return ret;
-}
-
-static PyGetSetDef new_PyCFunction_getsets[] = {
- {const_cast<char *>("__doc__"), (getter)pyside_cf_get___doc__},
- {const_cast<char *>("__signature__"), (getter)pyside_cf_get___signature__,
- (setter)pyside_set___signature__},
- {nullptr}
-};
-
-static PyGetSetDef new_PyStaticMethod_getsets[] = {
- {const_cast<char *>("__doc__"), (getter)pyside_sm_get___doc__},
- {const_cast<char *>("__signature__"), (getter)pyside_sm_get___signature__,
- (setter)pyside_set___signature__},
- {nullptr}
-};
-
-static PyGetSetDef new_PyMethodDescr_getsets[] = {
- {const_cast<char *>("__doc__"), (getter)pyside_md_get___doc__},
- {const_cast<char *>("__signature__"), (getter)pyside_md_get___signature__,
- (setter)pyside_set___signature__},
- {nullptr}
-};
-
-static PyGetSetDef new_PyType_getsets[] = {
- {const_cast<char *>("__doc__"), (getter)pyside_tp_get___doc__},
- {const_cast<char *>("__signature__"), (getter)pyside_tp_get___signature__,
- (setter)pyside_set___signature__},
- {nullptr}
-};
-
-static PyGetSetDef new_PyWrapperDescr_getsets[] = {
- {const_cast<char *>("__doc__"), (getter)pyside_wd_get___doc__},
- {const_cast<char *>("__signature__"), (getter)pyside_wd_get___signature__,
- (setter)pyside_set___signature__},
- {nullptr}
-};
-
-////////////////////////////////////////////////////////////////////////////
-//
-// get_signature -- providing a superior interface
-//
-// Additionally to the interface via __signature__, we also provide
-// a general function, which allows for different signature layouts.
-// The "modifier" argument is a string that is passed in from loader.py .
-// Configuration what the modifiers mean is completely in Python.
-//
-
-static PyObject *
-get_signature_intern(PyObject *ob, PyObject *modifier)
-{
- if (PyType_IsSubtype(Py_TYPE(ob), &PyCFunction_Type))
- return pyside_cf_get___signature__(ob, modifier);
- if (Py_TYPE(ob) == PepStaticMethod_TypePtr)
- return pyside_sm_get___signature__(ob, modifier);
- if (Py_TYPE(ob) == PepMethodDescr_TypePtr)
- return pyside_md_get___signature__(ob, modifier);
- if (PyType_Check(ob))
- return pyside_tp_get___signature__(ob, modifier);
- if (Py_TYPE(ob) == &PyWrapperDescr_Type)
- return pyside_wd_get___signature__(ob, modifier);
- return nullptr;
-}
-
-static PyObject *
-get_signature(PyObject * /* self */, PyObject *args)
-{
- PyObject *ob;
- PyObject *modifier = nullptr;
-
- init_module_1();
-
- if (!PyArg_ParseTuple(args, "O|O", &ob, &modifier))
- return nullptr;
- if (Py_TYPE(ob) == PepFunction_TypePtr)
- Py_RETURN_NONE;
- PyObject *ret = get_signature_intern(ob, modifier);
- if (ret != nullptr)
- return ret;
- Py_RETURN_NONE;
-}
-
-////////////////////////////////////////////////////////////////////////////
-//
-// This special Type_Ready does certain initializations earlier with
-// our new version.
-//
-
-#ifndef _WIN32
-////////////////////////////////////////////////////////////////////////////
-// a stack trace for linux-like platforms
-#include <stdio.h>
-#if defined(__GLIBC__)
-# include <execinfo.h>
-#endif
-#include <signal.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-void handler(int sig) {
-#if defined(__GLIBC__)
- void *array[30];
- size_t size;
-
- // get void *'s for all entries on the stack
- size = backtrace(array, 30);
-
- // print out all the frames to stderr
-#endif
- fprintf(stderr, "Error: signal %d:\n", sig);
-#if defined(__GLIBC__)
- backtrace_symbols_fd(array, size, STDERR_FILENO);
-#endif
- exit(1);
-}
-
-////////////////////////////////////////////////////////////////////////////
-#endif // _WIN32
-
-static int
-PySide_PatchTypes(void)
-{
- static int init_done = 0;
-
- if (!init_done) {
- Shiboken::AutoDecRef meth_descr(PyObject_GetAttrString(
- reinterpret_cast<PyObject *>(&PyString_Type), "split"));
- Shiboken::AutoDecRef wrap_descr(PyObject_GetAttrString(
- reinterpret_cast<PyObject *>(Py_TYPE(Py_True)), "__add__"));
- if (meth_descr.isNull() || wrap_descr.isNull()
- || PyType_Ready(Py_TYPE(meth_descr)) < 0
- || add_more_getsets(PepMethodDescr_TypePtr, new_PyMethodDescr_getsets, &old_md_doc_descr) < 0
- || add_more_getsets(&PyCFunction_Type, new_PyCFunction_getsets, &old_cf_doc_descr) < 0
- || add_more_getsets(PepStaticMethod_TypePtr, new_PyStaticMethod_getsets, &old_sm_doc_descr) < 0
- || add_more_getsets(&PyType_Type, new_PyType_getsets, &old_tp_doc_descr) < 0
- || add_more_getsets(Py_TYPE(wrap_descr), new_PyWrapperDescr_getsets, &old_wd_doc_descr) < 0
- )
- return -1;
-#ifndef _WIN32
- // We enable the stack trace in CI, only.
- const char *testEnv = getenv("QTEST_ENVIRONMENT");
- if (testEnv && strstr(testEnv, "ci"))
- signal(SIGSEGV, handler); // install our handler
-#endif // _WIN32
- init_done = 1;
- }
- return 0;
-}
-
-static void
-init_module_1(void)
-{
- static int init_done = 0;
-
- if (!init_done) {
- pyside_globals = init_phase_1();
- if (pyside_globals != nullptr)
- init_done = 1;
- }
-}
-
-static int
-PySide_BuildSignatureArgs(PyObject *obtype_mod, const char *signatures[])
-{
- init_module_1();
- Shiboken::AutoDecRef type_key(GetTypeKey(obtype_mod));
- /*
- * PYSIDE-996: Avoid string overflow in MSVC, which has a limit of
- * 2**15 unicode characters (64 K memory).
- * Instead of one huge string, we take a ssize_t that is the
- * address of a string array. It will not be turned into a real
- * string list until really used by Python. This is quite optimal.
- */
- Shiboken::AutoDecRef numkey(Py_BuildValue("n", signatures));
- if (type_key.isNull() || numkey.isNull()
- || PyDict_SetItem(pyside_globals->arg_dict, type_key, numkey) < 0)
- return -1;
- /*
- * We record also a mapping from type key to type/module. This helps to
- * lazily initialize the Py_LIMITED_API in name_key_to_func().
- */
- return PyDict_SetItem(pyside_globals->map_dict, type_key, obtype_mod) == 0 ? 0 : -1;
-}
-
-static PyMethodDef signature_methods[] = {
- {"get_signature", (PyCFunction)get_signature, METH_VARARGS,
- "get the __signature__, but pass an optional string parameter"},
- {nullptr, nullptr}
-};
-
-static void
-init_module_2(void)
-{
- static int init_done = 0;
-
- if (!init_done) {
- // Phase 2 will call __init__.py which touches a signature, itself.
- // Therefore we set init_done prior to init_phase_2().
- init_done = 1;
- init_phase_2(pyside_globals, signature_methods);
- }
-}
-
-static PyObject *
-_address_to_stringlist(PyObject *numkey)
-{
- ssize_t address = PyNumber_AsSsize_t(numkey, PyExc_ValueError);
- if (address == -1 && PyErr_Occurred())
- return nullptr;
- char **sig_strings = reinterpret_cast<char **>(address);
- PyObject *res_list = PyList_New(0);
- if (res_list == nullptr)
- return nullptr;
- for (; *sig_strings != nullptr; ++sig_strings) {
- char *sig_str = *sig_strings;
- Shiboken::AutoDecRef pystr(Py_BuildValue("s", sig_str));
- if (pystr.isNull() || PyList_Append(res_list, pystr) < 0)
- return nullptr;
- }
- return res_list;
-}
-
-static PyObject *
-PySide_BuildSignatureProps(PyObject *type_key)
-{
- /*
- * Here is the second part of the function.
- * This part will be called on-demand when needed by some attribute.
- * We simply pick up the arguments that we stored here and replace
- * them by the function result.
- */
- init_module_2();
- if (type_key == nullptr)
- return nullptr;
- PyObject *numkey = PyDict_GetItem(pyside_globals->arg_dict, type_key);
- Shiboken::AutoDecRef strings(_address_to_stringlist(numkey));
- if (strings.isNull())
- return nullptr;
- Shiboken::AutoDecRef arg_tup(Py_BuildValue("(OO)", type_key, strings.object()));
- if (arg_tup.isNull())
- return nullptr;
- PyObject *dict = PyObject_CallObject(pyside_globals->pyside_type_init_func, arg_tup);
- if (dict == nullptr) {
- if (PyErr_Occurred())
- return nullptr;
- // No error: return an empty dict.
- if (empty_dict == nullptr)
- empty_dict = PyDict_New();
- return empty_dict;
- }
- // We replace the arguments by the result dict.
- if (PyDict_SetItem(pyside_globals->arg_dict, type_key, dict) < 0)
- return nullptr;
- return dict;
-}
-
-static int _finish_nested_classes(PyObject *dict);
-static int _build_func_to_type(PyObject *obtype);
-
-static int
-PySide_FinishSignatures(PyObject *module, const char *signatures[])
-{
- /*
- * Initialization of module functions and resolving of static methods.
- */
- const char *name = PyModule_GetName(module);
- if (name == nullptr)
- return -1;
-
- // we abuse the call for types, since they both have a __name__ attribute.
- if (PySide_BuildSignatureArgs(module, signatures) < 0)
- return -1;
-
- /*
- * Note: This function crashed when called from PySide_BuildSignatureArgs.
- * Probably this was too early.
- *
- * Pep384: We need to switch this always on since we have no access
- * to the PyCFunction attributes. Therefore I simplified things
- * and always use our own mapping.
- */
- PyObject *key, *func, *obdict = PyModule_GetDict(module);
- Py_ssize_t pos = 0;
-
- while (PyDict_Next(obdict, &pos, &key, &func))
- if (PyCFunction_Check(func))
- if (PyDict_SetItem(pyside_globals->map_dict, func, module) < 0)
- return -1;
- if (_finish_nested_classes(obdict) < 0)
- return -1;
- // The finish_import function will not work the first time since phase 2
- // was not yet run. But that is ok, because the first import is always for
- // the shiboken module (or a test module).
- if (pyside_globals->finish_import_func == nullptr) {
- assert(strncmp(name, "PySide2.", 8) != 0);
- return 0;
- }
- Shiboken::AutoDecRef ret(PyObject_CallFunction(
- pyside_globals->finish_import_func, const_cast<char *>("(O)"), module));
- return ret.isNull() ? -1 : 0;
-}
-
-static int
-_finish_nested_classes(PyObject *obdict)
-{
- PyObject *key, *value, *obtype;
- PyTypeObject *subtype;
- Py_ssize_t pos = 0;
-
- if (obdict == nullptr)
- return -1;
- while (PyDict_Next(obdict, &pos, &key, &value)) {
- if (PyType_Check(value)) {
- obtype = value;
- if (_build_func_to_type(obtype) < 0)
- return -1;
- // now continue with nested cases
- subtype = reinterpret_cast<PyTypeObject *>(obtype);
- if (_finish_nested_classes(subtype->tp_dict) < 0)
- return -1;
- }
- }
- return 0;
-}
-
-static int
-_build_func_to_type(PyObject *obtype)
-{
- /*
- * There is no general way to directly get the type of a static method.
- * On Python 3, the type is hidden in an unused pointer in the
- * PyCFunction structure, but the Limited API does not allow to access
- * this, either.
- *
- * In the end, it was easier to avoid such tricks and build an explicit
- * mapping from function to type.
- *
- * We walk through the method list of the type
- * and record the mapping from static method to this type in a dict.
- * We also check for hidden methods, see below.
- */
- auto *type = reinterpret_cast<PyTypeObject *>(obtype);
- PyObject *dict = type->tp_dict;
- PyMethodDef *meth = type->tp_methods;
-
- if (meth == nullptr)
- return 0;
-
- for (; meth->ml_name != nullptr; meth++) {
- /*
- * It is possible that a method is overwritten by another
- * attribute with the same name. This case was obviously provoked
- * explicitly in "testbinding.TestObject.staticMethodDouble",
- * where instead of the method a "PySide2.QtCore.Signal" object
- * was in the dict.
- * This overlap is also found in regular PySide under
- * "PySide2.QtCore.QProcess.error" where again a signal object is
- * returned. These hidden methods will be opened for the
- * signature module by adding them under the name
- * "{name}.overload".
- */
- PyObject *descr = PyDict_GetItemString(dict, meth->ml_name);
- PyObject *look_attr = meth->ml_flags & METH_STATIC
- ? Shiboken::PyMagicName::func() : Shiboken::PyMagicName::name();
- int check_name = meth->ml_flags & METH_STATIC ? 0 : 1;
- if (descr == nullptr)
- return -1;
-
- // We first check all methods if one is hidden by something else.
- Shiboken::AutoDecRef look(PyObject_GetAttr(descr, look_attr));
- Shiboken::AutoDecRef given(Py_BuildValue("s", meth->ml_name));
- if (look.isNull()
- || (check_name && PyObject_RichCompareBool(look, given, Py_EQ) != 1)) {
- PyErr_Clear();
- Shiboken::AutoDecRef cfunc(PyCFunction_NewEx(meth,
- reinterpret_cast<PyObject *>(type), nullptr));
- if (cfunc.isNull())
- return -1;
- if (meth->ml_flags & METH_STATIC)
- descr = PyStaticMethod_New(cfunc);
- else
- descr = PyDescr_NewMethod(type, meth);
- if (descr == nullptr)
- return -1;
- char mangled_name[200];
- strcpy(mangled_name, meth->ml_name);
- strcat(mangled_name, ".overload");
- if (PyDict_SetItemString(dict, mangled_name, descr) < 0)
- return -1;
- if (meth->ml_flags & METH_STATIC) {
- // This is the special case where a static method is hidden.
- Shiboken::AutoDecRef special(Py_BuildValue("(Os)", cfunc.object(), "overload"));
- if (PyDict_SetItem(pyside_globals->map_dict, special, obtype) < 0)
- return -1;
- }
- if (PyDict_SetItemString(pyside_globals->map_dict, mangled_name, obtype) < 0)
- return -1;
- continue;
- }
- // Then we insert the mapping for static methods.
- if (meth->ml_flags & METH_STATIC) {
- if (PyDict_SetItem(pyside_globals->map_dict, look, obtype) < 0)
- return -1;
- }
- }
- return 0;
-}
-
-int
-SbkSpecial_Type_Ready(PyObject * /* module */, PyTypeObject *type,
- const char *signatures[])
-{
- if (PyType_Ready(type) < 0)
- return -1;
- auto *ob_type = reinterpret_cast<PyObject *>(type);
- int ret = PySide_BuildSignatureArgs(ob_type, signatures);
- if (ret < 0) {
- PyErr_Print();
- PyErr_SetNone(PyExc_ImportError);
- }
- return ret;
-}
-
-void
-FinishSignatureInitialization(PyObject *module, const char *signatures[])
-{
- /*
- * This function is called at the very end of a module initialization.
- * We now patch certain types to support the __signature__ attribute,
- * initialize module functions and resolve static methods.
- *
- * Still, it is not possible to call init phase 2 from here,
- * because the import is still running. Do it from Python!
- */
- PySide_PatchTypes();
- if (PySide_FinishSignatures(module, signatures) < 0) {
- PyErr_Print();
- PyErr_SetNone(PyExc_ImportError);
- }
-}
-
-void
-SetError_Argument(PyObject *args, const char *func_name)
-{
- /*
- * This function replaces the type error construction with extra
- * overloads parameter in favor of using the signature module.
- * Error messages are rare, so we do it completely in Python.
- */
- init_module_1();
- init_module_2();
- Shiboken::AutoDecRef res(PyObject_CallFunction(
- pyside_globals->seterror_argument_func,
- const_cast<char *>("(Os)"), args, func_name));
- if (res.isNull()) {
- PyErr_Print();
- Py_FatalError("seterror_argument did not receive a result");
- }
- PyObject *err, *msg;
- if (!PyArg_UnpackTuple(res, func_name, 2, 2, &err, &msg)) {
- PyErr_Print();
- Py_FatalError("unexpected failure in seterror_argument");
- }
- PyErr_SetObject(err, msg);
-}
-
-/*
- * Support for the metatype SbkObjectType_Type's tp_getset.
- *
- * This was not necessary for __signature__, because PyType_Type inherited it.
- * But the __doc__ attribute existed already by inheritance, and calling
- * PyType_Modified() is not supported. So we added the getsets explicitly
- * to the metatype.
- */
-
-PyObject *
-Sbk_TypeGet___signature__(PyObject *ob, PyObject *modifier)
-{
- return pyside_tp_get___signature__(ob, modifier);
-}
-
-PyObject *Sbk_TypeGet___doc__(PyObject *ob)
-{
- return pyside_tp_get___doc__(ob);
-}
-
-} //extern "C"
diff --git a/sources/shiboken2/libshiboken/signature.h b/sources/shiboken2/libshiboken/signature.h
deleted file mode 100644
index b22a78497..000000000
--- a/sources/shiboken2/libshiboken/signature.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SIGNATURE_H
-#define SIGNATURE_H
-
-#include "sbkpython.h"
-
-extern "C"
-{
-
-LIBSHIBOKEN_API int SbkSpecial_Type_Ready(PyObject *, PyTypeObject *, const char *[]);
-LIBSHIBOKEN_API void FinishSignatureInitialization(PyObject *, const char *[]);
-LIBSHIBOKEN_API void SetError_Argument(PyObject *, const char *);
-LIBSHIBOKEN_API PyObject *Sbk_TypeGet___signature__(PyObject *, PyObject *);
-LIBSHIBOKEN_API PyObject *Sbk_TypeGet___doc__(PyObject *);
-
-} // extern "C"
-
-#endif // SIGNATURE_H
diff --git a/sources/shiboken2/libshiboken/signature_doc.rst b/sources/shiboken2/libshiboken/signature_doc.rst
deleted file mode 100644
index cb9041d0c..000000000
--- a/sources/shiboken2/libshiboken/signature_doc.rst
+++ /dev/null
@@ -1,357 +0,0 @@
-*************************
-The signature C extension
-*************************
-
-This module is a C extension for CPython 3.5 and up, and CPython 2.7.
-Its purpose is to provide support for the ``__signature__`` attribute
-of builtin PyCFunction objects.
-
-
-Short Introduction to the Topic
-===============================
-
-Beginning with CPython 3.5, Python functions began to grow a ``__signature__``
-attribute for normal Python functions. This is totally optional and just
-a nice-to-have feature in Python.
-
-PySide, on the other hand, could use ``__signature__`` very much, because the
-typing info for the 15000+ PySide functions is really missing, and it
-would be nice to have this info directly available.
-
-
-The Idea to Support Signatures
-==============================
-
-We want to have an additional ``__signature__`` attribute in all PySide
-methods, without changing lots of generated code.
-Therefore, we did not change any of the existing data structures,
-but supported the new attribute by a global dictionary.
-
-When the ``__signature__`` property is requested, a method is called that
-does a lookup in the global dict. This is a flexible approach with little impact
-to the rest of the project. It has very limited overhead compared to direct
-attribute access, but for the need of a signature access from time to time,
-this is an adequate compromise.
-
-
-How this Code Works
--------------------
-
-Signatures are supported for regular Python functions, only. Creating signatures
-for ``PyCFunction`` objects would require quite some extra effort in Python.
-
-Fortunately, we found this special *stealth* technique, that saves us most of the
-needed effort:
-
-The basic idea is to create a dummy Python function with **varnames**, **defaults**
-and **annotations** properties, and then to use the inspect
-module to create a signature object. This object is returned as the computed
-result of the ``__signature__`` attribute of the real ``PyCFunction`` object.
-
-There is one thing that really changes Python a bit:
-
-* We added the ``__signature__`` attribute to every function.
-
-That is a little change to Python that does not harm, but it saves us
-tons of code, that was needed in the early versions of the module.
-
-The internal work is done in two steps:
-
-* All functions of a class get the *signature text* when the module is imported.
- This is only a very small overhead added to the startup time. It is a single
- string for each whole class.
-* The actual signature object is created later, when the attribute is really
- requested. Signatures are cached and only created on first access.
-
-Example:
-
-The ``PyCFunction`` ``QtWidgets.QApplication.palette`` is interrogated for its
-signature. That means ``pyside_sm_get___signature__()`` is called.
-It calls ``GetSignature_Function`` which returns the signature if it is found.
-
-
-Why this Code is Fast
----------------------
-
-It costs a little time (maybe 6 seconds) to run througs every single signature
-object, since these are more than 25000 Python objects. But all the signature
-objects will be rarely accessed but in special applications.
-The normal case are only a few accesses, and these are working pretty fast.
-
-The key to make this signature module fast is to avoid computation as much as
-possible. When no signature objects are used, then almost no time is lost in
-initialization. Only the above mentioned strings and some support modules are
-additionally loaded on ``import PySide2``.
-When it comes to signature usage, then late initialization is used and cached.
-This technique is also known as *full laziness* in haskell.
-
-There are actually two locations where late initialization occurs:
-
-* ``dict`` can be no dict but a tuple. That is the initial argument tuple that
- was saved by ``PySide_BuildSignatureArgs`` at module load time.
- If so, then ``pyside_type_init`` in parser.py will be called,
- which parses the string and creates the dict.
-* ``props`` can be empty. Then ``create_signature`` in loader.py
- is called, which uses a dummy function to produce a signature instance
- with the inspect module.
-
-The initialization that is always done is just two dictionary writes
-per class, and we have about 1000 classes.
-To measure the additional overhead, we have simulated what happens
-when ``from PySide2 import *`` is performed.
-It turned out that the overhead is below 0.5 ms.
-
-
-The Signature Package Structure
--------------------------------
-
-The C++ code involved with the signature module is completely in the file
-shiboken2/libshiboken/signature.cpp . All other functionality is implemented in
-the ``signature`` Python package. It has the following structure::
-
- shiboken2/files.dir/shibokensupport/
- backport_inspect.py
-
- signature/
- loader.py
- parser.py
- mapping.py
- errorhandler.py
- layout.py
-
- lib/
- enum_sig.py
- tool.py
-
-
-
-Really important are the **parser**, **mapping**, **errorhandler**, **enum_sig**,
-**layout** and **loader** modules. The rest is needed to create Python 2 compatibility
-or be compatible with embedding and installers.
-
-
-loader.py
-~~~~~~~~~
-
-This module assembles and imports the ``inspect`` module, and then exports the
-``create_signature`` function. This function takes a fake function and some
-attributes and builds a ``__signature__`` object with the inspect module.
-
-
-parser.py
-~~~~~~~~~
-
-This module takes a class signatures string from C++ and parses it into the
-needed properties for the ``create_signature`` function. Its entry point is the
-``pyside_type_init`` function, which is called from the C module via ``loader.py``.
-
-
-mapping.py
-~~~~~~~~~~
-
-The purpose of the mapping module is maintaining a list of replacement strings
-that map from the *signature text* in C to the property strings that Python
-needs. A lot of mappings are resolved by rather complex expressions in ``parser.py``,
-but a few hundred cases are better to spell explicitly, here.
-
-
-errorhandler.py
-~~~~~~~~~~~~~~~
-
-Since ``Qt For Python 5.12``, we no longer use the builtin type error messages from C++.
-Instead, we get much better results with the signature module. At the same time,
-this enforced supporting shiboken as well, and the signature module was no longer
-optional.
-
-
-enum_sig.py
-~~~~~~~~~~~
-
-The diverse applications of the signature module all needed to iterate over modules,
-classes and functions. In order to centralize this enumeration, the process has
-been factored out as a context manager. The user has only to supply functions
-that do the actual formatting.
-
-See for example the .pyi generator ``pyside2/PySide2/support/generate_pyi.py``.
-
-
-layout.py
-~~~~~~~~~
-
-As more applications used the signature module, different formatting of signatures
-was needed. To support that, we created the function ``create_signature``, which
-has a parameter to choose from some prefefined layouts.
-
-
-*typing27.py*
-~~~~~~~~~~~~~
-
-Python 2 has no typing module at all. This is a backport of the minimum that is needed.
-
-
-*backport_inspect.py*
-~~~~~~~~~~~~~~~~~~~~~
-
-Python 2 has an inspect module, but lacks the signature functions, completely.
-This module adds the missing functionality, which is merged at runtime into
-the inspect module.
-
-
-Multiple Arities
-----------------
-
-One aspect that was ignored so far was *multiple arities*: How to handle it when
-a function has more than one signature?
-
-I did not find any note on how multiple signatures should be treated in Python,
-but this simple rules seem to work well:
-
-* If there is a list, then it is a multi-signature.
-* Otherwise, it is a simple signature.
-
-
-Impacts of The Signature Module
-===============================
-
-The signature module has a number of impacts to other PySide modules, which were
-created as a consequence of its existence, and there will be a few more in the
-future:
-
-
-existence_test.py
------------------
-
-The file ``pyside2/tests/registry/existence_test.py`` was written using the
-signatures from the signatures module. The idea is that there are some 15000
-functions with a certain signature.
-
-These functions should not get lost by some bad check-in. Therefore, a list
-of all existing signatures is kept as a module that assembles a
-dictionary. The function existence is checked, and also the exact arity.
-
-This module exists for every PySide release and every platform. The initial
-module is generated once and saved as ``exists_{plat}_{version}.py``.
-
-An error is normally only reported as a warning, but:
-
-
-Interaction With The Coin Module
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When this test program is run in COIN, then the warnings are turned into
-errors. The reason is that only in COIN, we have a stable configuration
-of PySide modules that can reliably be compared.
-
-These modules have the name ``exists_{platf}_{version}_ci.py``, and as a big
-exception for generated code, these files are *intentionally* checked in.
-
-
-What Happens When a List is Missing?
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When a new version of PySide gets created, then the existence test files
-initially do not exist.
-
-When a COIN test is run, then it will complain about the error and create
-the missing module on standard output.
-But since COIN tests are run multiple times, the output that was generated
-by the first test will still exist at the subsequent runs.
-(If COIN was properly implemented, we could not take that advantage and
-would need to implement that as an extra exception.)
-
-As a result, a missing module will be reported as a test which partially
-succeeded (called "FLAKY"). To avoid further flaky tests and to activate as a real test,
-we can now capture the error output of COIN and check the generated module
-in.
-
-
-Explicitly Enforcing Recreation
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The former way to regenerate the registry files was to remove the files
-and check that in. This has the desired effect, but creates huge deltas.
-As a more efficient way, we have prepared a comment in the first line
-that contains the word "recreate".
-By uncommenting this line, a NameError is triggered, which has the same
-effect.
-
-
-init_platform.py
-~~~~~~~~~~~~~~~~
-
-For generating the ``exists_{platf}_{version}`` modules, the module
-``pyside2/tests/registry/init_platform.py`` was written. It can be used
-standalone from the commandline, to check the compatibility of some
-changes, directly.
-
-
-scrape_testresults.py
----------------------
-
-To simplify and automate the process of extracting the ``exists_{platf}_{version}_ci.py``
-files, the script ``pyside2/tests/registry/scrape_testresults.py`` has been written.
-
-This script scans the whole testresults website for PySide, that is::
-
- https://testresults.qt.io/coin/api/results/pyside/pyside-setup/
-
-On the first scan, the script runs less than 30 minutes. After that, a cache
-is generated and the scan works *much* faster. The test results are placed
-into the folder ``pyside2/tests/registry/testresults/embedded/`` with a
-unique name that allows for easy sorting. Example::
-
- testresults/embedded/2018_09_10_10_40_34-test_1536891759-exists_linux_5_11_2_ci.py
-
-These files are created only once. If they already exist, they are not touched, again.
-The file `pyside2/tests/registry/known_urls.json`` holds all scanned URLs after
-a successful scan. The ``testresults/embedded`` folder can be kept for reference
-or can be removed. Important is only the json file.
-
-The result of a scan is then directly placed into the ``pyside2/tests/registry/``
-folder. It should be reviewed and then eventually checked in.
-
-
-generate_pyi.py
----------------
-
-``pyside2/PySide2/support/generate_pyi.py`` is still under development.
-This module generates so-called hinting stubs for integration of PySide
-with diverse *Python IDEs*.
-
-Although this module creates the stubs as an add-on, the
-impact on the quality of the signature module is considerable:
-
-The module must create syntactically correct ``.pyi`` files which contain
-not only signatures but also constants and enums of all PySide modules.
-This serves as an extra challenge that has a very positive effect on
-the completeness and correctness of signatures.
-
-
-Current Extensions
-------------------
-
-Before the signature module was written, there already existed the concept of
-signatures, but in a more C++ - centric way. From that time, there existed
-the error messages, which are created when a function gets wrong argument types.
-
-These error messages were replaced by text generated on demand by
-the signature module, in order to be more consistent and correct.
-This was implemented in ``Qt For Python 5.12.0``.
-
-Additionally, the ``__doc__`` attribute of PySide methods was not set.
-It was easy to get a nice ``help()`` feature by creating signatures
-as default content for docstrings.
-This was implemented in ``Qt For Python 5.12.1``.
-
-
-Literature
-==========
-
- `PEP 362 – Function Signature Object <https://www.python.org/dev/peps/pep-0362/>`__
-
- `PEP 484 – Type Hints <https://www.python.org/dev/peps/pep-0484/>`__
-
- `PEP 3107 – Function Annotations <https://www.python.org/dev/peps/pep-3107/>`__
-
-
-*Personal Remark: This module is dedicated to our lovebird "Püppi", who died on 2017-09-15.*
diff --git a/sources/shiboken2/libshiboken/threadstatesaver.cpp b/sources/shiboken2/libshiboken/threadstatesaver.cpp
deleted file mode 100644
index 0d19528f9..000000000
--- a/sources/shiboken2/libshiboken/threadstatesaver.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "threadstatesaver.h"
-
-namespace Shiboken
-{
-
-ThreadStateSaver::ThreadStateSaver() = default;
-
-ThreadStateSaver::~ThreadStateSaver()
-{
- restore();
-}
-
-void ThreadStateSaver::save()
-{
- if (PyEval_ThreadsInitialized())
- m_threadState = PyEval_SaveThread();
-}
-
-void ThreadStateSaver::restore()
-{
- if (m_threadState) {
- PyEval_RestoreThread(m_threadState);
- m_threadState = nullptr;
- }
-}
-
-} // namespace Shiboken
-
diff --git a/sources/shiboken2/libshiboken/threadstatesaver.h b/sources/shiboken2/libshiboken/threadstatesaver.h
deleted file mode 100644
index ddfbcb93b..000000000
--- a/sources/shiboken2/libshiboken/threadstatesaver.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef THREADSTATESAVER_H
-#define THREADSTATESAVER_H
-
-#include "sbkpython.h"
-#include <shibokenmacros.h>
-
-namespace Shiboken
-{
-
-class LIBSHIBOKEN_API ThreadStateSaver
-{
-public:
- ThreadStateSaver(const ThreadStateSaver &) = delete;
- ThreadStateSaver(ThreadStateSaver &&) = delete;
- ThreadStateSaver &operator=(const ThreadStateSaver &) = delete;
- ThreadStateSaver &operator=(ThreadStateSaver &&) = delete;
-
- ThreadStateSaver();
- ~ThreadStateSaver();
- void save();
- void restore();
-private:
- PyThreadState *m_threadState = nullptr;
-};
-
-} // namespace Shiboken
-
-#endif // THREADSTATESAVER_H
-
diff --git a/sources/shiboken2/libshiboken/tmp-referencetopython/sbkconverter.cpp b/sources/shiboken2/libshiboken/tmp-referencetopython/sbkconverter.cpp
deleted file mode 100644
index ab205e215..000000000
--- a/sources/shiboken2/libshiboken/tmp-referencetopython/sbkconverter.cpp
+++ /dev/null
@@ -1,216 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkconverter.h"
-#include "sbkconverter_p.h"
-#include "basewrapper_p.h"
-
-#include "sbkdbg.h"
-
-namespace Shiboken {
-namespace Conversions {
-
-static SbkConverter *createConverterObject(PyTypeObject *type,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc,
- CppToPythonFunc pointerToPythonFunc,
- CppToPythonFunc copyToPythonFunc)
-{
- SbkConverter *converter = new SbkConverter;
- converter->pythonType = type;
-
- converter->pointerToPython = pointerToPythonFunc;
- converter->copyToPython = copyToPythonFunc;
-
- converter->toCppPointerConversion = std::make_pair(toCppPointerCheckFunc, toCppPointerConvFunc);
- converter->toCppConversions.clear();
-
- return converter;
-}
-
-SbkConverter *createConverter(SbkObjectType *type,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc,
- CppToPythonFunc pointerToPythonFunc,
- CppToPythonFunc copyToPythonFunc)
-{
- SbkConverter *converter = createConverterObject(reinterpret_cast<PyTypeObject *>(type),
- toCppPointerConvFunc, toCppPointerCheckFunc,
- pointerToPythonFunc, copyToPythonFunc);
- type->d->converter = converter;
- return converter;
-}
-
-void deleteConverter(SbkConverter *converter)
-{
- if (converter) {
- converter->toCppConversions.clear();
- delete converter;
- }
-}
-
-void addPythonToCppValueConversion(SbkConverter *converter,
- PythonToCppFunc pythonToCppFunc,
- IsConvertibleToCppFunc isConvertibleToCppFunc)
-{
- converter->toCppConversions.push_back(std::make_pair(isConvertibleToCppFunc, pythonToCppFunc));
-}
-void addPythonToCppValueConversion(SbkObjectType *type,
- PythonToCppFunc pythonToCppFunc,
- IsConvertibleToCppFunc isConvertibleToCppFunc)
-{
- addPythonToCppValueConversion(type->d->converter, pythonToCppFunc, isConvertibleToCppFunc);
-}
-
-PyObject *pointerToPython(SbkObjectType *type, const void *cppIn)
-{
- if (!cppIn)
- Py_RETURN_NONE;
- return type->d->converter->pointerToPython(cppIn);
-}
-
-static inline PyObject *CopyCppToPython(SbkConverter *converter, const void *cppIn)
-{
- assert(cppIn);
- return converter->copyToPython(cppIn);
-}
-PyObject *copyToPython(SbkObjectType *type, const void *cppIn)
-{
- return CopyCppToPython(type->d->converter, cppIn);
-}
-PyObject *toPython(SbkConverter *converter, const void *cppIn)
-{
- return CopyCppToPython(converter, cppIn);
-}
-
-PyObject *referenceToPython(SbkObjectType *type, const void *cppIn)
-{
- assert(cppIn);
- PyObject *pyOut = (PyObject *)BindingManager::instance().retrieveWrapper(cppIn);
- if (pyOut) {
- Py_INCREF(pyOut);
- return pyOut;
- }
- // If it is Value Type, return a copy of the C++ object.
- if (type->d->converter->copyToPython)
- return type->d->converter->copyToPython(cppIn);
- // If it is an Object Type, return a copy of the C++ object.
- return type->d->converter->pointerToPython(cppIn);
-}
-
-PythonToCppFunc isPythonToCppPointerConvertible(SbkObjectType *type, PyObject *pyIn)
-{
- assert(pyIn);
- return type->d->converter->toCppPointerConversion.first(pyIn);
-}
-
-static inline PythonToCppFunc IsPythonToCppConvertible(SbkConverter *converter, PyObject *pyIn)
-{
- assert(pyIn);
- ToCppConversionList &convs = converter->toCppConversions;
- for (ToCppConversionList::iterator conv = convs.begin(); conv != convs.end(); ++conv) {
- PythonToCppFunc toCppFunc = 0;
- if ((toCppFunc = (*conv).first(pyIn)))
- return toCppFunc;
- }
- return 0;
-}
-PythonToCppFunc isPythonToCppValueConvertible(SbkObjectType *type, PyObject *pyIn)
-{
- return IsPythonToCppConvertible(type->d->converter, pyIn);
-}
-PythonToCppFunc isPythonToCppConvertible(SbkConverter *converter, PyObject *pyIn)
-{
- return IsPythonToCppConvertible(converter, pyIn);
-}
-
-PythonToCppFunc isPythonToCppReferenceConvertible(SbkObjectType *type, PyObject *pyIn)
-{
- if (pyIn != Py_None) {
- PythonToCppFunc toCpp = isPythonToCppPointerConvertible(type, pyIn);
- if (toCpp)
- return toCpp;
- }
- return isPythonToCppValueConvertible(type, pyIn);
-}
-
-void nonePythonToCppNullPtr(PyObject *, void *cppOut)
-{
- assert(cppOut);
- *reinterpret_cast<void **>(cppOut) = nullptr;
-}
-
-void pythonToCppPointer(SbkObjectType *type, PyObject *pyIn, void *cppOut)
-{
- assert(pyIn);
- assert(cppOut);
- SbkObjectType *inType = (SbkObjectType *)Py_TYPE(pyIn);
- if (ObjectType::hasCast(inType)) {
- *reinterpret_cast<void **>(cppOut) =
- ObjectType::cast(inType, reinterpret_cast<SbkObject *>(pyIn), reinterpret_cast<PyTypeObject *>(type));
- } else {
- *reinterpret_cast<void **>(cppOut) =
- Object::cppPointer(reinterpret_cast<SbkObject *>(pyIn), reinterpret_cast<PyTypeObject *>(type));
- }
-}
-
-bool isImplicitConversion(SbkObjectType *type, PythonToCppFunc toCppFunc)
-{
- // This is the Object Type or Value Type conversion that only
- // retrieves the C++ pointer held in the Python wrapper.
- if (toCppFunc == type->d->converter->toCppPointerConversion.second)
- return false;
-
- // Object Types doesn't have any kind of value conversion,
- // only C++ pointer retrieval.
- if (type->d->converter->toCppConversions.empty())
- return false;
-
- // The first conversion of the non-pointer conversion list is
- // a Value Type's copy to C++ function, which is not an implicit
- // conversion.
- // Otherwise it must be one of the implicit conversions.
- // Note that we don't check if the Python to C++ conversion is in
- // the list of the type's conversions, for it is expected that the
- // caller knows what he's doing.
- ToCppConversionList::iterator conv = type->d->converter->toCppConversions.begin();
- return toCppFunc != (*conv).second;
-}
-
-} } // namespace Shiboken::Conversions
diff --git a/sources/shiboken2/libshiboken/tmp-referencetopython/sbkconverter.h b/sources/shiboken2/libshiboken/tmp-referencetopython/sbkconverter.h
deleted file mode 100644
index 3578e4039..000000000
--- a/sources/shiboken2/libshiboken/tmp-referencetopython/sbkconverter.h
+++ /dev/null
@@ -1,191 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBK_CONVERTER_H
-#define SBK_CONVERTER_H
-
-#include <limits>
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-#include "basewrapper.h"
-
-extern "C"
-{
-
-/**
- * SbkConverter is used to perform type conversions from C++
- * to Python and vice-versa;.and it is also used for type checking.
- * SbkConverter is a private structure that must be accessed
- * using the functions provided by the converter API.
- */
-struct SbkConverter;
-
-/**
- * Given a void pointer to a C++ object, this function must return
- * the proper Python object. It may be either an existing wrapper
- * for the C++ object, or a newly create one. Or even the Python
- * equivalent of the C++ value passed in the argument.
- *
- * C++ -> Python
- */
-typedef PyObject *(*CppToPythonFunc)(const void *);
-
-/**
- * This function converts a Python object to a C++ value, it may be
- * a pointer, value, class, container or primitive type, passed via
- * a void pointer, that will be cast properly inside the function.
- * This function is usually returned by an IsConvertibleToCppFunc
- * function, or obtained knowing the type of the Python object input,
- * thus it will not check the Python object type, and will expect
- * the void pointer to be pointing to a proper variable.
- *
- * Python -> C++
- */
-typedef void (*PythonToCppFunc)(PyObject *,void *);
-
-/**
- * Checks if the Python object passed in the argument is convertible to a
- * C++ type defined inside the function, it returns the converter function
- * that will transform a Python argument into a C++ value.
- * It returns NULL if the Python object is not convertible to the C++ type
- * that the function represents.
- *
- * Python -> C++ ?
- */
-typedef PythonToCppFunc (*IsConvertibleToCppFunc)(PyObject *);
-
-} // extern "C"
-
-
-namespace Shiboken {
-namespace Conversions {
-
-/**
- * Creates a converter for a wrapper type.
- * \param type A Shiboken.ObjectType that will receive the new converter.
- * \param toCppPointerConvFunc Function to retrieve the C++ pointer held by a Python wrapper.
- * \param toCppPointerCheckFunc Check and return the retriever function of the C++ pointer held by a Python wrapper.
- * \param pointerToPythonFunc Function to convert a C++ object to a Python \p type wrapper, keeping their identity.
- * \param copyToPythonFunc Function to convert a C++ object to a Python \p type, copying the object.
- * \returns The new converter referred by the wrapper \p type.
- */
-LIBSHIBOKEN_API SbkConverter *createConverter(SbkObjectType *type,
- PythonToCppFunc toCppPointerConvFunc,
- IsConvertibleToCppFunc toCppPointerCheckFunc,
- CppToPythonFunc pointerToPythonFunc,
- CppToPythonFunc copyToPythonFunc = 0);
-
-LIBSHIBOKEN_API void deleteConverter(SbkConverter *converter);
-
-/**
- * Adds a new conversion of a Python object to a C++ value.
- * This is used in copy and implicit conversions.
- */
-LIBSHIBOKEN_API void addPythonToCppValueConversion(SbkConverter *converter,
- PythonToCppFunc pythonToCppFunc,
- IsConvertibleToCppFunc isConvertibleToCppFunc);
-LIBSHIBOKEN_API void addPythonToCppValueConversion(SbkObjectType *type,
- PythonToCppFunc pythonToCppFunc,
- IsConvertibleToCppFunc isConvertibleToCppFunc);
-
-// C++ -> Python ---------------------------------------------------------------------------
-
-/**
- * Retrieves the Python wrapper object for the given \p cppIn C++ pointer object.
- * This function is used only for Value and Object Types.
- * Example usage:
- * TYPE *var;
- * PyObject *pyVar = pointerToPython(SBKTYPE, &var);
- */
-LIBSHIBOKEN_API PyObject *pointerToPython(SbkObjectType *type, const void *cppIn);
-
-/**
- * Retrieves the Python wrapper object for the given C++ value pointed by \p cppIn.
- * This function is used only for Value Types.
- * Example usage:
- * TYPE var;
- * PyObject *pyVar = copyToPython(SBKTYPE, &var);
- */
-LIBSHIBOKEN_API PyObject *copyToPython(SbkObjectType *type, const void *cppIn);
-
-// TODO:WRITEDOCSTRING - used only for Value Types - cppIn must point to a value
-/**
- * Retrieves the Python wrapper object for the given C++ reference pointed by \p cppIn.
- * This function is used only for Value and Object Types.
- * It differs from pointerToPython() for not checking for a NULL pointer.
- * Example usage:
- * TYPE &var = SOMETHING;
- * PyObject *pyVar = copyToPython(SBKTYPE, &var);
- */
-LIBSHIBOKEN_API PyObject *referenceToPython(SbkObjectType *type, const void *cppIn);
-
-// TODO:WRITEDOCSTRING - used only for Primitives and Containers (and Value Types) - cppIn must point to a primitive, container or value type
-/// This is the same as copyToPython function.
-LIBSHIBOKEN_API PyObject *toPython(SbkConverter *converter, const void *cppIn);
-
-// Python -> C++ convertibility checks -----------------------------------------------------
-
-// TODO:WRITEDOCSTRING
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppPointerConvertible(SbkObjectType *type, PyObject *pyIn);
-
-// TODO:WRITEDOCSTRING- Returns a Python to C++ conversion function if true, or NULL if false.
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppValueConvertible(SbkObjectType *type, PyObject *pyIn);
-
-// TODO:WRITEDOCSTRING- Returns a Python to C++ conversion function if true, or NULL if false.
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppReferenceConvertible(SbkObjectType *type, PyObject *pyIn);
-
-/// This is the same as isPythonToCppValueConvertible function.
-LIBSHIBOKEN_API PythonToCppFunc isPythonToCppConvertible(SbkConverter *converter, PyObject *pyIn);
-
-// Python -> C++ ---------------------------------------------------------------------------
-
-// TODO:WRITEDOCSTRING - function used by the generated [TYPE]_PythonToCpp_[TYPE]_PTR
-LIBSHIBOKEN_API void pythonToCppPointer(SbkObjectType *type, PyObject *pyIn, void *cppOut);
-
-// TODO:WRITEDOCSTRING - function used by the generated isConvertible when the PyObject is None,
-// making a C++ NULL pointer the result of the toCpp function call.
-// DRAFT: When the Python object is a Py_None, it's C++ conversion is always a NULL pointer.
-LIBSHIBOKEN_API void nonePythonToCppNullPtr(PyObject *, void *cppOut);
-
-// TODO:WRITEDOCSTRING - tells if \p toCpp is an implicit conversion.
-LIBSHIBOKEN_API bool isImplicitConversion(SbkObjectType *type, PythonToCppFunc toCpp);
-
-} } // namespace Shiboken::Conversions
-
-#endif // SBK_CONVERTER_H
diff --git a/sources/shiboken2/libshiboken/typespec.cpp b/sources/shiboken2/libshiboken/typespec.cpp
deleted file mode 100644
index 902ed55af..000000000
--- a/sources/shiboken2/libshiboken/typespec.cpp
+++ /dev/null
@@ -1,777 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkpython.h"
-#include "typespec.h"
-#include "sbkstaticstrings.h"
-#include <structmember.h>
-
-#if PY_MAJOR_VERSION < 3
-
-extern "C"
-{
-
-// for some reason python 2.7 needs this on Windows
-#ifdef WIN32
-static PyGC_Head *_PyGC_generation0;
-#endif
-
-// from pymacro.h
-#ifndef Py_PYMACRO_H
-#define Py_PYMACRO_H
-
-/* Minimum value between x and y */
-#define Py_MIN(x, y) (((x) > (y)) ? (y) : (x))
-
-/* Maximum value between x and y */
-#define Py_MAX(x, y) (((x) > (y)) ? (x) : (y))
-
-/* Absolute value of the number x */
-#define Py_ABS(x) ((x) < 0 ? -(x) : (x))
-
-#define _Py_XSTRINGIFY(x) #x
-
-/* Convert the argument to a string. For example, Py_STRINGIFY(123) is replaced
- with "123" by the preprocessor. Defines are also replaced by their value.
- For example Py_STRINGIFY(__LINE__) is replaced by the line number, not
- by "__LINE__". */
-#define Py_STRINGIFY(x) _Py_XSTRINGIFY(x)
-
-/* Get the size of a structure member in bytes */
-#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member)
-
-/* Argument must be a char or an int in [-128, 127] or [0, 255]. */
-#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff))
-
-/* Assert a build-time dependency, as an expression.
-
- Your compile will fail if the condition isn't true, or can't be evaluated
- by the compiler. This can be used in an expression: its value is 0.
-
- Example:
-
- #define foo_to_char(foo) \
- ((char *)(foo) \
- + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))
-
- Written by Rusty Russell, public domain, http://ccodearchive.net/ */
-#define Py_BUILD_ASSERT_EXPR(cond) \
- (sizeof(char [1 - 2*!(cond)]) - 1)
-
-#define Py_BUILD_ASSERT(cond) do { \
- (void)Py_BUILD_ASSERT_EXPR(cond); \
- } while (0)
-
-/* Get the number of elements in a visible array
-
- This does not work on pointers, or arrays declared as [], or function
- parameters. With correct compiler support, such usage will cause a build
- error (see Py_BUILD_ASSERT_EXPR).
-
- Written by Rusty Russell, public domain, http://ccodearchive.net/
-
- Requires at GCC 3.1+ */
-// Simplified by "0 &&"
-#if 0 && (defined(__GNUC__) && !defined(__STRICT_ANSI__) && \
- (((__GNUC__ == 3) && (__GNU_MINOR__ >= 1)) || (__GNUC__ >= 4)))
-/* Two gcc extensions.
- &a[0] degrades to a pointer: a different type from an array */
-#define Py_ARRAY_LENGTH(array) \
- (sizeof(array) / sizeof((array)[0]) \
- + Py_BUILD_ASSERT_EXPR(!__builtin_types_compatible_p(typeof(array), \
- typeof(&(array)[0]))))
-#else
-#define Py_ARRAY_LENGTH(array) \
- (sizeof(array) / sizeof((array)[0]))
-#endif
-
-
-/* Define macros for inline documentation. */
-#define PyDoc_VAR(name) static char name[]
-#define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str)
-#ifdef WITH_DOC_STRINGS
-#define PyDoc_STR(str) str
-#else
-#define PyDoc_STR(str) ""
-#endif
-
-/* Below "a" is a power of 2. */
-/* Round down size "n" to be a multiple of "a". */
-#define _Py_SIZE_ROUND_DOWN(n, a) ((size_t)(n) & ~(size_t)((a) - 1))
-/* Round up size "n" to be a multiple of "a". */
-#define _Py_SIZE_ROUND_UP(n, a) (((size_t)(n) + \
- (size_t)((a) - 1)) & ~(size_t)((a) - 1))
-/* Round pointer "p" down to the closest "a"-aligned address <= "p". */
-#define _Py_ALIGN_DOWN(p, a) ((void *)((uintptr_t)(p) & ~(uintptr_t)((a) - 1)))
-/* Round pointer "p" up to the closest "a"-aligned address >= "p". */
-#define _Py_ALIGN_UP(p, a) ((void *)(((uintptr_t)(p) + \
- (uintptr_t)((a) - 1)) & ~(uintptr_t)((a) - 1)))
-/* Check if pointer "p" is aligned to "a"-bytes boundary. */
-#define _Py_IS_ALIGNED(p, a) (!((uintptr_t)(p) & (uintptr_t)((a) - 1)))
-
-#ifdef __GNUC__
-#define Py_UNUSED(name) _unused_ ## name __attribute__((unused))
-#else
-#define Py_UNUSED(name) _unused_ ## name
-#endif
-
-#endif /* Py_PYMACRO_H */
-
-// from typeobject.c
-static int
-extra_ivars(PyTypeObject *type, PyTypeObject *base)
-{
- size_t t_size = type->tp_basicsize;
- size_t b_size = base->tp_basicsize;
-
- assert(t_size >= b_size); /* Else type smaller than base! */
- if (type->tp_itemsize || base->tp_itemsize) {
- /* If itemsize is involved, stricter rules */
- return t_size != b_size ||
- type->tp_itemsize != base->tp_itemsize;
- }
- if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
- type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
- type->tp_flags & Py_TPFLAGS_HEAPTYPE)
- t_size -= sizeof(PyObject *);
- if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
- type->tp_dictoffset + sizeof(PyObject *) == t_size &&
- type->tp_flags & Py_TPFLAGS_HEAPTYPE)
- t_size -= sizeof(PyObject *);
-
- return t_size != b_size;
-}
-
-static void
-clear_slots(PyTypeObject *type, PyObject *self)
-{
- Py_ssize_t i, n;
- PyMemberDef *mp;
-
- n = Py_SIZE(type);
- mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
- for (i = 0; i < n; i++, mp++) {
- if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
- char *addr = (char *)self + mp->offset;
- PyObject *obj = *(PyObject **)addr;
- if (obj != NULL) {
- *(PyObject **)addr = NULL;
- Py_DECREF(obj);
- }
- }
- }
-}
-
-static void
-subtype_dealloc(PyObject *self)
-{
- PyTypeObject *type, *base;
- destructor basedealloc;
- PyThreadState *tstate = PyThreadState_GET();
-
- /* Extract the type; we expect it to be a heap type */
- type = Py_TYPE(self);
- assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
-
- /* Test whether the type has GC exactly once */
-
- if (!PyType_IS_GC(type)) {
- /* It's really rare to find a dynamic type that doesn't have
- GC; it can only happen when deriving from 'object' and not
- adding any slots or instance variables. This allows
- certain simplifications: there's no need to call
- clear_slots(), or DECREF the dict, or clear weakrefs. */
-
- /* Maybe call finalizer; exit early if resurrected */
- if (type->tp_del) {
- type->tp_del(self);
- if (self->ob_refcnt > 0)
- return;
- }
-
- /* Find the nearest base with a different tp_dealloc */
- base = type;
- while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
- assert(Py_SIZE(base) == 0);
- base = base->tp_base;
- assert(base);
- }
-
- /* Extract the type again; tp_del may have changed it */
- type = Py_TYPE(self);
-
- /* Call the base tp_dealloc() */
- assert(basedealloc);
- basedealloc(self);
-
- /* Can't reference self beyond this point */
- Py_DECREF(type);
-
- /* Done */
- return;
- }
-
- /* We get here only if the type has GC */
-
- /* UnTrack and re-Track around the trashcan macro, alas */
- /* See explanation at end of function for full disclosure */
- PyObject_GC_UnTrack(self);
- ++_PyTrash_delete_nesting;
- ++ tstate->trash_delete_nesting;
- Py_TRASHCAN_SAFE_BEGIN(self);
- --_PyTrash_delete_nesting;
- -- tstate->trash_delete_nesting;
- /* DO NOT restore GC tracking at this point. weakref callbacks
- * (if any, and whether directly here or indirectly in something we
- * call) may trigger GC, and if self is tracked at that point, it
- * will look like trash to GC and GC will try to delete self again.
- */
-
- /* Find the nearest base with a different tp_dealloc */
- base = type;
- while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
- base = base->tp_base;
- assert(base);
- }
-
- /* If we added a weaklist, we clear it. Do this *before* calling
- the finalizer (__del__), clearing slots, or clearing the instance
- dict. */
-
- if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
- PyObject_ClearWeakRefs(self);
-
- /* Maybe call finalizer; exit early if resurrected */
- if (type->tp_del) {
- _PyObject_GC_TRACK(self);
- type->tp_del(self);
- if (self->ob_refcnt > 0)
- goto endlabel; /* resurrected */
- else
- _PyObject_GC_UNTRACK(self);
- /* New weakrefs could be created during the finalizer call.
- If this occurs, clear them out without calling their
- finalizers since they might rely on part of the object
- being finalized that has already been destroyed. */
- if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
- /* Modeled after GET_WEAKREFS_LISTPTR() */
- PyWeakReference **list = (PyWeakReference **) \
- PyObject_GET_WEAKREFS_LISTPTR(self);
- while (*list)
- _PyWeakref_ClearRef(*list);
- }
- }
-
- /* Clear slots up to the nearest base with a different tp_dealloc */
- base = type;
- while (base->tp_dealloc == subtype_dealloc) {
- if (Py_SIZE(base))
- clear_slots(base, self);
- base = base->tp_base;
- assert(base);
- }
-
- /* If we added a dict, DECREF it */
- if (type->tp_dictoffset && !base->tp_dictoffset) {
- PyObject **dictptr = _PyObject_GetDictPtr(self);
- if (dictptr != NULL) {
- PyObject *dict = *dictptr;
- if (dict != NULL) {
- Py_DECREF(dict);
- *dictptr = NULL;
- }
- }
- }
-
- /* Extract the type again; tp_del may have changed it */
- type = Py_TYPE(self);
-
- /* Call the base tp_dealloc(); first retrack self if
- * basedealloc knows about gc.
- */
- if (PyType_IS_GC(base))
- _PyObject_GC_TRACK(self);
- assert(basedealloc);
- basedealloc(self);
-
- /* Can't reference self beyond this point */
- Py_DECREF(type);
-
- endlabel:
- ++_PyTrash_delete_nesting;
- ++ tstate->trash_delete_nesting;
- Py_TRASHCAN_SAFE_END(self);
- --_PyTrash_delete_nesting;
- -- tstate->trash_delete_nesting;
-
- /* Explanation of the weirdness around the trashcan macros:
-
- Q. What do the trashcan macros do?
-
- A. Read the comment titled "Trashcan mechanism" in object.h.
- For one, this explains why there must be a call to GC-untrack
- before the trashcan begin macro. Without understanding the
- trashcan code, the answers to the following questions don't make
- sense.
-
- Q. Why do we GC-untrack before the trashcan and then immediately
- GC-track again afterward?
-
- A. In the case that the base class is GC-aware, the base class
- probably GC-untracks the object. If it does that using the
- UNTRACK macro, this will crash when the object is already
- untracked. Because we don't know what the base class does, the
- only safe thing is to make sure the object is tracked when we
- call the base class dealloc. But... The trashcan begin macro
- requires that the object is *untracked* before it is called. So
- the dance becomes:
-
- GC untrack
- trashcan begin
- GC track
-
- Q. Why did the last question say "immediately GC-track again"?
- It's nowhere near immediately.
-
- A. Because the code *used* to re-track immediately. Bad Idea.
- self has a refcount of 0, and if gc ever gets its hands on it
- (which can happen if any weakref callback gets invoked), it
- looks like trash to gc too, and gc also tries to delete self
- then. But we're already deleting self. Double deallocation is
- a subtle disaster.
-
- Q. Why the bizarre (net-zero) manipulation of
- _PyTrash_delete_nesting around the trashcan macros?
-
- A. Some base classes (e.g. list) also use the trashcan mechanism.
- The following scenario used to be possible:
-
- - suppose the trashcan level is one below the trashcan limit
-
- - subtype_dealloc() is called
-
- - the trashcan limit is not yet reached, so the trashcan level
- is incremented and the code between trashcan begin and end is
- executed
-
- - this destroys much of the object's contents, including its
- slots and __dict__
-
- - basedealloc() is called; this is really list_dealloc(), or
- some other type which also uses the trashcan macros
-
- - the trashcan limit is now reached, so the object is put on the
- trashcan's to-be-deleted-later list
-
- - basedealloc() returns
-
- - subtype_dealloc() decrefs the object's type
-
- - subtype_dealloc() returns
-
- - later, the trashcan code starts deleting the objects from its
- to-be-deleted-later list
-
- - subtype_dealloc() is called *AGAIN* for the same object
-
- - at the very least (if the destroyed slots and __dict__ don't
- cause problems) the object's type gets decref'ed a second
- time, which is *BAD*!!!
-
- The remedy is to make sure that if the code between trashcan
- begin and end in subtype_dealloc() is called, the code between
- trashcan begin and end in basedealloc() will also be called.
- This is done by decrementing the level after passing into the
- trashcan block, and incrementing it just before leaving the
- block.
-
- But now it's possible that a chain of objects consisting solely
- of objects whose deallocator is subtype_dealloc() will defeat
- the trashcan mechanism completely: the decremented level means
- that the effective level never reaches the limit. Therefore, we
- *increment* the level *before* entering the trashcan block, and
- matchingly decrement it after leaving. This means the trashcan
- code will trigger a little early, but that's no big deal.
-
- Q. Are there any live examples of code in need of all this
- complexity?
-
- A. Yes. See SF bug 668433 for code that crashed (when Python was
- compiled in debug mode) before the trashcan level manipulations
- were added. For more discussion, see SF patches 581742, 575073
- and bug 574207.
- */
-}
-
-static PyTypeObject *
-solid_base(PyTypeObject *type)
-{
- PyTypeObject *base;
-
- if (type->tp_base)
- base = solid_base(type->tp_base);
- else
- base = &PyBaseObject_Type;
- if (extra_ivars(type, base))
- return type;
- else
- return base;
-}
-
-/* Calculate the best base amongst multiple base classes.
- This is the first one that's on the path to the "solid base". */
-
-static PyTypeObject *
-best_base(PyObject *bases)
-{
- Py_ssize_t i, n;
- PyTypeObject *base, *winner, *candidate, *base_i;
- PyObject *base_proto;
-
- assert(PyTuple_Check(bases));
- n = PyTuple_GET_SIZE(bases);
- assert(n > 0);
- base = NULL;
- winner = NULL;
- for (i = 0; i < n; i++) {
- base_proto = PyTuple_GET_ITEM(bases, i);
- if (PyClass_Check(base_proto))
- continue;
- if (!PyType_Check(base_proto)) {
- PyErr_SetString(
- PyExc_TypeError,
- "bases must be types");
- return NULL;
- }
- base_i = (PyTypeObject *)base_proto;
- if (base_i->tp_dict == NULL) {
- if (PyType_Ready(base_i) < 0)
- return NULL;
- }
- if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
- PyErr_Format(PyExc_TypeError,
- "type '%.100s' is not an acceptable base type",
- base_i->tp_name);
- return NULL;
- }
- candidate = solid_base(base_i);
- if (winner == NULL) {
- winner = candidate;
- base = base_i;
- }
- else if (PyType_IsSubtype(winner, candidate))
- ;
- else if (PyType_IsSubtype(candidate, winner)) {
- winner = candidate;
- base = base_i;
- }
- else {
- PyErr_SetString(
- PyExc_TypeError,
- "multiple bases have "
- "instance lay-out conflict");
- return NULL;
- }
- }
- if (base == NULL)
- PyErr_SetString(PyExc_TypeError,
- "a new-style class can't have only classic bases");
- return base;
-}
-
-static const short slotoffsets[] = {
- -1, /* invalid slot */
-/* Generated by typeslots.py */
-0,
-0,
-offsetof(PyHeapTypeObject, as_mapping.mp_ass_subscript),
-offsetof(PyHeapTypeObject, as_mapping.mp_length),
-offsetof(PyHeapTypeObject, as_mapping.mp_subscript),
-offsetof(PyHeapTypeObject, as_number.nb_absolute),
-offsetof(PyHeapTypeObject, as_number.nb_add),
-offsetof(PyHeapTypeObject, as_number.nb_and),
-offsetof(PyHeapTypeObject, as_number.nb_nonzero),
-offsetof(PyHeapTypeObject, as_number.nb_divmod),
-offsetof(PyHeapTypeObject, as_number.nb_float),
-offsetof(PyHeapTypeObject, as_number.nb_floor_divide),
-offsetof(PyHeapTypeObject, as_number.nb_index),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_add),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_and),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_floor_divide),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_lshift),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_multiply),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_or),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_power),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_remainder),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_rshift),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_subtract),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_true_divide),
-offsetof(PyHeapTypeObject, as_number.nb_inplace_xor),
-offsetof(PyHeapTypeObject, as_number.nb_int),
-offsetof(PyHeapTypeObject, as_number.nb_invert),
-offsetof(PyHeapTypeObject, as_number.nb_lshift),
-offsetof(PyHeapTypeObject, as_number.nb_multiply),
-offsetof(PyHeapTypeObject, as_number.nb_negative),
-offsetof(PyHeapTypeObject, as_number.nb_or),
-offsetof(PyHeapTypeObject, as_number.nb_positive),
-offsetof(PyHeapTypeObject, as_number.nb_power),
-offsetof(PyHeapTypeObject, as_number.nb_remainder),
-offsetof(PyHeapTypeObject, as_number.nb_rshift),
-offsetof(PyHeapTypeObject, as_number.nb_subtract),
-offsetof(PyHeapTypeObject, as_number.nb_true_divide),
-offsetof(PyHeapTypeObject, as_number.nb_xor),
-offsetof(PyHeapTypeObject, as_sequence.sq_ass_item),
-offsetof(PyHeapTypeObject, as_sequence.sq_concat),
-offsetof(PyHeapTypeObject, as_sequence.sq_contains),
-offsetof(PyHeapTypeObject, as_sequence.sq_inplace_concat),
-offsetof(PyHeapTypeObject, as_sequence.sq_inplace_repeat),
-offsetof(PyHeapTypeObject, as_sequence.sq_item),
-offsetof(PyHeapTypeObject, as_sequence.sq_length),
-offsetof(PyHeapTypeObject, as_sequence.sq_repeat),
-offsetof(PyHeapTypeObject, ht_type.tp_alloc),
-offsetof(PyHeapTypeObject, ht_type.tp_base),
-offsetof(PyHeapTypeObject, ht_type.tp_bases),
-offsetof(PyHeapTypeObject, ht_type.tp_call),
-offsetof(PyHeapTypeObject, ht_type.tp_clear),
-offsetof(PyHeapTypeObject, ht_type.tp_dealloc),
-offsetof(PyHeapTypeObject, ht_type.tp_del),
-offsetof(PyHeapTypeObject, ht_type.tp_descr_get),
-offsetof(PyHeapTypeObject, ht_type.tp_descr_set),
-offsetof(PyHeapTypeObject, ht_type.tp_doc),
-offsetof(PyHeapTypeObject, ht_type.tp_getattr),
-offsetof(PyHeapTypeObject, ht_type.tp_getattro),
-offsetof(PyHeapTypeObject, ht_type.tp_hash),
-offsetof(PyHeapTypeObject, ht_type.tp_init),
-offsetof(PyHeapTypeObject, ht_type.tp_is_gc),
-offsetof(PyHeapTypeObject, ht_type.tp_iter),
-offsetof(PyHeapTypeObject, ht_type.tp_iternext),
-offsetof(PyHeapTypeObject, ht_type.tp_methods),
-offsetof(PyHeapTypeObject, ht_type.tp_new),
-offsetof(PyHeapTypeObject, ht_type.tp_repr),
-offsetof(PyHeapTypeObject, ht_type.tp_richcompare),
-offsetof(PyHeapTypeObject, ht_type.tp_setattr),
-offsetof(PyHeapTypeObject, ht_type.tp_setattro),
-offsetof(PyHeapTypeObject, ht_type.tp_str),
-offsetof(PyHeapTypeObject, ht_type.tp_traverse),
-offsetof(PyHeapTypeObject, ht_type.tp_members),
-offsetof(PyHeapTypeObject, ht_type.tp_getset),
-offsetof(PyHeapTypeObject, ht_type.tp_free),
-offsetof(PyHeapTypeObject, as_number.nb_long),
-offsetof(PyHeapTypeObject, as_number.nb_divide),
-offsetof(PyHeapTypeObject, as_sequence.sq_slice),
-};
-
-PyObject *
-PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
-{
- auto res = reinterpret_cast<PyHeapTypeObject *>(PyType_GenericAlloc(&PyType_Type, 0));
- PyTypeObject *type, *base;
- PyObject *modname;
- auto res_start = reinterpret_cast<char *>(res);
- PyType_Slot *slot;
-
- /* Set the type name and qualname */
- auto s = const_cast<char *>(strrchr(spec->name, '.')); // C++11
- if (s == NULL)
- s = const_cast<char *>(spec->name);
- else
- s++;
-
- if (res == NULL)
- return NULL;
- type = &res->ht_type;
- /* The flags must be initialized early, before the GC traverses us */
- type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
- // was PyUnicode_FromString in Python 3
- res->ht_name = PyString_FromString(s);
- if (!res->ht_name)
- goto fail;
- // no ht_qualname in Python 2
- // res->ht_qualname = res->ht_name;
- // Py_INCREF(res->ht_qualname);
- type->tp_name = spec->name;
- if (!type->tp_name)
- goto fail;
-
- /* Adjust for empty tuple bases */
- if (!bases) {
- base = &PyBaseObject_Type;
- /* See whether Py_tp_base(s) was specified */
- for (slot = spec->slots; slot->slot; slot++) {
- if (slot->slot == Py_tp_base)
- base = (PyTypeObject *)slot->pfunc; // C++11
- else if (slot->slot == Py_tp_bases) {
- bases = (PyObject *)slot->pfunc; // C++11
- Py_INCREF(bases);
- }
- }
- if (!bases)
- bases = PyTuple_Pack(1, base);
- if (!bases)
- goto fail;
- }
- else
- Py_INCREF(bases);
-
- /* Calculate best base, and check that all bases are type objects */
- base = best_base(bases);
- if (base == NULL) {
- goto fail;
- }
- if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
- PyErr_Format(PyExc_TypeError,
- "type '%.100s' is not an acceptable base type",
- base->tp_name);
- goto fail;
- }
-
- /* Initialize essential fields */
- // no async in Python 2
- // type->tp_as_async = &res->as_async;
- type->tp_as_number = &res->as_number;
- type->tp_as_sequence = &res->as_sequence;
- type->tp_as_mapping = &res->as_mapping;
- type->tp_as_buffer = &res->as_buffer;
- /* Set tp_base and tp_bases */
- type->tp_bases = bases;
- bases = NULL;
- Py_INCREF(base);
- type->tp_base = base;
-
- type->tp_basicsize = spec->basicsize;
- type->tp_itemsize = spec->itemsize;
-
- for (slot = spec->slots; slot->slot; slot++) {
- if (slot->slot < 0
- || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) {
- PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
- goto fail;
- }
- if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases)
- /* Processed above */
- continue;
- *reinterpret_cast<void **>(res_start + slotoffsets[slot->slot]) = slot->pfunc;
-
- /* need to make a copy of the docstring slot, which usually
- points to a static string literal */
- if (slot->slot == Py_tp_doc) {
- // No signature in Python 2
- // const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc);
- const char *old_doc = (const char *)slot->pfunc;
- size_t len = strlen(old_doc)+1;
- char *tp_doc = (char *)PyObject_MALLOC(len); // C++11
- if (tp_doc == NULL) {
- PyErr_NoMemory();
- goto fail;
- }
- memcpy(tp_doc, old_doc, len);
- type->tp_doc = tp_doc;
- }
- }
- if (type->tp_dealloc == NULL) {
- /* It's a heap type, so needs the heap types' dealloc.
- subtype_dealloc will call the base type's tp_dealloc, if
- necessary. */
- type->tp_dealloc = subtype_dealloc;
- }
-
- if (PyType_Ready(type) < 0)
- goto fail;
-
- // no ht_cached_keys in Python 2
- // if (type->tp_dictoffset) {
- // res->ht_cached_keys = _PyDict_NewKeysForClass();
- // }
-
- /* Set type.__module__ */
- s = (char *)strrchr(spec->name, '.'); // c++11
- if (s != NULL) {
- int err;
- // was PyUnicode_FromStringAndSize in Python 3
- modname = PyString_FromStringAndSize(
- spec->name, (Py_ssize_t)(s - spec->name));
- if (modname == NULL) {
- goto fail;
- }
- // no PyId_ things in Python 2
- // err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname);
- err = PyDict_SetItem(type->tp_dict, Shiboken::PyMagicName::module(), modname);
- Py_DECREF(modname);
- if (err != 0)
- goto fail;
- } else {
- // no PyErr_WarnFormat in Python 2
- // if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
- // "builtin type %.200s has no __module__ attribute",
- // spec->name))
- char msg[250];
- sprintf(msg, "builtin type %.200s has no __module__ attribute", spec->name);
- if (PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1))
- goto fail;
- }
-
- return reinterpret_cast<PyObject *>(res);
-
- fail:
- Py_DECREF(res);
- return NULL;
-}
-
-PyObject *
-PyType_FromSpec(PyType_Spec *spec)
-{
- return PyType_FromSpecWithBases(spec, NULL);
-}
-
-void *
-PyType_GetSlot(PyTypeObject *type, int slot)
-{
- if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) {
- PyErr_BadInternalCall();
- return NULL;
- }
- if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) {
- /* Extension module requesting slot from a future version */
- return NULL;
- }
- return *reinterpret_cast<void **>(reinterpret_cast<char *>(type) + slotoffsets[slot]);
-}
-
-} // extern "C"
-#endif // PY_MAJOR_VERSION < 3
diff --git a/sources/shiboken2/libshiboken/typespec.h b/sources/shiboken2/libshiboken/typespec.h
deleted file mode 100644
index 193b654c2..000000000
--- a/sources/shiboken2/libshiboken/typespec.h
+++ /dev/null
@@ -1,153 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TYPESPEC_H
-#define TYPESPEC_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-
-#if PY_MAJOR_VERSION < 3
-extern "C"
-{
-
-typedef struct{
- int slot; // slot is somehow reserved in Qt /* slot id, see below */
- void *pfunc; /* function pointer */
-} PyType_Slot;
-
-typedef struct{
- const char *name;
- int basicsize;
- int itemsize;
- unsigned int flags;
- PyType_Slot *slots; /* terminated by slot==0. */
-} PyType_Spec;
-
-LIBSHIBOKEN_API PyObject *PyType_FromSpec(PyType_Spec *);
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
-LIBSHIBOKEN_API PyObject *PyType_FromSpecWithBases(PyType_Spec *, PyObject *);
-#endif
-#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
-LIBSHIBOKEN_API void *PyType_GetSlot(PyTypeObject *, int);
-#endif
-
-// from typeslots.h
-/* Do not renumber the file; these numbers are part of the stable ABI. */
-/* Disabled, see #10181 */
-#undef Py_bf_getbuffer
-#undef Py_bf_releasebuffer
-#define Py_mp_ass_subscript 3
-#define Py_mp_length 4
-#define Py_mp_subscript 5
-#define Py_nb_absolute 6
-#define Py_nb_add 7
-#define Py_nb_and 8
-#define Py_nb_nonzero 9
-#define Py_nb_divmod 10
-#define Py_nb_float 11
-#define Py_nb_floor_divide 12
-#define Py_nb_index 13
-#define Py_nb_inplace_add 14
-#define Py_nb_inplace_and 15
-#define Py_nb_inplace_floor_divide 16
-#define Py_nb_inplace_lshift 17
-#define Py_nb_inplace_multiply 18
-#define Py_nb_inplace_or 19
-#define Py_nb_inplace_power 20
-#define Py_nb_inplace_remainder 21
-#define Py_nb_inplace_rshift 22
-#define Py_nb_inplace_subtract 23
-#define Py_nb_inplace_true_divide 24
-#define Py_nb_inplace_xor 25
-#define Py_nb_int 26
-#define Py_nb_invert 27
-#define Py_nb_lshift 28
-#define Py_nb_multiply 29
-#define Py_nb_negative 30
-#define Py_nb_or 31
-#define Py_nb_positive 32
-#define Py_nb_power 33
-#define Py_nb_remainder 34
-#define Py_nb_rshift 35
-#define Py_nb_subtract 36
-#define Py_nb_true_divide 37
-#define Py_nb_xor 38
-#define Py_sq_ass_item 39
-#define Py_sq_concat 40
-#define Py_sq_contains 41
-#define Py_sq_inplace_concat 42
-#define Py_sq_inplace_repeat 43
-#define Py_sq_item 44
-#define Py_sq_length 45
-#define Py_sq_repeat 46
-#define Py_tp_alloc 47
-#define Py_tp_base 48
-#define Py_tp_bases 49
-#define Py_tp_call 50
-#define Py_tp_clear 51
-#define Py_tp_dealloc 52
-#define Py_tp_del 53
-#define Py_tp_descr_get 54
-#define Py_tp_descr_set 55
-#define Py_tp_doc 56
-#define Py_tp_getattr 57
-#define Py_tp_getattro 58
-#define Py_tp_hash 59
-#define Py_tp_init 60
-#define Py_tp_is_gc 61
-#define Py_tp_iter 62
-#define Py_tp_iternext 63
-#define Py_tp_methods 64
-#define Py_tp_new 65
-#define Py_tp_repr 66
-#define Py_tp_richcompare 67
-#define Py_tp_setattr 68
-#define Py_tp_setattro 69
-#define Py_tp_str 70
-#define Py_tp_traverse 71
-#define Py_tp_members 72
-#define Py_tp_getset 73
-#define Py_tp_free 74
-#define Py_nb_long 75
-#define Py_nb_divide 76
-#define Py_sq_slice 77
-} // extern "C"
-#endif // PY_MAJOR_VERSION < 3
-#endif // TYPESPEC_H
diff --git a/sources/shiboken2/libshiboken/voidptr.cpp b/sources/shiboken2/libshiboken/voidptr.cpp
deleted file mode 100644
index 6ac3c131d..000000000
--- a/sources/shiboken2/libshiboken/voidptr.cpp
+++ /dev/null
@@ -1,480 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "voidptr.h"
-#include "sbkconverter.h"
-#include "basewrapper.h"
-#include "basewrapper_p.h"
-
-extern "C"
-{
-
-// Void pointer object definition.
-typedef struct {
- PyObject_HEAD
- void *cptr;
- Py_ssize_t size;
- bool isWritable;
-} SbkVoidPtrObject;
-
-PyObject *SbkVoidPtrObject_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- // PYSIDE-560: It is much safer to first call a function and then do a
- // type cast than to do everything in one line. The bad construct looked
- // like this, actual call forgotten:
- // SbkVoidPtrObject *self =
- // reinterpret_cast<SbkVoidPtrObject *>(type->tp_alloc);
- PyObject *ob = type->tp_alloc(type, 0);
- auto *self = reinterpret_cast<SbkVoidPtrObject *>(ob);
-
- if (self != nullptr) {
- self->cptr = nullptr;
- self->size = -1;
- self->isWritable = false;
- }
-
- return reinterpret_cast<PyObject *>(self);
-}
-
-#define SbkVoidPtr_Check(op) (Py_TYPE(op) == SbkVoidPtrTypeF())
-
-
-int SbkVoidPtrObject_init(PyObject *self, PyObject *args, PyObject *kwds)
-{
- PyObject *addressObject;
- Py_ssize_t size = -1;
- int isWritable = 0;
- auto *sbkSelf = reinterpret_cast<SbkVoidPtrObject *>(self);
-
- static const char *kwlist[] = {"address", "size", "writeable", nullptr};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|ni", const_cast<char **>(kwlist),
- &addressObject, &size, &isWritable))
- return -1;
-
- // Void pointer.
- if (SbkVoidPtr_Check(addressObject)) {
- auto *sbkOther = reinterpret_cast<SbkVoidPtrObject *>(addressObject);
- sbkSelf->cptr = sbkOther->cptr;
- sbkSelf->size = sbkOther->size;
- sbkSelf->isWritable = sbkOther->isWritable;
- }
- // Python buffer interface.
- else if (PyObject_CheckBuffer(addressObject)) {
- Py_buffer bufferView;
-
- // Bail out if the object can't provide a simple contiguous buffer.
- if (PyObject_GetBuffer(addressObject, &bufferView, PyBUF_SIMPLE) < 0)
- return 0;
-
- sbkSelf->cptr = bufferView.buf;
- sbkSelf->size = bufferView.len > 0 ? bufferView.len : size;
- sbkSelf->isWritable = bufferView.readonly <= 0;
-
- // Release the buffer.
- PyBuffer_Release(&bufferView);
- }
- // Shiboken::Object wrapper.
- else if (Shiboken::Object::checkType(addressObject)) {
- auto *sbkOther = reinterpret_cast<SbkObject *>(addressObject);
- sbkSelf->cptr = sbkOther->d->cptr[0];
- sbkSelf->size = size;
- sbkSelf->isWritable = isWritable > 0;
- }
- // An integer representing an address.
- else {
- if (addressObject == Py_None) {
- sbkSelf->cptr = nullptr;
- sbkSelf->size = 0;
- sbkSelf->isWritable = false;
- }
-
- else {
- void *cptr = PyLong_AsVoidPtr(addressObject);
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "Creating a VoidPtr object requires an address of a C++ object, "
- "a wrapped Shiboken Object type, "
- "an object implementing the Python Buffer interface, "
- "or another VoidPtr object.");
- return -1;
- }
- sbkSelf->cptr = cptr;
- sbkSelf->size = size;
- sbkSelf->isWritable = isWritable > 0;
- }
- }
-
- return 0;
-}
-
-PyObject *SbkVoidPtrObject_richcmp(PyObject *obj1, PyObject *obj2, int op)
-{
- PyObject *result = Py_False;
- void *cptr1 = nullptr;
- void *cptr2 = nullptr;
- bool validObjects = true;
-
- if (SbkVoidPtr_Check(obj1))
- cptr1 = reinterpret_cast<SbkVoidPtrObject *>(obj1)->cptr;
- else
- validObjects = false;
-
- if (SbkVoidPtr_Check(obj2))
- cptr2 = reinterpret_cast<SbkVoidPtrObject *>(obj2)->cptr;
- else
- validObjects = false;
-
- if (validObjects) {
- switch (op) {
- case Py_EQ: if (cptr1 == cptr2) result = Py_True; break;
- case Py_NE: if (cptr1 != cptr2) result = Py_True; break;
- case Py_LT: break;
- case Py_LE: break;
- case Py_GT: break;
- case Py_GE: break;
- }
- }
-
- Py_INCREF(result);
- return result;
-}
-
-PyObject *SbkVoidPtrObject_int(PyObject *v)
-{
- auto *sbkObject = reinterpret_cast<SbkVoidPtrObject *>(v);
- return PyLong_FromVoidPtr(sbkObject->cptr);
-}
-
-PyObject *toBytes(PyObject *self, PyObject *args)
-{
- auto *sbkObject = reinterpret_cast<SbkVoidPtrObject *>(self);
- if (sbkObject->size < 0) {
- PyErr_SetString(PyExc_IndexError, "VoidPtr does not have a size set.");
- return nullptr;
- }
- PyObject *bytes = PyBytes_FromStringAndSize(reinterpret_cast<const char *>(sbkObject->cptr),
- sbkObject->size);
- Py_XINCREF(bytes);
- return bytes;
-}
-
-static struct PyMethodDef SbkVoidPtrObject_methods[] = {
- {"toBytes", toBytes, METH_NOARGS},
- {nullptr}
-};
-
-static Py_ssize_t SbkVoidPtrObject_length(PyObject *v)
-{
- auto *sbkObject = reinterpret_cast<SbkVoidPtrObject *>(v);
- if (sbkObject->size < 0) {
- PyErr_SetString(PyExc_IndexError, "VoidPtr does not have a size set.");
- return -1;
- }
-
- return sbkObject->size;
-}
-
-static const char trueString[] = "True" ;
-static const char falseString[] = "False" ;
-
-PyObject *SbkVoidPtrObject_repr(PyObject *v)
-{
-
-
- auto *sbkObject = reinterpret_cast<SbkVoidPtrObject *>(v);
- #ifdef IS_PY3K
- PyObject *s = PyUnicode_FromFormat("%s(%p, %zd, %s)",
- #else
- PyObject *s = PyBytes_FromFormat("%s(%p, %zd, %s)",
- #endif
- Py_TYPE(sbkObject)->tp_name,
- sbkObject->cptr,
- sbkObject->size,
- sbkObject->isWritable ? trueString : falseString);
- Py_XINCREF(s);
- return s;
-}
-
-PyObject *SbkVoidPtrObject_str(PyObject *v)
-{
- auto *sbkObject = reinterpret_cast<SbkVoidPtrObject *>(v);
- #ifdef IS_PY3K
- PyObject *s = PyUnicode_FromFormat("%s(Address %p, Size %zd, isWritable %s)",
- #else
- PyObject *s = PyBytes_FromFormat("%s(Address %p, Size %zd, isWritable %s)",
- #endif
- Py_TYPE(sbkObject)->tp_name,
- sbkObject->cptr,
- sbkObject->size,
- sbkObject->isWritable ? trueString : falseString);
- Py_XINCREF(s);
- return s;
-}
-
-
-static int SbkVoidPtrObject_getbuffer(PyObject *obj, Py_buffer *view, int flags)
-{
- if (view == nullptr)
- return -1;
-
- auto *sbkObject = reinterpret_cast<SbkVoidPtrObject *>(obj);
- if (sbkObject->size < 0)
- return -1;
-
- int readonly = sbkObject->isWritable ? 0 : 1;
- if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
- (readonly == 1)) {
- PyErr_SetString(PyExc_BufferError,
- "Object is not writable.");
- return -1;
- }
-
- view->obj = obj;
- if (obj)
- Py_XINCREF(obj);
- view->buf = sbkObject->cptr;
- view->len = sbkObject->size;
- view->readonly = readonly;
- view->itemsize = 1;
- view->format = nullptr;
- if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
- view->format = const_cast<char *>("B");
- view->ndim = 1;
- view->shape = nullptr;
- if ((flags & PyBUF_ND) == PyBUF_ND)
- view->shape = &(view->len);
- view->strides = nullptr;
- if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
- view->strides = &(view->itemsize);
- view->suboffsets = nullptr;
- view->internal = nullptr;
- return 0;
-}
-
-#if PY_VERSION_HEX < 0x03000000
-
-static Py_ssize_t SbkVoidPtrObject_readbufferproc(PyObject *self, Py_ssize_t segment, void **ptrptr)
-{
- if (segment || !Shiboken::Object::isValid(self))
- return -1;
-
- SbkVoidPtrObject *sbkObject = reinterpret_cast<SbkVoidPtrObject *>(self);
- *ptrptr = reinterpret_cast<void *>(sbkObject->cptr);
- return sbkObject->size;
-}
-
-static Py_ssize_t SbkVoidPtrObject_segcountproc(PyObject *self, Py_ssize_t *lenp)
-{
- if (lenp) {
- SbkVoidPtrObject *sbkObject = reinterpret_cast<SbkVoidPtrObject *>(self);
- *lenp = sbkObject->size;
- }
- return 1;
-}
-
-PyBufferProcs SbkVoidPtrObjectBufferProc = {
- &SbkVoidPtrObject_readbufferproc, // bf_getreadbuffer
- (writebufferproc)&SbkVoidPtrObject_readbufferproc, // bf_getwritebuffer
- &SbkVoidPtrObject_segcountproc, // bf_getsegcount
- (charbufferproc)&SbkVoidPtrObject_readbufferproc, // bf_getcharbuffer
- (getbufferproc)SbkVoidPtrObject_getbuffer, // bf_getbuffer
-};
-
-#else
-
-static PyBufferProcs SbkVoidPtrObjectBufferProc = {
- (getbufferproc)SbkVoidPtrObject_getbuffer, // bf_getbuffer
- (releasebufferproc)nullptr // bf_releasebuffer
-};
-
-#endif
-
-// Void pointer type definition.
-static PyType_Slot SbkVoidPtrType_slots[] = {
- {Py_tp_repr, (void *)SbkVoidPtrObject_repr},
- {Py_nb_int, (void *)SbkVoidPtrObject_int},
- {Py_sq_length, (void *)SbkVoidPtrObject_length},
- {Py_tp_str, (void *)SbkVoidPtrObject_str},
- {Py_tp_richcompare, (void *)SbkVoidPtrObject_richcmp},
- {Py_tp_init, (void *)SbkVoidPtrObject_init},
- {Py_tp_new, (void *)SbkVoidPtrObject_new},
- {Py_tp_dealloc, (void *)Sbk_object_dealloc},
- {Py_tp_methods, (void *)SbkVoidPtrObject_methods},
- {0, nullptr}
-};
-static PyType_Spec SbkVoidPtrType_spec = {
- "2:shiboken2.shiboken2.VoidPtr",
- sizeof(SbkVoidPtrObject),
- 0,
- Py_TPFLAGS_DEFAULT,
- SbkVoidPtrType_slots,
-};
-
-
-}
-
-PyTypeObject *SbkVoidPtrTypeF(void)
-{
- static PyTypeObject *type = nullptr;
- if (!type) {
- type = reinterpret_cast<PyTypeObject *>(SbkType_FromSpec(&SbkVoidPtrType_spec));
-#if PY_VERSION_HEX < 0x03000000
- type->tp_as_buffer = &SbkVoidPtrObjectBufferProc;
- type->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
-#else
- PepType_AS_BUFFER(type) = &SbkVoidPtrObjectBufferProc;
-#endif
- }
- return type;
-}
-
-namespace VoidPtr {
-
-static int voidPointerInitialized = false;
-
-void init()
-{
- if (PyType_Ready(reinterpret_cast<PyTypeObject *>(SbkVoidPtrTypeF())) < 0)
- Py_FatalError("[libshiboken] Failed to initialize Shiboken.VoidPtr type.");
- else
- voidPointerInitialized = true;
-}
-
-void addVoidPtrToModule(PyObject *module)
-{
- if (voidPointerInitialized) {
- Py_INCREF(SbkVoidPtrTypeF());
- PyModule_AddObject(module, PepType_GetNameStr(SbkVoidPtrTypeF()),
- reinterpret_cast<PyObject *>(SbkVoidPtrTypeF()));
- }
-}
-
-static PyObject *createVoidPtr(void *cppIn, Py_ssize_t size = 0, bool isWritable = false)
-{
- if (!cppIn)
- Py_RETURN_NONE;
-
- SbkVoidPtrObject *result = PyObject_New(SbkVoidPtrObject, SbkVoidPtrTypeF());
- if (!result)
- Py_RETURN_NONE;
-
- result->cptr = cppIn;
- result->size = size;
- result->isWritable = isWritable;
-
- return reinterpret_cast<PyObject *>(result);
-}
-
-static PyObject *toPython(const void *cppIn)
-{
- return createVoidPtr(const_cast<void *>(cppIn));
-}
-
-static void VoidPtrToCpp(PyObject *pyIn, void *cppOut)
-{
- auto *sbkIn = reinterpret_cast<SbkVoidPtrObject *>(pyIn);
- *reinterpret_cast<void **>(cppOut) = sbkIn->cptr;
-}
-
-static PythonToCppFunc VoidPtrToCppIsConvertible(PyObject *pyIn)
-{
- return SbkVoidPtr_Check(pyIn) ? VoidPtrToCpp : nullptr;
-}
-
-static void SbkObjectToCpp(PyObject *pyIn, void *cppOut)
-{
- auto *sbkIn = reinterpret_cast<SbkObject *>(pyIn);
- *reinterpret_cast<void **>(cppOut) = sbkIn->d->cptr[0];
-}
-
-static PythonToCppFunc SbkObjectToCppIsConvertible(PyObject *pyIn)
-{
- return Shiboken::Object::checkType(pyIn) ? SbkObjectToCpp : nullptr;
-}
-
-static void PythonBufferToCpp(PyObject *pyIn, void *cppOut)
-{
- if (PyObject_CheckBuffer(pyIn)) {
- Py_buffer bufferView;
-
- // Bail out if the object can't provide a simple contiguous buffer.
- if (PyObject_GetBuffer(pyIn, &bufferView, PyBUF_SIMPLE) < 0)
- return;
-
- *reinterpret_cast<void **>(cppOut) = bufferView.buf;
-
- // Release the buffer.
- PyBuffer_Release(&bufferView);
- }
-}
-
-static PythonToCppFunc PythonBufferToCppIsConvertible(PyObject *pyIn)
-{
- if (PyObject_CheckBuffer(pyIn)) {
- Py_buffer bufferView;
-
- // Bail out if the object can't provide a simple contiguous buffer.
- if (PyObject_GetBuffer(pyIn, &bufferView, PyBUF_SIMPLE) < 0)
- return nullptr;
-
- // Release the buffer.
- PyBuffer_Release(&bufferView);
-
- return PythonBufferToCpp;
- }
- return nullptr;
-}
-
-SbkConverter *createConverter()
-{
- SbkConverter *converter = Shiboken::Conversions::createConverter(SbkVoidPtrTypeF(), toPython);
- Shiboken::Conversions::addPythonToCppValueConversion(converter,
- VoidPtrToCpp,
- VoidPtrToCppIsConvertible);
- Shiboken::Conversions::addPythonToCppValueConversion(converter,
- SbkObjectToCpp,
- SbkObjectToCppIsConvertible);
- Shiboken::Conversions::addPythonToCppValueConversion(converter,
- PythonBufferToCpp,
- PythonBufferToCppIsConvertible);
- return converter;
-}
-
-} // namespace VoidPtr
diff --git a/sources/shiboken2/libshiboken/voidptr.h b/sources/shiboken2/libshiboken/voidptr.h
deleted file mode 100644
index e74c1045e..000000000
--- a/sources/shiboken2/libshiboken/voidptr.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef VOIDPTR_H
-#define VOIDPTR_H
-
-#include "sbkpython.h"
-#include "shibokenmacros.h"
-#include "sbkconverter.h"
-
-extern "C"
-{
-
-// Void pointer type declaration.
-extern LIBSHIBOKEN_API PyTypeObject *SbkVoidPtrTypeF(void);
-
-} // extern "C"
-
-namespace VoidPtr
-{
-
-void init();
-SbkConverter *createConverter();
-LIBSHIBOKEN_API void addVoidPtrToModule(PyObject *module);
-
-}
-
-
-#endif // VOIDPTR_H
diff --git a/sources/shiboken2/shiboken_tool.py b/sources/shiboken2/shiboken_tool.py
deleted file mode 100755
index 8494c5d57..000000000
--- a/sources/shiboken2/shiboken_tool.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#############################################################################
-##
-## Copyright (C) 2018 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-import sys
-import os
-import subprocess
-
-def main():
- # The tools listed as entrypoints in setup.py are copied to 'scripts/..'
- cmd = os.path.join("..", os.path.basename(sys.argv[0]))
- command = [os.path.join(os.path.dirname(os.path.realpath(__file__)), cmd)]
- command.extend(sys.argv[1:])
- sys.exit(subprocess.call(command))
-
-if __name__ == "__main__":
- main()
diff --git a/sources/shiboken2/shiboken_version.py b/sources/shiboken2/shiboken_version.py
deleted file mode 100644
index f5ef03613..000000000
--- a/sources/shiboken2/shiboken_version.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-major_version = "5"
-minor_version = "15"
-patch_version = "0"
-
-# For example: "a", "b", "rc"
-# (which means "alpha", "beta", "release candidate").
-# An empty string means the generated package will be an official release.
-release_version_type = "a"
-
-# For example: "1", "2" (which means "beta1", "beta2", if type is "b").
-pre_release_version = "1"
-
-if __name__ == '__main__':
- # Used by CMake.
- print('{0};{1};{2};{3};{4}'.format(major_version, minor_version, patch_version,
- release_version_type, pre_release_version))
diff --git a/sources/shiboken2/shibokenmodule/CMakeLists.txt b/sources/shiboken2/shibokenmodule/CMakeLists.txt
deleted file mode 100644
index e1eafa12f..000000000
--- a/sources/shiboken2/shibokenmodule/CMakeLists.txt
+++ /dev/null
@@ -1,88 +0,0 @@
-project(shibokenmodule)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/shibokenmodule.txt.in"
- "${CMAKE_CURRENT_BINARY_DIR}/shibokenmodule.txt" @ONLY)
-
-set(sample_SRC ${CMAKE_CURRENT_BINARY_DIR}/shiboken2/shiboken2_module_wrapper.cpp)
-
-set(shibokenmodule_TYPESYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/typesystem_shiboken.xml)
-
-add_custom_command(
-OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/mjb_rejected_classes.log"
-BYPRODUCTS ${sample_SRC}
-# Note: shiboken2 is an executable target. By not specifying its explicit
-# path, CMAKE figures it out, itself!
-# This fixes an issue with Visual Studio, see https://github.com/PySide/shiboken2/pull/11
-COMMAND shiboken2 --project-file=${CMAKE_CURRENT_BINARY_DIR}/shibokenmodule.txt ${GENERATOR_EXTRA_FLAGS}
-DEPENDS ${shibokenmodule_TYPESYSTEM}
-WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
-COMMENT "Running generator for 'shiboken2'..."
-)
-
-add_library(shibokenmodule MODULE ${sample_SRC})
-target_include_directories(shibokenmodule PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR})
-set_property(TARGET shibokenmodule PROPERTY PREFIX "")
-set_property(TARGET shibokenmodule PROPERTY OUTPUT_NAME "shiboken2${PYTHON_EXTENSION_SUFFIX}")
-
-if(WIN32)
- set_property(TARGET shibokenmodule PROPERTY SUFFIX ".pyd")
-endif()
-target_link_libraries(shibokenmodule PUBLIC libshiboken)
-
-create_generator_target(shibokenmodule)
-
-install(TARGETS shibokenmodule DESTINATION ${PYTHON_SITE_PACKAGES}/shiboken2)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/_config.py.in"
- "${CMAKE_CURRENT_BINARY_DIR}/_config.py" @ONLY)
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/_config.py"
- DESTINATION "${PYTHON_SITE_PACKAGES}/shiboken2")
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/__init__.py.in"
- "${CMAKE_CURRENT_BINARY_DIR}/__init__.py" @ONLY)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/__init__.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/__init__.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/__init__.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/__init__.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/errorhandler.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/errorhandler.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/layout.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/layout.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/loader.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/loader.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/importhandler.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/importhandler.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/mapping.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/mapping.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/parser.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/parser.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/lib/__init__.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/lib/__init__.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/lib/enum_sig.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/lib/enum_sig.py" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/signature/lib/tool.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/signature/lib/tool.py" COPYONLY)
-if (PYTHON_VERSION_MAJOR EQUAL 3)
-else()
- configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/backport_inspect.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/backport_inspect.py" COPYONLY)
- configure_file("${CMAKE_CURRENT_SOURCE_DIR}/files.dir/shibokensupport/typing27.py"
- "${CMAKE_CURRENT_BINARY_DIR}/files.dir/shibokensupport/typing27.py" COPYONLY)
-endif()
-install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/files.dir"
- DESTINATION "${PYTHON_SITE_PACKAGES}/shiboken2")
-
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/__init__.py"
- DESTINATION "${PYTHON_SITE_PACKAGES}/shiboken2")
-
-# Use absolute path instead of relative path, to avoid ninja build errors due to
-# duplicate file dependency inconsistency.
-set(shiboken_version_relative_path "${CMAKE_CURRENT_SOURCE_DIR}/../shiboken_version.py")
-get_filename_component(shiboken_version_path ${shiboken_version_relative_path} ABSOLUTE)
-configure_file("${shiboken_version_path}"
- "${CMAKE_CURRENT_BINARY_DIR}/_git_shiboken_module_version.py" @ONLY)
-
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/_git_shiboken_module_version.py"
- DESTINATION "${PYTHON_SITE_PACKAGES}/shiboken2")
diff --git a/sources/shiboken2/shibokenmodule/__init__.py.in b/sources/shiboken2/shibokenmodule/__init__.py.in
deleted file mode 100644
index ed6ce5623..000000000
--- a/sources/shiboken2/shibokenmodule/__init__.py.in
+++ /dev/null
@@ -1,30 +0,0 @@
-__version__ = "@FINAL_PACKAGE_VERSION@"
-__version_info__ = (@shiboken_MAJOR_VERSION@, @shiboken_MINOR_VERSION@, @shiboken_MICRO_VERSION@, "@shiboken_PRE_RELEASE_VERSION_TYPE@", "@shiboken_PRE_RELEASE_VERSION@")
-
-# PYSIDE-932: Python 2 cannot import 'zipfile' for embedding while being imported, itself.
-# We simply pre-load all imports for the signature extension.
-# Also, PyInstaller seems not always to be reliable in finding modules.
-# We explicitly import everything that is needed:
-import sys
-import os
-import zipfile
-import base64
-import marshal
-import io
-import contextlib
-import textwrap
-import traceback
-import types
-import struct
-import re
-import tempfile
-import keyword
-import functools
-if sys.version_info[0] == 3:
- # PyInstaller seems to sometimes fail:
- import typing
-
-from .shiboken2 import *
-
-# Trigger signature initialization.
-type.__signature__
diff --git a/sources/shiboken2/shibokenmodule/_config.py.in b/sources/shiboken2/shibokenmodule/_config.py.in
deleted file mode 100644
index 9607e5ca7..000000000
--- a/sources/shiboken2/shibokenmodule/_config.py.in
+++ /dev/null
@@ -1,11 +0,0 @@
-shiboken_library_soversion = str(@shiboken2_library_so_version@)
-
-version = "@FINAL_PACKAGE_VERSION@"
-version_info = (@shiboken_MAJOR_VERSION@, @shiboken_MINOR_VERSION@, @shiboken_MICRO_VERSION@, "@shiboken_PRE_RELEASE_VERSION_TYPE@", "@shiboken_PRE_RELEASE_VERSION@")
-
-@PACKAGE_BUILD_DATE@
-@PACKAGE_BUILD_COMMIT_DATE@
-@PACKAGE_BUILD_COMMIT_HASH@
-@PACKAGE_BUILD_COMMIT_HASH_DESCRIBED@
-@PACKAGE_SETUP_PY_PACKAGE_TIMESTAMP_ASSIGNMENT@
-@PACKAGE_SETUP_PY_PACKAGE_VERSION_ASSIGNMENT@
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/__init__.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/__init__.py
deleted file mode 100644
index 2d640cb89..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/__init__.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2018 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-# this file intentionally left blank
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/backport_inspect.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/backport_inspect.py
deleted file mode 100644
index 0f9598c64..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/backport_inspect.py
+++ /dev/null
@@ -1,900 +0,0 @@
-# This Python file uses the following encoding: utf-8
-# It has been edited by fix-complaints.py .
-
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function
-
-"""
-PSF LICENSE AGREEMENT FOR PYTHON 3.7.0
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
- the Individual or Organization ("Licensee") accessing and otherwise using Python
- 3.7.0 software in source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
- grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
- analyze, test, perform and/or display publicly, prepare derivative works,
- distribute, and otherwise use Python 3.7.0 alone or in any derivative
- version, provided, however, that PSF's License Agreement and PSF's notice of
- copyright, i.e., "Copyright © 2001-2018 Python Software Foundation; All Rights
- Reserved" are retained in Python 3.7.0 alone or in any derivative version
- prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on or
- incorporates Python 3.7.0 or any part thereof, and wants to make the
- derivative work available to others as provided herein, then Licensee hereby
- agrees to include in any such work a brief summary of the changes made to Python
- 3.7.0.
-
-4. PSF is making Python 3.7.0 available to Licensee on an "AS IS" basis.
- PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
- EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
- WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
- USE OF PYTHON 3.7.0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.7.0
- FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
- MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.7.0, OR ANY DERIVATIVE
- THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material breach of
- its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any relationship
- of agency, partnership, or joint venture between PSF and Licensee. This License
- Agreement does not grant permission to use PSF trademarks or trade name in a
- trademark sense to endorse or promote products or services of Licensee, or any
- third party.
-
-8. By copying, installing or otherwise using Python 3.7.0, Licensee agrees
- to be bound by the terms and conditions of this License Agreement.
-"""
-
-__doc__ = """
- signature() - get a Signature object for the callable
-"""
-
-import sys
-from collections import OrderedDict
-
-CO_OPTIMIZED = 0x0001
-CO_NEWLOCALS = 0x0002
-CO_VARARGS = 0x0004
-CO_VARKEYWORDS = 0x0008
-CO_NESTED = 0x0010
-CO_GENERATOR = 0x0020
-CO_NOFREE = 0x0040
-
-
-###############################################################################
-### Function Signature Object (PEP 362)
-###############################################################################
-
-
-
-# PYSIDE-1286: We now use the added __qualname__ for classes.
-def _get_class_name(cls):
- return getattr(cls, "__qualname__", cls.__name__)
-
-# This function was changed: 'builtins' and 'qualname' don't exist.
-# We use '__builtin__' and '__(qual)?name__' instead.
-def formatannotation(annotation, base_module=None):
- if getattr(annotation, '__module__', None) == 'typing':
- # The replace must not be done on Python 2.7 because it
- # already happens somewhere else.
- return repr(annotation) ##.replace('typing.', '')
- if isinstance(annotation, type):
- if annotation.__module__ in ('__builtin__', base_module):
- return _get_class_name(annotation)
- return annotation.__module__ + '.' + _get_class_name(annotation)
- return repr(annotation)
-
-
-def _signature_is_functionlike(obj):
- """Private helper to test if `obj` is a duck type of FunctionType.
- A good example of such objects are functions compiled with
- Cython, which have all attributes that a pure Python function
- would have, but have their code statically compiled.
- """
-
- if not callable(obj) or isclass(obj):
- # All function-like objects are obviously callables,
- # and not classes.
- return False
-
- name = getattr(obj, '__name__', None)
- code = getattr(obj, '__code__', None)
- defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
- kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
- annotations = getattr(obj, '__annotations__', None)
-
- return (isinstance(code, types.CodeType) and
- isinstance(name, str) and
- (defaults is None or isinstance(defaults, tuple)) and
- (kwdefaults is None or isinstance(kwdefaults, dict)) and
- isinstance(annotations, dict))
-
-
-
-def _signature_from_function(cls, func):
- """Private helper: constructs Signature for the given python function."""
-
- is_duck_function = False
- if not isfunction(func):
- if _signature_is_functionlike(func):
- is_duck_function = True
- else:
- # If it's not a pure Python function, and not a duck type
- # of pure function:
- raise TypeError('{!r} is not a Python function'.format(func))
-
- Parameter = cls._parameter_cls
-
- # Parameter information.
- func_code = func.__code__
- pos_count = func_code.co_argcount
- arg_names = func_code.co_varnames
- positional = tuple(arg_names[:pos_count])
- keyword_only_count = 0 # func_code.co_kwonlyargcount
- keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
- annotations = func.__annotations__
- defaults = func.__defaults__
- kwdefaults = func.__kwdefaults__
-
- if defaults:
- pos_default_count = len(defaults)
- else:
- pos_default_count = 0
-
- parameters = []
-
- # Non-keyword-only parameters w/o defaults.
- non_default_count = pos_count - pos_default_count
- for name in positional[:non_default_count]:
- annotation = annotations.get(name, _empty)
- parameters.append(Parameter(name, annotation=annotation,
- kind=_POSITIONAL_OR_KEYWORD))
-
- # ... w/ defaults.
- for offset, name in enumerate(positional[non_default_count:]):
- annotation = annotations.get(name, _empty)
- parameters.append(Parameter(name, annotation=annotation,
- kind=_POSITIONAL_OR_KEYWORD,
- default=defaults[offset]))
-
- # *args
- if func_code.co_flags & CO_VARARGS:
- name = arg_names[pos_count + keyword_only_count]
- annotation = annotations.get(name, _empty)
- parameters.append(Parameter(name, annotation=annotation,
- kind=_VAR_POSITIONAL))
-
- # Keyword-only parameters.
- for name in keyword_only:
- default = _empty
- if kwdefaults is not None:
- default = kwdefaults.get(name, _empty)
-
- annotation = annotations.get(name, _empty)
- parameters.append(Parameter(name, annotation=annotation,
- kind=_KEYWORD_ONLY,
- default=default))
- # **kwargs
- if func_code.co_flags & CO_VARKEYWORDS:
- index = pos_count + keyword_only_count
- if func_code.co_flags & CO_VARARGS:
- index += 1
-
- name = arg_names[index]
- annotation = annotations.get(name, _empty)
- parameters.append(Parameter(name, annotation=annotation,
- kind=_VAR_KEYWORD))
-
- # Is 'func' is a pure Python function - don't validate the
- # parameters list (for correct order and defaults), it should be OK.
- return cls(parameters,
- return_annotation=annotations.get('return', _empty),
- __validate_parameters__=is_duck_function)
-
-
-
-
-class _void(object):
- """A private marker - used in Parameter & Signature."""
-
-
-class _empty(object):
- """Marker object for Signature.empty and Parameter.empty."""
-
-
-class _ParameterKind(object): # (enum.IntEnum):
- POSITIONAL_ONLY = 0
- POSITIONAL_OR_KEYWORD = 1
- VAR_POSITIONAL = 2
- KEYWORD_ONLY = 3
- VAR_KEYWORD = 4
-
- def __str__(self):
- return self._name_
-
-
-_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
-_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
-_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
-_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
-_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
-
-
-class Parameter(object):
- """Represents a parameter in a function signature.
-
- Has the following public attributes:
-
- * name : str
- The name of the parameter as a string.
- * default : object
- The default value for the parameter if specified. If the
- parameter has no default value, this attribute is set to
- `Parameter.empty`.
- * annotation
- The annotation for the parameter if specified. If the
- parameter has no annotation, this attribute is set to
- `Parameter.empty`.
- * kind : str
- Describes how argument values are bound to the parameter.
- Possible values: `Parameter.POSITIONAL_ONLY`,
- `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
- `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
- """
-
- __slots__ = ('_name', '_kind', '_default', '_annotation')
-
- POSITIONAL_ONLY = _POSITIONAL_ONLY
- POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
- VAR_POSITIONAL = _VAR_POSITIONAL
- KEYWORD_ONLY = _KEYWORD_ONLY
- VAR_KEYWORD = _VAR_KEYWORD
-
- empty = _empty
-
- def __init__(self, name, kind, default=_empty, annotation=_empty):
-
- if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
- _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
- raise ValueError("invalid value for 'Parameter.kind' attribute")
- self._kind = kind
-
- if default is not _empty:
- if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
- msg = '{} parameters cannot have default values'.format(kind)
- raise ValueError(msg)
- self._default = default
- self._annotation = annotation
-
- if name is _empty:
- raise ValueError('name is a required attribute for Parameter')
-
- if not isinstance(name, str):
- raise TypeError("name must be a str, not a {!r}".format(name))
-
- if name[0] == '.' and name[1:].isdigit():
- # These are implicit arguments generated by comprehensions. In
- # order to provide a friendlier interface to users, we recast
- # their name as "implicitN" and treat them as positional-only.
- # See issue 19611.
- if kind != _POSITIONAL_OR_KEYWORD:
- raise ValueError(
- 'implicit arguments must be passed in as {}'.format(
- _POSITIONAL_OR_KEYWORD
- )
- )
- self._kind = _POSITIONAL_ONLY
- name = 'implicit{}'.format(name[1:])
-
- if not True: # name.isidentifier():
- raise ValueError('{!r} is not a valid parameter name'.format(name))
-
- self._name = name
-
- def __reduce__(self):
- return (type(self),
- (self._name, self._kind),
- {'_default': self._default,
- '_annotation': self._annotation})
-
- def __setstate__(self, state):
- self._default = state['_default']
- self._annotation = state['_annotation']
-
- @property
- def name(self):
- return self._name
-
- @property
- def default(self):
- return self._default
-
- @property
- def annotation(self):
- return self._annotation
-
- @property
- def kind(self):
- return self._kind
-
- def replace(self, name=_void, kind=_void,
- annotation=_void, default=_void):
- """Creates a customized copy of the Parameter."""
-
- if name is _void:
- name = self._name
-
- if kind is _void:
- kind = self._kind
-
- if annotation is _void:
- annotation = self._annotation
-
- if default is _void:
- default = self._default
-
- return type(self)(name, kind, default=default, annotation=annotation)
-
- def __str__(self):
- kind = self.kind
- formatted = self._name
-
- # Add annotation and default value
- if self._annotation is not _empty:
- formatted = '{}: {}'.format(formatted,
- formatannotation(self._annotation))
-
- if self._default is not _empty:
- formatted = '{}={}'.format(formatted, repr(self._default))
-
- if kind == _VAR_POSITIONAL:
- formatted = '*' + formatted
- elif kind == _VAR_KEYWORD:
- formatted = '**' + formatted
-
- return formatted
-
- def __repr__(self):
- return '<{} "{}">'.format(_get_class_name(self.__class__), self)
-
- def __hash__(self):
- return hash((self.name, self.kind, self.annotation, self.default))
-
- def __eq__(self, other):
- if self is other:
- return True
- if not isinstance(other, Parameter):
- return NotImplemented
- return (self._name == other._name and
- self._kind == other._kind and
- self._default == other._default and
- self._annotation == other._annotation)
-
-
-class BoundArguments(object):
- """Result of `Signature.bind` call. Holds the mapping of arguments
- to the function's parameters.
-
- Has the following public attributes:
-
- * arguments : OrderedDict
- An ordered mutable mapping of parameters' names to arguments' values.
- Does not contain arguments' default values.
- * signature : Signature
- The Signature object that created this instance.
- * args : tuple
- Tuple of positional arguments values.
- * kwargs : dict
- Dict of keyword arguments values.
- """
-
- __slots__ = ('arguments', '_signature', '__weakref__')
-
- def __init__(self, signature, arguments):
- self.arguments = arguments
- self._signature = signature
-
- @property
- def signature(self):
- return self._signature
-
- @property
- def args(self):
- args = []
- for param_name, param in self._signature.parameters.items():
- if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
- break
-
- try:
- arg = self.arguments[param_name]
- except KeyError:
- # We're done here. Other arguments
- # will be mapped in 'BoundArguments.kwargs'
- break
- else:
- if param.kind == _VAR_POSITIONAL:
- # *args
- args.extend(arg)
- else:
- # plain argument
- args.append(arg)
-
- return tuple(args)
-
- @property
- def kwargs(self):
- kwargs = {}
- kwargs_started = False
- for param_name, param in self._signature.parameters.items():
- if not kwargs_started:
- if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
- kwargs_started = True
- else:
- if param_name not in self.arguments:
- kwargs_started = True
- continue
-
- if not kwargs_started:
- continue
-
- try:
- arg = self.arguments[param_name]
- except KeyError:
- pass
- else:
- if param.kind == _VAR_KEYWORD:
- # **kwargs
- kwargs.update(arg)
- else:
- # plain keyword argument
- kwargs[param_name] = arg
-
- return kwargs
-
- def apply_defaults(self):
- """Set default values for missing arguments.
-
- For variable-positional arguments (*args) the default is an
- empty tuple.
-
- For variable-keyword arguments (**kwargs) the default is an
- empty dict.
- """
- arguments = self.arguments
- new_arguments = []
- for name, param in self._signature.parameters.items():
- try:
- new_arguments.append((name, arguments[name]))
- except KeyError:
- if param.default is not _empty:
- val = param.default
- elif param.kind is _VAR_POSITIONAL:
- val = ()
- elif param.kind is _VAR_KEYWORD:
- val = {}
- else:
- # This BoundArguments was likely produced by
- # Signature.bind_partial().
- continue
- new_arguments.append((name, val))
- self.arguments = OrderedDict(new_arguments)
-
- def __eq__(self, other):
- if self is other:
- return True
- if not isinstance(other, BoundArguments):
- return NotImplemented
- return (self.signature == other.signature and
- self.arguments == other.arguments)
-
- def __setstate__(self, state):
- self._signature = state['_signature']
- self.arguments = state['arguments']
-
- def __getstate__(self):
- return {'_signature': self._signature, 'arguments': self.arguments}
-
- def __repr__(self):
- args = []
- for arg, value in self.arguments.items():
- args.append('{}={!r}'.format(arg, value))
- return '<{} ({})>'.format(_get_class_name(self.__class__), ', '.join(args))
-
-
-class Signature(object):
- """A Signature object represents the overall signature of a function.
- It stores a Parameter object for each parameter accepted by the
- function, as well as information specific to the function itself.
-
- A Signature object has the following public attributes and methods:
-
- * parameters : OrderedDict
- An ordered mapping of parameters' names to the corresponding
- Parameter objects (keyword-only arguments are in the same order
- as listed in `code.co_varnames`).
- * return_annotation : object
- The annotation for the return type of the function if specified.
- If the function has no annotation for its return type, this
- attribute is set to `Signature.empty`.
- * bind(*args, **kwargs) -> BoundArguments
- Creates a mapping from positional and keyword arguments to
- parameters.
- * bind_partial(*args, **kwargs) -> BoundArguments
- Creates a partial mapping from positional and keyword arguments
- to parameters (simulating 'functools.partial' behavior.)
- """
-
- __slots__ = ('_return_annotation', '_parameters')
-
- _parameter_cls = Parameter
- _bound_arguments_cls = BoundArguments
-
- empty = _empty
-
- def __init__(self, parameters=None, return_annotation=_empty,
- __validate_parameters__=True):
- """Constructs Signature from the given list of Parameter
- objects and 'return_annotation'. All arguments are optional.
- """
-
- if parameters is None:
- params = OrderedDict()
- else:
- if __validate_parameters__:
- params = OrderedDict()
- top_kind = _POSITIONAL_ONLY
- kind_defaults = False
-
- for idx, param in enumerate(parameters):
- kind = param.kind
- name = param.name
-
- if kind < top_kind:
- msg = 'wrong parameter order: {!r} before {!r}'
- msg = msg.format(top_kind, kind)
- raise ValueError(msg)
- elif kind > top_kind:
- kind_defaults = False
- top_kind = kind
-
- if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
- if param.default is _empty:
- if kind_defaults:
- # No default for this parameter, but the
- # previous parameter of the same kind had
- # a default
- msg = 'non-default argument follows default ' \
- 'argument'
- raise ValueError(msg)
- else:
- # There is a default for this parameter.
- kind_defaults = True
-
- if name in params:
- msg = 'duplicate parameter name: {!r}'.format(name)
- raise ValueError(msg)
-
- params[name] = param
- else:
- params = OrderedDict(((param.name, param)
- for param in parameters))
-
- self._parameters = params # types.MappingProxyType(params)
- self._return_annotation = return_annotation
-
- @classmethod
- def from_function(cls, func):
- """Constructs Signature for the given python function."""
-
- warnings.warn("inspect.Signature.from_function() is deprecated, "
- "use Signature.from_callable()",
- DeprecationWarning, stacklevel=2)
- return _signature_from_function(cls, func)
-
- @classmethod
- def from_builtin(cls, func):
- """Constructs Signature for the given builtin function."""
-
- warnings.warn("inspect.Signature.from_builtin() is deprecated, "
- "use Signature.from_callable()",
- DeprecationWarning, stacklevel=2)
- return _signature_from_builtin(cls, func)
-
- @classmethod
- def from_callable(cls, obj, follow_wrapped=True):
- """Constructs Signature for the given callable object."""
- return _signature_from_callable(obj, sigcls=cls,
- follow_wrapper_chains=follow_wrapped)
-
- @property
- def parameters(self):
- return self._parameters
-
- @property
- def return_annotation(self):
- return self._return_annotation
-
- def replace(self, parameters=_void, return_annotation=_void):
- """Creates a customized copy of the Signature.
- Pass 'parameters' and/or 'return_annotation' arguments
- to override them in the new copy.
- """
-
- if parameters is _void:
- parameters = self.parameters.values()
-
- if return_annotation is _void:
- return_annotation = self._return_annotation
-
- return type(self)(parameters,
- return_annotation=return_annotation)
-
- def _hash_basis(self):
- params = tuple(param for param in self.parameters.values()
- if param.kind != _KEYWORD_ONLY)
-
- kwo_params = {param.name: param for param in self.parameters.values()
- if param.kind == _KEYWORD_ONLY}
-
- return params, kwo_params, self.return_annotation
-
- def __hash__(self):
- params, kwo_params, return_annotation = self._hash_basis()
- kwo_params = frozenset(kwo_params.values())
- return hash((params, kwo_params, return_annotation))
-
- def __eq__(self, other):
- if self is other:
- return True
- if not isinstance(other, Signature):
- return NotImplemented
- return self._hash_basis() == other._hash_basis()
-
- def _bind(self, args, kwargs, partial=False):
- """Private method. Don't use directly."""
-
- arguments = OrderedDict()
-
- parameters = iter(self.parameters.values())
- parameters_ex = ()
- arg_vals = iter(args)
-
- while True:
- # Let's iterate through the positional arguments and corresponding
- # parameters
- try:
- arg_val = next(arg_vals)
- except StopIteration:
- # No more positional arguments
- try:
- param = next(parameters)
- except StopIteration:
- # No more parameters. That's it. Just need to check that
- # we have no `kwargs` after this while loop
- break
- else:
- if param.kind == _VAR_POSITIONAL:
- # That's OK, just empty *args. Let's start parsing
- # kwargs
- break
- elif param.name in kwargs:
- if param.kind == _POSITIONAL_ONLY:
- msg = '{arg!r} parameter is positional only, ' \
- 'but was passed as a keyword'
- msg = msg.format(arg=param.name)
- raise TypeError(msg)# from None
- parameters_ex = (param,)
- break
- elif (param.kind == _VAR_KEYWORD or
- param.default is not _empty):
- # That's fine too - we have a default value for this
- # parameter. So, lets start parsing `kwargs`, starting
- # with the current parameter
- parameters_ex = (param,)
- break
- else:
- # No default, not VAR_KEYWORD, not VAR_POSITIONAL,
- # not in `kwargs`
- if partial:
- parameters_ex = (param,)
- break
- else:
- msg = 'missing a required argument: {arg!r}'
- msg = msg.format(arg=param.name)
- raise TypeError(msg)# from None
- else:
- # We have a positional argument to process
- try:
- param = next(parameters)
- except StopIteration:
- raise TypeError('too many positional arguments')# from None
- else:
- if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
- # Looks like we have no parameter for this positional
- # argument
- raise TypeError(
- 'too many positional arguments')# from None
-
- if param.kind == _VAR_POSITIONAL:
- # We have an '*args'-like argument, let's fill it with
- # all positional arguments we have left and move on to
- # the next phase
- values = [arg_val]
- values.extend(arg_vals)
- arguments[param.name] = tuple(values)
- break
-
- if param.name in kwargs:
- raise TypeError(
- 'multiple values for argument {arg!r}'.format(
- arg=param.name))# from None
-
- arguments[param.name] = arg_val
-
- # Now, we iterate through the remaining parameters to process
- # keyword arguments
- kwargs_param = None
- for param in itertools.chain(parameters_ex, parameters):
- if param.kind == _VAR_KEYWORD:
- # Memorize that we have a '**kwargs'-like parameter
- kwargs_param = param
- continue
-
- if param.kind == _VAR_POSITIONAL:
- # Named arguments don't refer to '*args'-like parameters.
- # We only arrive here if the positional arguments ended
- # before reaching the last parameter before *args.
- continue
-
- param_name = param.name
- try:
- arg_val = kwargs.pop(param_name)
- except KeyError:
- # We have no value for this parameter. It's fine though,
- # if it has a default value, or it is an '*args'-like
- # parameter, left alone by the processing of positional
- # arguments.
- if (not partial and param.kind != _VAR_POSITIONAL and
- param.default is _empty):
- raise TypeError('missing a required argument: {arg!r}'. \
- format(arg=param_name))# from None
-
- else:
- if param.kind == _POSITIONAL_ONLY:
- # This should never happen in case of a properly built
- # Signature object (but let's have this check here
- # to ensure correct behavior just in case)
- raise TypeError('{arg!r} parameter is positional only, '
- 'but was passed as a keyword'. \
- format(arg=param.name))
-
- arguments[param_name] = arg_val
-
- if kwargs:
- if kwargs_param is not None:
- # Process our '**kwargs'-like parameter
- arguments[kwargs_param.name] = kwargs
- else:
- raise TypeError(
- 'got an unexpected keyword argument {arg!r}'.format(
- arg=next(iter(kwargs))))
-
- return self._bound_arguments_cls(self, arguments)
-
- def bind(*args, **kwargs):
- """Get a BoundArguments object, that maps the passed `args`
- and `kwargs` to the function's signature. Raises `TypeError`
- if the passed arguments can not be bound.
- """
- return args[0]._bind(args[1:], kwargs)
-
- def bind_partial(*args, **kwargs):
- """Get a BoundArguments object, that partially maps the
- passed `args` and `kwargs` to the function's signature.
- Raises `TypeError` if the passed arguments can not be bound.
- """
- return args[0]._bind(args[1:], kwargs, partial=True)
-
- def __reduce__(self):
- return (type(self),
- (tuple(self._parameters.values()),),
- {'_return_annotation': self._return_annotation})
-
- def __setstate__(self, state):
- self._return_annotation = state['_return_annotation']
-
- def __repr__(self):
- return '<{} {}>'.format(_get_class_name(self.__class__), self)
-
- def __str__(self):
- result = []
- render_pos_only_separator = False
- render_kw_only_separator = True
- for param in self.parameters.values():
- formatted = str(param)
-
- kind = param.kind
-
- if kind == _POSITIONAL_ONLY:
- render_pos_only_separator = True
- elif render_pos_only_separator:
- # It's not a positional-only parameter, and the flag
- # is set to 'True' (there were pos-only params before.)
- result.append('/')
- render_pos_only_separator = False
-
- if kind == _VAR_POSITIONAL:
- # OK, we have an '*args'-like parameter, so we won't need
- # a '*' to separate keyword-only arguments
- render_kw_only_separator = False
- elif kind == _KEYWORD_ONLY and render_kw_only_separator:
- # We have a keyword-only parameter to render and we haven't
- # rendered an '*args'-like parameter before, so add a '*'
- # separator to the parameters list ("foo(arg1, *, arg2)" case)
- result.append('*')
- # This condition should be only triggered once, so
- # reset the flag
- render_kw_only_separator = False
-
- result.append(formatted)
-
- if render_pos_only_separator:
- # There were only positional-only parameters, hence the
- # flag was not reset to 'False'
- result.append('/')
-
- rendered = '({})'.format(', '.join(result))
-
- if self.return_annotation is not _empty:
- anno = formatannotation(self.return_annotation)
- rendered += ' -> {}'.format(anno)
-
- return rendered
-
-
-def signature(obj, follow_wrapped=True):
- """Get a signature object for the passed callable."""
- return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/fix-complaints.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/fix-complaints.py
deleted file mode 100644
index 3818ad602..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/fix-complaints.py
+++ /dev/null
@@ -1,98 +0,0 @@
-# This Python file uses the following encoding: utf-8
-# It has been edited by fix-complaints.py .
-
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-"""
-fix-complaints.py
-
-This module fixes the buildbot messages of external python files.
-Run it once after copying a new version. It is idem-potent, unless
-you are changing messages (what I did, of course :-) .
-"""
-
-import os
-import glob
-
-patched_file_patterns = "backport_inspect.py typing27.py python_minilib_*.py"
-
-offending_words = {
- "behavio""ur": "behavior",
- "at""least": "at_least",
- "reali""sed": "realized",
-}
-
-utf8_line = "# This Python file uses the following encoding: utf-8\n"
-marker_line = "# It has been edited by {} .\n".format(
- os.path.basename(__file__))
-
-def patch_file(fname):
- with open(fname) as f:
- lines = f.readlines()
- dup = lines[:]
- for idx, line in enumerate(lines):
- for word, repl in offending_words.items():
- if word in line:
- lines[idx] = line.replace(word, repl)
- print("line:{!r} {!r}->{!r}".format(line, word, repl))
- if lines[0].strip() != utf8_line.strip():
- lines[:0] = [utf8_line, "\n"]
- if lines[1] != marker_line:
- lines[1:1] = marker_line
- if lines != dup:
- with open(fname, "w") as f:
- f.write("".join(lines))
-
-def doit():
- dirname = os.path.dirname(__file__)
- patched_files = []
- for name in patched_file_patterns.split():
- pattern = os.path.join(dirname, name)
- patched_files += glob.glob(pattern)
- for fname in patched_files:
- print("Working on", fname)
- patch_file(fname)
-
-if __name__ == "__main__":
- doit()
-
-# end of file
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/PSF-3.7.0.txt b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/PSF-3.7.0.txt
deleted file mode 100644
index be42010dd..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/PSF-3.7.0.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-PSF LICENSE AGREEMENT FOR PYTHON 3.7.0
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
- the Individual or Organization ("Licensee") accessing and otherwise using Python
- 3.7.0 software in source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
- grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
- analyze, test, perform and/or display publicly, prepare derivative works,
- distribute, and otherwise use Python 3.7.0 alone or in any derivative
- version, provided, however, that PSF's License Agreement and PSF's notice of
- copyright, i.e., "Copyright © 2001-2018 Python Software Foundation; All Rights
- Reserved" are retained in Python 3.7.0 alone or in any derivative version
- prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on or
- incorporates Python 3.7.0 or any part thereof, and wants to make the
- derivative work available to others as provided herein, then Licensee hereby
- agrees to include in any such work a brief summary of the changes made to Python
- 3.7.0.
-
-4. PSF is making Python 3.7.0 available to Licensee on an "AS IS" basis.
- PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
- EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
- WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
- USE OF PYTHON 3.7.0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.7.0
- FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
- MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.7.0, OR ANY DERIVATIVE
- THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material breach of
- its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any relationship
- of agency, partnership, or joint venture between PSF and Licensee. This License
- Agreement does not grant permission to use PSF trademarks or trade name in a
- trademark sense to endorse or promote products or services of Licensee, or any
- third party.
-
-8. By copying, installing or otherwise using Python 3.7.0, Licensee agrees
- to be bound by the terms and conditions of this License Agreement.
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/__init__.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/__init__.py
deleted file mode 100644
index ee541d0ea..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/__init__.py
+++ /dev/null
@@ -1,42 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-__all__ = "get_signature layout mapping lib".split()
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/errorhandler.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/errorhandler.py
deleted file mode 100644
index 4dbed077d..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/errorhandler.py
+++ /dev/null
@@ -1,148 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2020 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-"""
-errorhandler.py
-
-This module handles the TypeError messages which were previously
-produced by the generated C code.
-
-This version is at least consistent with the signatures, which
-are created by the same module.
-
-Experimentally, we are trying to guess those errors which are
-just the wrong number of elements in an iterator.
-At the moment, it is unclear whether the information given is
-enough to produce a useful ValueError.
-
-This matter will be improved in a later version.
-"""
-
-import sys
-
-from shibokensupport.signature import inspect
-from shibokensupport.signature import get_signature
-from shibokensupport.signature.mapping import update_mapping, namespace
-from textwrap import dedent
-
-
-def qt_isinstance(inst, the_type):
- if the_type == float:
- return isinstance(inst, int) or isinstance(int, float)
- try:
- return isinstance(inst, the_type)
- except TypeError as e:
- print("FIXME", e)
- return False
-
-
-def matched_type(args, sigs):
- for sig in sigs:
- params = list(sig.parameters.values())
- if len(args) > len(params):
- continue
- if len(args) < len(params):
- k = len(args)
- if params[k].default is params[k].empty:
- # this is a necessary parameter, so it fails.
- continue
- ok = True
- for arg, param in zip(args, params):
- ann = param.annotation
- if qt_isinstance(arg, ann):
- continue
- ok = False
- if ok:
- return sig
- return None
-
-
-def seterror_argument(args, func_name):
- update_mapping()
- func = eval(func_name, namespace)
- sigs = get_signature(func, "typeerror")
- if type(sigs) != list:
- sigs = [sigs]
- if type(args) != tuple:
- args = (args,)
- # temp!
- found = matched_type(args, sigs)
- if found:
- msg = dedent("""
- '{func_name}' called with wrong argument values:
- {func_name}{args}
- Found signature:
- {func_name}{found}
- """.format(**locals())).strip()
- return ValueError, msg
- type_str = ", ".join(type(arg).__name__ for arg in args)
- msg = dedent("""
- '{func_name}' called with wrong argument types:
- {func_name}({type_str})
- Supported signatures:
- """.format(**locals())).strip()
- for sig in sigs:
- msg += "\n {func_name}{sig}".format(**locals())
- # We don't raise the error here, to avoid the loader in the traceback.
- return TypeError, msg
-
-def check_string_type(s):
- if sys.version_info[0] == 3:
- return isinstance(s, str)
- else:
- return isinstance(s, (str, unicode))
-
-def make_helptext(func):
- existing_doc = func.__doc__
- sigs = get_signature(func)
- if not sigs:
- return existing_doc
- if type(sigs) != list:
- sigs = [sigs]
- try:
- func_name = func.__name__
- except AttribureError:
- func_name = func.__func__.__name__
- sigtext = "\n".join(func_name + str(sig) for sig in sigs)
- msg = sigtext + "\n\n" + existing_doc if check_string_type(existing_doc) else sigtext
- return msg
-
-# end of file
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/importhandler.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/importhandler.py
deleted file mode 100644
index 7af43bea0..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/importhandler.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-"""
-importhandler.py
-
-This module handles special actions after the import of PySide modules.
-The reason for this was the wish to replace some deprecated functions
-by a Python implementation that gives a warning.
-
-It provides a framework to safely call functions outside of files.dir,
-because the implementation of deprecated functions should be visible
-to the users (in the hope they don't use it any longer <wink>).
-
-As a first approach, the function finish_import redirects to
-PySide2/support/deprecated.py . There can come other extensions as well.
-"""
-
-try:
- from PySide2.support import deprecated
- have_deprecated = True
-except ImportError:
- have_deprecated = False
-
-
-# called by loader.py from signature.cpp
-def finish_import(module):
- if have_deprecated and module.__name__.startswith("PySide2."):
- try:
- name = "fix_for_" + module.__name__.split(".")[1]
- func = getattr(deprecated, name, None)
- if func:
- func(module)
- except Exception as e:
- name = e.__class__.__qualname__
- print(72 * "*")
- print("Error in deprecated.py, ignored:")
- print(" {name}: {e}".format(**locals()))
-
-"""
-A note for people who might think this could be written in pure Python:
-
-Sure, by an explicit import of the modules to patch, this is no problem.
-But in the general case, a module should only be imported on user
-request and not because we want to patch it. So I started over.
-
-I then tried to do it on demand by redirection of the __import__ function.
-Things worked quite nicely as it seemed, but at second view this solution
-was much less appealing.
-
-Reason:
-If someone executes as the first PySide statement
-
- from PySide2 import QtGui
-
-then this import is already running. We can see the other imports like the
-diverse initializations and QtCore, because it is triggered by import of
-QtGui. But the QtGui import can not be seen at all!
-
-With a lot of effort, sys.setprofile() and stack inspection with the inspect
-module, it is *perhaps* possible to solve that. I tried for a day and then
-gave up, since the solution is anyway not too nice when __import__ must
-be overridden.
-"""
-#eof
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/layout.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/layout.py
deleted file mode 100644
index 384273d92..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/layout.py
+++ /dev/null
@@ -1,282 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-"""
-layout.py
-
-The signature module now has the capability to configure
-differently formatted versions of signatures. The default
-layout is known from the "__signature__" attribute.
-
-The function "get_signature(ob, modifier=None)" produces the same
-signatures by default. By passing different modifiers, you
-can select different layouts.
-
-This module configures the different layouts which can be used.
-It also implements them in this file. The configurations are
-used literally as strings like "signature", "existence", etc.
-"""
-
-from textwrap import dedent
-from shibokensupport.signature import inspect, typing
-from shibokensupport.signature.mapping import ellipsis
-from shibokensupport.signature.lib.tool import SimpleNamespace
-
-
-class SignatureLayout(SimpleNamespace):
- """
- Configure a signature.
-
- The layout of signatures can have different layouts which are
- controlled by keyword arguments:
-
- definition=True Determines if self will generated.
- defaults=True
- ellipsis=False Replaces defaults by "...".
- return_annotation=True
- parameter_names=True False removes names before ":".
- """
- allowed_keys = SimpleNamespace(definition=True,
- defaults=True,
- ellipsis=False,
- return_annotation=True,
- parameter_names=True)
- allowed_values = True, False
-
- def __init__(self, **kwds):
- args = SimpleNamespace(**self.allowed_keys.__dict__)
- args.__dict__.update(kwds)
- self.__dict__.update(args.__dict__)
- err_keys = list(set(self.__dict__) - set(self.allowed_keys.__dict__))
- if err_keys:
- self._attributeerror(err_keys)
- err_values = list(set(self.__dict__.values()) - set(self.allowed_values))
- if err_values:
- self._valueerror(err_values)
-
- def __setattr__(self, key, value):
- if key not in self.allowed_keys.__dict__:
- self._attributeerror([key])
- if value not in self.allowed_values:
- self._valueerror([value])
- self.__dict__[key] = value
-
- def _attributeerror(self, err_keys):
- err_keys = ", ".join(err_keys)
- allowed_keys = ", ".join(self.allowed_keys.__dict__.keys())
- raise AttributeError(dedent("""\
- Not allowed: '{err_keys}'.
- The only allowed keywords are '{allowed_keys}'.
- """.format(**locals())))
-
- def _valueerror(self, err_values):
- err_values = ", ".join(map(str, err_values))
- allowed_values = ", ".join(map(str, self.allowed_values))
- raise ValueError(dedent("""\
- Not allowed: '{err_values}'.
- The only allowed values are '{allowed_values}'.
- """.format(**locals())))
-
-# The following names are used literally in this module.
-# This way, we avoid the dict hashing problem.
-signature = SignatureLayout()
-
-existence = SignatureLayout(definition=False,
- defaults=False,
- return_annotation=False,
- parameter_names=False)
-
-hintingstub = SignatureLayout(ellipsis=True)
-
-typeerror = SignatureLayout(definition=False,
- return_annotation=False,
- parameter_names=False)
-
-
-def define_nameless_parameter():
- """
- Create Nameless Parameters
-
- A nameless parameter has a reduced string representation.
- This is done by cloning the parameter type and overwriting its
- __str__ method. The inner structure is still a valid parameter.
- """
- def __str__(self):
- # for Python 2, we must change self to be an instance of P
- klass = self.__class__
- self.__class__ = P
- txt = P.__str__(self)
- self.__class__ = klass
- txt = txt[txt.index(":") + 1:].strip() if ":" in txt else txt
- return txt
-
- P = inspect.Parameter
- newname = "NamelessParameter"
- bases = P.__bases__
- body = dict(P.__dict__) # get rid of mappingproxy
- if "__slots__" in body:
- # __slots__ would create duplicates
- for name in body["__slots__"]:
- del body[name]
- body["__str__"] = __str__
- return type(newname, bases, body)
-
-
-NamelessParameter = define_nameless_parameter()
-
-"""
-Note on the "Optional" feature:
-
-When an annotation has a default value that is None, then the
-type has to be wrapped into "typing.Optional".
-
-Note that only the None value creates an Optional expression,
-because the None leaves the domain of the variable.
-Defaults like integer values are ignored: They stay in the domain.
-
-That information would be lost when we use the "..." convention.
-
-Note that the typing module has the remarkable expansion
-
- Optional[T] is Variant[T, NoneType]
-
-We want to avoid that when generating the .pyi file.
-This is done by a regex in generate_pyi.py .
-The following would work in Python 3, but this is a version-dependent
-hack that also won't work in Python 2 and would be _very_ complex.
-"""
-# import sys
-# if sys.version_info[0] == 3:
-# class hugo(list):pass
-# typing._normalize_alias["hugo"] = "Optional"
-# Optional = typing._alias(hugo, typing.T, inst=False)
-# else:
-# Optional = typing.Optional
-
-
-def make_signature_nameless(signature):
- """
- Make a Signature Nameless
-
- We use an existing signature and change the type of its parameters.
- The signature looks different, but is totally intact.
- """
- for key in signature.parameters.keys():
- signature.parameters[key].__class__ = NamelessParameter
-
-
-_POSITIONAL_ONLY = inspect._POSITIONAL_ONLY
-_POSITIONAL_OR_KEYWORD = inspect._POSITIONAL_OR_KEYWORD
-_VAR_POSITIONAL = inspect._VAR_POSITIONAL
-_KEYWORD_ONLY = inspect._KEYWORD_ONLY
-_VAR_KEYWORD = inspect._VAR_KEYWORD
-_empty = inspect._empty
-
-def create_signature(props, key):
- if not props:
- # empty signatures string
- return
- if isinstance(props["multi"], list):
- # multi sig: call recursively
- return list(create_signature(elem, key)
- for elem in props["multi"])
- if type(key) is tuple:
- sig_kind, modifier = key
- else:
- sig_kind, modifier = key, "signature"
-
- layout = globals()[modifier] # lookup of the modifier in this module
- if not isinstance(layout, SignatureLayout):
- raise SystemError("Modifiers must be names of a SignatureLayout "
- "instance")
-
- # this is the basic layout of a signature
- varnames = props["varnames"]
- if layout.definition:
- if sig_kind == "function":
- pass
- elif sig_kind == "method":
- varnames = ("self",) + varnames
- elif sig_kind == "staticmethod":
- pass
- elif sig_kind == "classmethod":
- varnames = ("klass",) + varnames
- else:
- raise SystemError("Methods must be function, method, staticmethod"
- " or classmethod")
- # calculate the modifications
- defaults = props["defaults"][:]
- if not layout.defaults:
- defaults = ()
- annotations = props["annotations"].copy()
- if not layout.return_annotation and "return" in annotations:
- del annotations["return"]
-
- # Build a signature.
- kind = inspect._POSITIONAL_OR_KEYWORD
- params = []
- for idx, name in enumerate(varnames):
- if name.startswith("**"):
- kind = _VAR_KEYWORD
- elif name.startswith("*"):
- kind = _VAR_POSITIONAL
- ann = annotations.get(name, _empty)
- name = name.lstrip("*")
- defpos = idx - len(varnames) + len(defaults)
- default = defaults[defpos] if defpos >= 0 else _empty
- if default is None:
- ann = typing.Optional[ann]
- if default is not _empty and layout.ellipsis:
- default = ellipsis
- param = inspect.Parameter(name, kind, annotation=ann, default=default)
- params.append(param)
- if kind == _VAR_POSITIONAL:
- kind = _KEYWORD_ONLY
- sig = inspect.Signature(params,
- return_annotation=annotations.get('return', _empty),
- __validate_parameters__=False)
-
- # the special case of nameless parameters
- if not layout.parameter_names:
- make_signature_nameless(sig)
- return sig
-
-# end of file
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/__init__.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/__init__.py
deleted file mode 100644
index 2d640cb89..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/__init__.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2018 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-# this file intentionally left blank
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/enum_sig.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/enum_sig.py
deleted file mode 100644
index fa4d5e77c..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/enum_sig.py
+++ /dev/null
@@ -1,219 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2020 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-"""
-enum_sig.py
-
-Enumerate all signatures of a class.
-
-This module separates the enumeration process from the formatting.
-It is not easy to adhere to this protocol, but in the end, it paid off
-by producing a lot of clarity.
-"""
-
-import sys
-from shibokensupport.signature import inspect
-from shibokensupport.signature import get_signature
-
-
-class ExactEnumerator(object):
- """
- ExactEnumerator enumerates all signatures in a module as they are.
-
- This class is used for generating complete listings of all signatures.
- An appropriate formatter should be supplied, if printable output
- is desired.
- """
-
- def __init__(self, formatter, result_type=dict):
- global EnumType
- try:
- # Lazy import
- from PySide2.QtCore import Qt
- EnumType = type(Qt.Key)
- except ImportError:
- EnumType = None
-
- self.fmt = formatter
- self.result_type = result_type
- self.fmt.level = 0
- self.fmt.after_enum = self.after_enum
- self._after_enum = False
-
- def after_enum(self):
- ret = self._after_enum
- self._after_enum = False
-
- def module(self, mod_name):
- __import__(mod_name)
- self.fmt.mod_name = mod_name
- with self.fmt.module(mod_name):
- module = sys.modules[mod_name]
- members = inspect.getmembers(module, inspect.isclass)
- functions = inspect.getmembers(module, inspect.isroutine)
- ret = self.result_type()
- self.fmt.class_name = None
- for class_name, klass in members:
- ret.update(self.klass(class_name, klass))
- if isinstance(klass, EnumType):
- raise SystemError("implement enum instances at module level")
- for func_name, func in functions:
- ret.update(self.function(func_name, func))
- return ret
-
- def klass(self, class_name, klass):
- ret = self.result_type()
- if "<" in class_name:
- # This is happening in QtQuick for some reason:
- ## class QSharedPointer<QQuickItemGrabResult >:
- # We simply skip over this class.
- return ret
- bases_list = []
- for base in klass.__bases__:
- name = base.__name__
- if name not in ("object", "type"):
- name = base.__module__ + "." + name
- bases_list.append(name)
- class_str = "{}({})".format(class_name, ", ".join(bases_list))
- # class_members = inspect.getmembers(klass)
- # gives us also the inherited things.
- class_members = sorted(list(klass.__dict__.items()))
- subclasses = []
- functions = []
- enums = []
-
- for thing_name, thing in class_members:
- if inspect.isclass(thing):
- subclass_name = ".".join((class_name, thing_name))
- subclasses.append((subclass_name, thing))
- elif inspect.isroutine(thing):
- func_name = thing_name.split(".")[0] # remove ".overload"
- signature = getattr(thing, "__signature__", None)
- if signature is not None:
- functions.append((func_name, thing))
- elif type(type(thing)) is EnumType:
- enums.append((thing_name, thing))
- init_signature = getattr(klass, "__signature__", None)
- enums.sort(key=lambda tup: tup[1]) # sort by enum value
- self.fmt.have_body = bool(subclasses or functions or enums or init_signature)
-
- with self.fmt.klass(class_name, class_str):
- self.fmt.level += 1
- self.fmt.class_name = class_name
- if hasattr(self.fmt, "enum"):
- # this is an optional feature
- for enum_name, value in enums:
- with self.fmt.enum(class_name, enum_name, int(value)):
- pass
- for subclass_name, subclass in subclasses:
- if klass == subclass:
- # this is a side effect of the typing module for Python 2.7
- # via the "._gorg" property, which we can safely ignore.
- print("Warning: {class_name} points to itself via {subclass_name}, skipped!"
- .format(**locals()))
- continue
- ret.update(self.klass(subclass_name, subclass))
- self.fmt.class_name = class_name
- ret.update(self.function("__init__", klass))
- for func_name, func in functions:
- func_kind = get_signature(func, "__func_kind__")
- modifier = func_kind if func_kind in (
- "staticmethod", "classmethod") else None
- ret.update(self.function(func_name, func, modifier))
- self.fmt.level -= 1
- return ret
-
- def function(self, func_name, func, modifier=None):
- self.fmt.level += 1
- ret = self.result_type()
- signature = func.__signature__
- if signature is not None:
- with self.fmt.function(func_name, signature, modifier) as key:
- ret[key] = signature
- self.fmt.level -= 1
- return ret
-
-
-def stringify(signature):
- if isinstance(signature, list):
- # remove duplicates which still sometimes occour:
- ret = set(stringify(sig) for sig in signature)
- return sorted(ret) if len(ret) > 1 else list(ret)[0]
- return tuple(str(pv) for pv in signature.parameters.values())
-
-
-class SimplifyingEnumerator(ExactEnumerator):
- """
- SimplifyingEnumerator enumerates all signatures in a module filtered.
-
- There are no default values, no variable
- names and no self parameter. Only types are present after simplification.
- The functions 'next' resp. '__next__' are removed
- to make the output identical for Python 2 and 3.
- An appropriate formatter should be supplied, if printable output
- is desired.
- """
-
- def function(self, func_name, func, modifier=None):
- ret = self.result_type()
- signature = get_signature(func, 'existence')
- sig = stringify(signature) if signature is not None else None
- if sig is not None and func_name not in ("next", "__next__", "__div__"):
- with self.fmt.function(func_name, sig) as key:
- ret[key] = sig
- return ret
-
-class HintingEnumerator(ExactEnumerator):
- """
- HintingEnumerator enumerates all signatures in a module slightly changed.
-
- This class is used for generating complete listings of all signatures for
- hinting stubs. Only default values are replaced by "...".
- """
-
- def function(self, func_name, func, modifier=None):
- ret = self.result_type()
- signature = get_signature(func, 'hintingstub')
- if signature is not None:
- with self.fmt.function(func_name, signature, modifier) as key:
- ret[key] = signature
- return ret
-
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py
deleted file mode 100644
index 24e75e42c..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/lib/tool.py
+++ /dev/null
@@ -1,154 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-"""
-tool.py
-
-Some useful stuff, see below.
-On the function with_metaclass see the answer from Martijn Pieters on
-https://stackoverflow.com/questions/18513821/python-metaclass-understanding-the-with-metaclass
-"""
-
-from textwrap import dedent
-
-
-class SimpleNamespace(object):
- # From types.rst, because the builtin is implemented in Python 3, only.
- def __init__(self, **kwargs):
- self.__dict__.update(kwargs)
-
- def __repr__(self):
- keys = sorted(self.__dict__)
- items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
- return "{}({})".format(type(self).__name__, ", ".join(items))
-
- def __eq__(self, other):
- return self.__dict__ == other.__dict__
-
-try:
- from types import SimpleNamespace
-except ImportError:
- pass
-
-
-def build_brace_pattern(level, separators=""):
- """
- Build a brace pattern upto a given depth
-
- The brace pattern parses any pattern with round, square, curly, or angle
- brackets. Inside those brackets, any characters are allowed.
-
- The structure is quite simple and is recursively repeated as needed.
- When separators are given, the match stops at that separator.
-
- Reason to use this instead of some Python function:
- The resulting regex is _very_ fast!
-
- A faster replacement would be written in C, but this solution is
- sufficient when the nesting level is not too large.
-
- Because of the recursive nature of the pattern, the size grows by a factor
- of 4 at every level, as does the creation time. Up to a level of 6, this
- is below 10 ms.
-
- There are other regex engines available which allow recursive patterns,
- avoiding this problem completely. It might be considered to switch to
- such an engine if the external module is not a problem.
- """
- def escape(str):
- return "".join("\\" + c for c in str)
-
- ro, rc = round = "()"
- so, sc = square = "[]"
- co, cc = curly = "CD" # we insert "{}", later...
- ao, ac = angle = "<>"
- qu, bs = '"', "\\"
- all = round + square + curly + angle
- __ = " "
- ro, rc, so, sc, co, cc, ao, ac, separators, qu, bs, all = map(
- escape, (ro, rc, so, sc, co, cc, ao, ac, separators, qu, bs, all))
-
- no_brace_sep_q = r"[^{all}{separators}{qu}{bs}]".format(**locals())
- no_quote = r"(?: [^{qu}{bs}] | {bs}. )*".format(**locals())
- pattern = dedent(r"""
- (
- (?: {__} {no_brace_sep_q}
- | {qu} {no_quote} {qu}
- | {ro} {replacer} {rc}
- | {so} {replacer} {sc}
- | {co} {replacer} {cc}
- | {ao} {replacer} {ac}
- )+
- )
- """)
- no_braces_q = "[^{all}{qu}{bs}]*".format(**locals())
- repeated = dedent(r"""
- {indent} (?: {__} {no_braces_q}
- {indent} | {qu} {no_quote} {qu}
- {indent} | {ro} {replacer} {rc}
- {indent} | {so} {replacer} {sc}
- {indent} | {co} {replacer} {cc}
- {indent} | {ao} {replacer} {ac}
- {indent} )*
- """)
- for idx in range(level):
- pattern = pattern.format(replacer = repeated if idx < level-1 else no_braces_q,
- indent = idx * " ", **locals())
- return pattern.replace("C", "{").replace("D", "}")
-
-
-# Copied from the six module:
-def with_metaclass(meta, *bases):
- """Create a base class with a metaclass."""
- # This requires a bit of explanation: the basic idea is to make a dummy
- # metaclass for one level of class instantiation that replaces itself with
- # the actual metaclass.
- class metaclass(type):
-
- def __new__(cls, name, this_bases, d):
- return meta(name, bases, d)
-
- @classmethod
- def __prepare__(cls, name, this_bases):
- return meta.__prepare__(name, bases)
- return type.__new__(metaclass, 'temporary_class', (), {})
-
-# eof
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/loader.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/loader.py
deleted file mode 100644
index 1efc6fde5..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/loader.py
+++ /dev/null
@@ -1,221 +0,0 @@
-# This Python file uses the following encoding: utf-8
-# It has been edited by fix-complaints.py .
-
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-"""
-loader.py
-
-The loader has to load the signature module completely at startup,
-to make sure that the functions are available when needed.
-This is meanwhile necessary to make the '__doc__' attribute work correctly.
-
-It does not mean that everything is initialized in advance. Only the modules
-are loaded completely after 'import PySide2'.
-
-This version uses both a normal directory, but has also an embedded ZIP file
-as a fallback solution. The ZIP file is generated by 'embedding_generator.py'
-and embedded into 'signature.cpp' as "embed/signature.inc".
-
-Meanwhile, the ZIP file grew so much, that MSVC had problems
-with it's 64k string limit, so we had to break the string up.
-See 'zipped_string_sequence' in signature.cpp.
-"""
-
-import sys
-import os
-import traceback
-import types
-
-# On Python 2, we only have ImportError, which is way too coarse.
-# When problems occour, please use Python 3, because it has the finer
-# ModuleNotFoundError.
-
-try:
- ModuleNotFoundError
-except NameError:
- ModuleNotFoundError = ImportError
-
-def _qualname(x):
- return getattr(x, "__qualname__", x.__name__)
-
-# patching inspect's formatting to keep the word "typing":
-def formatannotation(annotation, base_module=None):
- # if getattr(annotation, '__module__', None) == 'typing':
- # return repr(annotation).replace('typing.', '')
- if isinstance(annotation, type):
- name = _qualname(annotation)
- if annotation.__module__ in ('builtins', base_module):
- return name
- return annotation.__module__ + '.' + name
- return repr(annotation)
-
-# Note also that during the tests we have a different encoding that would
-# break the Python license decorated files without an encoding line.
-
-# name used in signature.cpp
-def pyside_type_init(type_key, sig_strings):
- return parser.pyside_type_init(type_key, sig_strings)
-
-# name used in signature.cpp
-def create_signature(props, key):
- return layout.create_signature(props, key)
-
-# name used in signature.cpp
-def seterror_argument(args, func_name):
- return errorhandler.seterror_argument(args, func_name)
-
-# name used in signature.cpp
-def make_helptext(func):
- return errorhandler.make_helptext(func)
-
-# name used in signature.cpp
-def finish_import(module):
- return importhandler.finish_import(module)
-
-
-import signature_bootstrap
-from shibokensupport import signature
-signature.get_signature = signature_bootstrap.get_signature
-del signature_bootstrap
-
-def _get_modname(mod):
- return mod.__spec__.name if getattr(mod, "__spec__", None) else mod.__name__
-
-def _set_modname(mod, name):
- if getattr(mod, "__spec__", None):
- mod.__spec__.name = name
- else:
- mod.__name__ = name
-
-
-def put_into_package(package, module, override=None):
- # take the last component of the module name
- name = (override if override else _get_modname(module)).rsplit(".", 1)[-1]
- # allow access as {package}.typing
- if package:
- setattr(package, name, module)
- # put into sys.modules as a package to allow all import options
- fullname = "{}.{}".format(_get_modname(package), name) if package else name
- _set_modname(module, fullname)
- # publish new dotted name in sys.modules
- sys.modules[fullname] = module
-
-
-# Debug: used to inspect what each step loads
-def list_modules(message):
- ext_modules = {key:value for (key, value) in sys.modules.items()
- if hasattr(value, "__file__")}
- print("SYS.MODULES", message, len(sys.modules), len(ext_modules))
- for (name, module) in sorted(ext_modules.items()):
- print(" {:23}".format(name), repr(module)[:70])
-
-
-orig_typing = True
-if sys.version_info >= (3,):
- import typing
- import inspect
- inspect.formatannotation = formatannotation
-else:
- tp_name = "typing"
- if tp_name not in sys.modules:
- orig_typing = False
- from shibokensupport import typing27 as typing
- sys.modules[tp_name] = typing
- typing.__name__ = tp_name
- else:
- import typing
- import inspect
- namespace = inspect.__dict__
- from shibokensupport import backport_inspect as inspect
- _doc = inspect.__doc__
- inspect.__dict__.update(namespace)
- inspect.__doc__ += _doc
- # force inspect to find all attributes. See "heuristic" in pydoc.py!
- inspect.__all__ = list(x for x in dir(inspect) if not x.startswith("_"))
-
-# Fix the module names in typing if possible. This is important since
-# the typing names should be I/O compatible, so that typing.Dict
-# shows itself as "typing.Dict".
-for name, obj in typing.__dict__.items():
- if hasattr(obj, "__module__"):
- try:
- obj.__module__ = "typing"
- except (TypeError, AttributeError):
- pass
-
-import shibokensupport
-put_into_package(shibokensupport.signature, typing, "typing")
-put_into_package(shibokensupport.signature, inspect, "inspect")
-
-
-def move_into_pyside_package():
- import PySide2
- try:
- import PySide2.support
- except ModuleNotFoundError:
- PySide2.support = types.ModuleType("PySide2.support")
- put_into_package(PySide2.support, signature)
- put_into_package(PySide2.support.signature, mapping)
- put_into_package(PySide2.support.signature, errorhandler)
- put_into_package(PySide2.support.signature, layout)
- put_into_package(PySide2.support.signature, lib)
- put_into_package(PySide2.support.signature, parser)
- put_into_package(PySide2.support.signature, importhandler)
- put_into_package(PySide2.support.signature.lib, enum_sig)
-
- put_into_package(None if orig_typing else PySide2.support.signature, typing)
- put_into_package(PySide2.support.signature, inspect)
-
-from shibokensupport.signature import mapping
-from shibokensupport.signature import errorhandler
-from shibokensupport.signature import layout
-from shibokensupport.signature import lib
-from shibokensupport.signature import parser
-from shibokensupport.signature import importhandler
-from shibokensupport.signature.lib import enum_sig
-
-if "PySide2" in sys.modules:
- # We publish everything under "PySide2.support.signature", again.
- move_into_pyside_package()
-
-# end of file
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/mapping.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/mapping.py
deleted file mode 100644
index 0571b11bd..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/mapping.py
+++ /dev/null
@@ -1,645 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-"""
-mapping.py
-
-This module has the mapping from the pyside C-modules view of signatures
-to the Python representation.
-
-The PySide modules are not loaded in advance, but only after they appear
-in sys.modules. This minimizes the loading overhead.
-"""
-
-import sys
-import struct
-import os
-
-from shibokensupport.signature import typing
-from shibokensupport.signature.typing import TypeVar, Generic
-from shibokensupport.signature.lib.tool import with_metaclass
-
-class ellipsis(object):
- def __repr__(self):
- return "..."
-
-ellipsis = ellipsis()
-Point = typing.Tuple[float, float]
-Variant = typing.Any
-ModelIndexList = typing.List[int]
-QImageCleanupFunction = typing.Callable
-
-# unfortunately, typing.Optional[t] expands to typing.Union[t, NoneType]
-# Until we can force it to create Optional[t] again, we use this.
-NoneType = type(None)
-
-_S = TypeVar("_S")
-
-MultiMap = typing.DefaultDict[str, typing.List[str]]
-
-# ulong_max is only 32 bit on windows.
-ulong_max = 2*sys.maxsize+1 if len(struct.pack("L", 1)) != 4 else 0xffffffff
-ushort_max = 0xffff
-
-GL_COLOR_BUFFER_BIT = 0x00004000
-GL_NEAREST = 0x2600
-
-WId = int
-
-# from 5.9
-GL_TEXTURE_2D = 0x0DE1
-GL_RGBA = 0x1908
-
-
-class _NotCalled(str):
- """
- Wrap some text with semantics
-
- This class is wrapped around text in order to avoid calling it.
- There are three reasons for this:
-
- - some instances cannot be created since they are abstract,
- - some can only be created after qApp was created,
- - some have an ugly __repr__ with angle brackets in it.
-
- By using derived classes, good looking instances can be created
- which can be used to generate source code or .pyi files. When the
- real object is needed, the wrapper can simply be called.
- """
- def __repr__(self):
- return "{}({})".format(type(self).__name__, self)
-
- def __call__(self):
- from shibokensupport.signature.mapping import __dict__ as namespace
- text = self if self.endswith(")") else self + "()"
- return eval(text, namespace)
-
-USE_PEP563 = False
-# Note: we cannot know if this feature has been imported.
-# Otherwise it would be "sys.version_info[:2] >= (3, 7)".
-# We *can* eventually inspect sys.modules and look if
-# the calling module has this future statement set,
-# but should we do that?
-
-
-# Some types are abstract. They just show their name.
-class Virtual(_NotCalled):
- pass
-
-# Other types I simply could not find.
-class Missing(_NotCalled):
- # The string must be quoted, because the object does not exist.
- def __repr__(self):
- if USE_PEP563:
- return _NotCalled.__repr__(self)
- return '{}("{}")'.format(type(self).__name__, self)
-
-
-class Invalid(_NotCalled):
- pass
-
-# Helper types
-class Default(_NotCalled):
- pass
-
-
-class Instance(_NotCalled):
- pass
-
-# Parameterized primitive variables
-class _Parameterized(object):
- def __init__(self, type):
- self.type = type
- self.__name__ = self.__class__.__name__
-
- def __repr__(self):
- return "{}({})".format(
- type(self).__name__, self.type.__name__)
-
-# Mark the primitive variables to be moved into the result.
-class ResultVariable(_Parameterized):
- pass
-
-# Mark the primitive variables to become Sequence, Iterable or List
-# (decided in the parser).
-class ArrayLikeVariable(_Parameterized):
- pass
-
-StringList = ArrayLikeVariable(str)
-
-
-class Reloader(object):
- """
- Reloder class
-
- This is a singleton class which provides the update function for the
- shiboken and PySide classes.
- """
- def __init__(self):
- self.sys_module_count = 0
-
- @staticmethod
- def module_valid(mod):
- if getattr(mod, "__file__", None) and not os.path.isdir(mod.__file__):
- ending = os.path.splitext(mod.__file__)[-1]
- return ending not in (".py", ".pyc", ".pyo", ".pyi")
- return False
-
- def update(self):
- """
- 'update' imports all binary modules which are already in sys.modules.
- The reason is to follow all user imports without introducing new ones.
- This function is called by pyside_type_init to adapt imports
- when the number of imported modules has changed.
- """
- if self.sys_module_count == len(sys.modules):
- return
- self.sys_module_count = len(sys.modules)
- g = globals()
- # PYSIDE-1009: Try to recognize unknown modules in errorhandler.py
- candidates = list(mod_name for mod_name in sys.modules.copy()
- if self.module_valid(sys.modules[mod_name]))
- for mod_name in candidates:
- # 'top' is PySide2 when we do 'import PySide.QtCore'
- # or Shiboken if we do 'import Shiboken'.
- # Convince yourself that these two lines below have the same
- # global effect as "import Shiboken" or "import PySide2.QtCore".
- top = __import__(mod_name)
- g[top.__name__] = top
- proc_name = "init_" + mod_name.replace(".", "_")
- if proc_name in g:
- # Modules are in place, we can update the type_map.
- g.update(g.pop(proc_name)())
-
-
-def check_module(mod):
- # During a build, there exist the modules already as directories,
- # although the '*.so' was not yet created. This causes a problem
- # in Python 3, because it accepts folders as namespace modules
- # without enforcing an '__init__.py'.
- if not Reloader.module_valid(mod):
- mod_name = mod.__name__
- raise ImportError("Module '{mod_name}' is not a binary module!"
- .format(**locals()))
-
-update_mapping = Reloader().update
-type_map = {}
-namespace = globals() # our module's __dict__
-
-type_map.update({
- "...": ellipsis,
- "bool": bool,
- "char": int,
- "char*": str,
- "char*const": str,
- "double": float,
- "float": float,
- "int": int,
- "List": ArrayLikeVariable,
- "long": int,
- "PyCallable": typing.Callable,
- "PyObject": object,
- "PySequence": typing.Iterable, # important for numpy
- "PyTypeObject": type,
- "QChar": str,
- "QHash": typing.Dict,
- "qint16": int,
- "qint32": int,
- "qint64": int,
- "qint8": int,
- "qintptr": int,
- "QList": ArrayLikeVariable,
- "qlonglong": int,
- "QMap": typing.Dict,
- "QPair": typing.Tuple,
- "qptrdiff": int,
- "qreal": float,
- "QSet": typing.Set,
- "QString": str,
- "QStringList": StringList,
- "quint16": int,
- "quint32": int,
- "quint32": int,
- "quint64": int,
- "quint8": int,
- "quintptr": int,
- "qulonglong": int,
- "QVariant": Variant,
- "QVector": typing.List,
- "real": float,
- "short": int,
- "signed char": int,
- "signed long": int,
- "std.list": typing.List,
- "std.map": typing.Dict,
- "std.pair": typing.Tuple,
- "std.vector": typing.List,
- "str": str,
- "true": True,
- "Tuple": typing.Tuple,
- "uchar": int,
- "uchar*": str,
- "uint": int,
- "ulong": int,
- "ULONG_MAX": ulong_max,
- "unsigned char": int, # 5.9
- "unsigned char*": str,
- "unsigned int": int,
- "unsigned long int": int, # 5.6, RHEL 6.6
- "unsigned long long": int,
- "unsigned long": int,
- "unsigned short int": int, # 5.6, RHEL 6.6
- "unsigned short": int,
- "Unspecified": None,
- "ushort": int,
- "void": int, # be more specific?
- "WId": WId,
- "zero(bytes)": b"",
- "zero(Char)": 0,
- "zero(float)": 0,
- "zero(int)": 0,
- "zero(object)": None,
- "zero(str)": "",
- "zero(typing.Any)": None,
- })
-
-type_map.update({
- # Handling variables declared as array:
- "array double*" : ArrayLikeVariable(float),
- "array float*" : ArrayLikeVariable(float),
- "array GLint*" : ArrayLikeVariable(int),
- "array GLuint*" : ArrayLikeVariable(int),
- "array int*" : ArrayLikeVariable(int),
- "array long long*" : ArrayLikeVariable(int),
- "array long*" : ArrayLikeVariable(int),
- "array short*" : ArrayLikeVariable(int),
- "array signed char*" : bytes,
- "array unsigned char*" : bytes,
- "array unsigned int*" : ArrayLikeVariable(int),
- "array unsigned short*" : ArrayLikeVariable(int),
- })
-
-type_map.update({
- # Special cases:
- "char*" : bytes,
- "QChar*" : bytes,
- "quint32*" : int, # only for QRandomGenerator
- "quint8*" : bytearray, # only for QCborStreamReader and QCborValue
- "uchar*" : bytes,
- "unsigned char*": bytes,
- })
-
-type_map.update({
- # Handling variables that are returned, eventually as Tuples:
- "bool*" : ResultVariable(bool),
- "float*" : ResultVariable(float),
- "int*" : ResultVariable(int),
- "long long*" : ResultVariable(int),
- "long*" : ResultVariable(int),
- "PStr*" : ResultVariable(str), # module sample
- "qint32*" : ResultVariable(int),
- "qint64*" : ResultVariable(int),
- "qreal*" : ResultVariable(float),
- "QString*" : ResultVariable(str),
- "quint16*" : ResultVariable(int),
- "uint*" : ResultVariable(int),
- "unsigned int*" : ResultVariable(int),
- "QStringList*" : ResultVariable(StringList),
- })
-
-
-# The Shiboken Part
-def init_Shiboken():
- type_map.update({
- "PyType": type,
- "shiboken2.bool": bool,
- "size_t": int,
- })
- return locals()
-
-
-def init_minimal():
- type_map.update({
- "MinBool": bool,
- })
- return locals()
-
-
-def init_sample():
- import datetime
- type_map.update({
- "char": int,
- "char**": typing.List[str],
- "Complex": complex,
- "double": float,
- "Foo.HANDLE": int,
- "HANDLE": int,
- "Null": None,
- "nullptr": None,
- "ObjectType.Identifier": Missing("sample.ObjectType.Identifier"),
- "OddBool": bool,
- "PStr": str,
- "PyDate": datetime.date,
- "sample.bool": bool,
- "sample.char": int,
- "sample.double": float,
- "sample.int": int,
- "sample.ObjectType": object,
- "sample.OddBool": bool,
- "sample.Photon.TemplateBase[Photon.DuplicatorType]": sample.Photon.ValueDuplicator,
- "sample.Photon.TemplateBase[Photon.IdentityType]": sample.Photon.ValueIdentity,
- "sample.Point": Point,
- "sample.PStr": str,
- "sample.unsigned char": int,
- "std.size_t": int,
- "std.string": str,
- "ZeroIn": 0,
- 'Str("<unk")': "<unk",
- 'Str("<unknown>")': "<unknown>",
- 'Str("nown>")': "nown>",
- })
- return locals()
-
-
-def init_other():
- import numbers
- type_map.update({
- "other.ExtendsNoImplicitConversion": Missing("other.ExtendsNoImplicitConversion"),
- "other.Number": numbers.Number,
- })
- return locals()
-
-
-def init_smart():
- # This missing type should be defined in module smart. We cannot set it to Missing()
- # because it is a container type. Therefore, we supply a surrogate:
- global SharedPtr
- class SharedPtr(Generic[_S]):
- __module__ = "smart"
- smart.SharedPtr = SharedPtr
- type_map.update({
- "smart.Smart.Integer2": int,
- })
- return locals()
-
-
-# The PySide Part
-def init_PySide2_QtCore():
- from PySide2.QtCore import Qt, QUrl, QDir
- from PySide2.QtCore import QRect, QSize, QPoint, QLocale, QByteArray
- from PySide2.QtCore import QMarginsF # 5.9
- try:
- # seems to be not generated by 5.9 ATM.
- from PySide2.QtCore import Connection
- except ImportError:
- pass
- type_map.update({
- "' '": " ",
- "'%'": "%",
- "'g'": "g",
- "4294967295UL": 4294967295, # 5.6, RHEL 6.6
- "CheckIndexOption.NoOption": Instance(
- "PySide2.QtCore.QAbstractItemModel.CheckIndexOptions.NoOption"), # 5.11
- "false": False,
- "list of QAbstractAnimation": typing.List[PySide2.QtCore.QAbstractAnimation],
- "list of QAbstractState": typing.List[PySide2.QtCore.QAbstractState],
- "long long": int,
- "NULL": None, # 5.6, MSVC
- "nullptr": None, # 5.9
- "PyByteArray": bytearray,
- "PyBytes": bytes,
- "PySide2.QtCore.QCborStreamReader.StringResult[PySide2.QtCore.QByteArray]":
- PySide2.QtCore.QCborStringResultByteArray,
- "PySide2.QtCore.QCborStreamReader.StringResult[QString]":
- PySide2.QtCore.QCborStringResultString,
- "PySide2.QtCore.QCborStreamReader.QCborStringResultByteArray":
- PySide2.QtCore.QCborStringResultByteArray, # 5.14, why?
- "PySide2.QtCore.QCborStreamReader.QCborStringResultString":
- PySide2.QtCore.QCborStringResultString, # 5.14, why?
- "PySide2.QtCore.QUrl.ComponentFormattingOptions":
- PySide2.QtCore.QUrl.ComponentFormattingOption, # mismatch option/enum, why???
- "PyUnicode": typing.Text,
- "Q_NULLPTR": None,
- "QDir.Filters(AllEntries | NoDotAndDotDot)": Instance(
- "QDir.Filters(QDir.AllEntries | QDir.NoDotAndDotDot)"),
- "QDir.SortFlags(Name | IgnoreCase)": Instance(
- "QDir.SortFlags(QDir.Name | QDir.IgnoreCase)"),
- "QGenericArgument((0))": ellipsis, # 5.6, RHEL 6.6. Is that ok?
- "QGenericArgument()": ellipsis,
- "QGenericArgument(0)": ellipsis,
- "QGenericArgument(NULL)": ellipsis, # 5.6, MSVC
- "QGenericArgument(nullptr)": ellipsis, # 5.10
- "QGenericArgument(Q_NULLPTR)": ellipsis,
- "QJsonObject": typing.Dict[str, PySide2.QtCore.QJsonValue],
- "QModelIndex()": Invalid("PySide2.QtCore.QModelIndex"), # repr is btw. very wrong, fix it?!
- "QModelIndexList": ModelIndexList,
- "QModelIndexList": ModelIndexList,
- "QString()": "",
- "QStringList()": [],
- "QStringRef": str,
- "QStringRef": str,
- "Qt.HANDLE": int, # be more explicit with some constants?
- "QUrl.FormattingOptions(PrettyDecoded)": Instance(
- "QUrl.FormattingOptions(QUrl.PrettyDecoded)"),
- "QVariant()": Invalid(Variant),
- "QVariant.Type": type, # not so sure here...
- "QVariantMap": typing.Dict[str, Variant],
- "QVariantMap": typing.Dict[str, Variant],
- })
- try:
- type_map.update({
- "PySide2.QtCore.QMetaObject.Connection": PySide2.QtCore.Connection, # wrong!
- })
- except AttributeError:
- # this does not exist on 5.9 ATM.
- pass
- return locals()
-
-
-def init_PySide2_QtGui():
- from PySide2.QtGui import QPageLayout, QPageSize # 5.12 macOS
- type_map.update({
- "0.0f": 0.0,
- "1.0f": 1.0,
- "GL_COLOR_BUFFER_BIT": GL_COLOR_BUFFER_BIT,
- "GL_NEAREST": GL_NEAREST,
- "int32_t": int,
- "QPixmap()": Default("PySide2.QtGui.QPixmap"), # can't create without qApp
- "QPlatformSurface*": int, # a handle
- "QVector< QTextLayout.FormatRange >()": [], # do we need more structure?
- "uint32_t": int,
- "uint8_t": int,
- "USHRT_MAX": ushort_max,
- })
- return locals()
-
-
-def init_PySide2_QtWidgets():
- from PySide2.QtWidgets import QWidget, QMessageBox, QStyleOption, QStyleHintReturn, QStyleOptionComplex
- from PySide2.QtWidgets import QGraphicsItem, QStyleOptionGraphicsItem # 5.9
- type_map.update({
- "QMessageBox.StandardButtons(Yes | No)": Instance(
- "QMessageBox.StandardButtons(QMessageBox.Yes | QMessageBox.No)"),
- "QWidget.RenderFlags(DrawWindowBackground | DrawChildren)": Instance(
- "QWidget.RenderFlags(QWidget.DrawWindowBackground | QWidget.DrawChildren)"),
- "SH_Default": QStyleHintReturn.SH_Default,
- "SO_Complex": QStyleOptionComplex.SO_Complex,
- "SO_Default": QStyleOption.SO_Default,
- "static_cast<Qt.MatchFlags>(Qt.MatchExactly|Qt.MatchCaseSensitive)": Instance(
- "Qt.MatchFlags(Qt.MatchExactly | Qt.MatchCaseSensitive)"),
- "Type": PySide2.QtWidgets.QListWidgetItem.Type,
- })
- return locals()
-
-
-def init_PySide2_QtSql():
- from PySide2.QtSql import QSqlDatabase
- type_map.update({
- "QLatin1String(defaultConnection)": QSqlDatabase.defaultConnection,
- "QVariant.Invalid": Invalid("Variant"), # not sure what I should create, here...
- })
- return locals()
-
-
-def init_PySide2_QtNetwork():
- best_structure = typing.OrderedDict if getattr(typing, "OrderedDict", None) else typing.Dict
- type_map.update({
- "QMultiMap[PySide2.QtNetwork.QSsl.AlternativeNameEntryType, QString]":
- best_structure[PySide2.QtNetwork.QSsl.AlternativeNameEntryType, typing.List[str]],
- })
- del best_structure
- return locals()
-
-
-def init_PySide2_QtXmlPatterns():
- from PySide2.QtXmlPatterns import QXmlName
- type_map.update({
- "QXmlName.NamespaceCode": Missing("PySide2.QtXmlPatterns.QXmlName.NamespaceCode"),
- "QXmlName.PrefixCode": Missing("PySide2.QtXmlPatterns.QXmlName.PrefixCode"),
- })
- return locals()
-
-
-def init_PySide2_QtMultimedia():
- import PySide2.QtMultimediaWidgets
- # Check if foreign import is valid. See mapping.py in shiboken2.
- check_module(PySide2.QtMultimediaWidgets)
- type_map.update({
- "QGraphicsVideoItem": PySide2.QtMultimediaWidgets.QGraphicsVideoItem,
- "qint64": int,
- "QVideoWidget": PySide2.QtMultimediaWidgets.QVideoWidget,
- })
- return locals()
-
-
-def init_PySide2_QtOpenGL():
- type_map.update({
- "GLbitfield": int,
- "GLenum": int,
- "GLfloat": float, # 5.6, MSVC 15
- "GLint": int,
- "GLuint": int,
- })
- return locals()
-
-
-def init_PySide2_QtQml():
- type_map.update({
- "QJSValueList()": [],
- "QVariantHash()": typing.Dict[str, Variant], # from 5.9
- })
- return locals()
-
-
-def init_PySide2_QtQuick():
- type_map.update({
- "PySide2.QtQuick.QSharedPointer[PySide2.QtQuick.QQuickItemGrabResult]":
- PySide2.QtQuick.QQuickItemGrabResult,
- "UnsignedShortType": int,
- })
- return locals()
-
-
-def init_PySide2_QtScript():
- type_map.update({
- "QScriptValueList()": [],
- })
- return locals()
-
-
-def init_PySide2_QtTest():
- type_map.update({
- "PySide2.QtTest.QTest.PySideQTouchEventSequence": PySide2.QtTest.QTest.QTouchEventSequence,
- "PySide2.QtTest.QTouchEventSequence": PySide2.QtTest.QTest.QTouchEventSequence,
- })
- return locals()
-
-# from 5.6, MSVC
-def init_PySide2_QtWinExtras():
- type_map.update({
- "QList< QWinJumpListItem* >()": [],
- })
- return locals()
-
-# from 5.12, macOS
-def init_PySide2_QtDataVisualization():
- from PySide2.QtDataVisualization import QtDataVisualization
- QtDataVisualization.QBarDataRow = typing.List[QtDataVisualization.QBarDataItem]
- QtDataVisualization.QBarDataArray = typing.List[QtDataVisualization.QBarDataRow]
- QtDataVisualization.QSurfaceDataRow = typing.List[QtDataVisualization.QSurfaceDataItem]
- QtDataVisualization.QSurfaceDataArray = typing.List[QtDataVisualization.QSurfaceDataRow]
- type_map.update({
- "100.0f": 100.0,
- "QtDataVisualization.QBarDataArray": QtDataVisualization.QBarDataArray,
- "QtDataVisualization.QBarDataArray*": QtDataVisualization.QBarDataArray,
- "QtDataVisualization.QSurfaceDataArray": QtDataVisualization.QSurfaceDataArray,
- "QtDataVisualization.QSurfaceDataArray*": QtDataVisualization.QSurfaceDataArray,
- })
- return locals()
-
-
-def init_testbinding():
- type_map.update({
- "testbinding.PySideCPP2.TestObjectWithoutNamespace": testbinding.TestObjectWithoutNamespace,
- })
- return locals()
-
-# end of file
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/parser.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/parser.py
deleted file mode 100644
index 2053c3e9d..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/parser.py
+++ /dev/null
@@ -1,458 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function, absolute_import
-
-import sys
-import re
-import warnings
-import types
-import keyword
-import functools
-from shibokensupport.signature.mapping import (type_map, update_mapping,
- namespace, typing, _NotCalled, ResultVariable, ArrayLikeVariable)
-from shibokensupport.signature.lib.tool import (SimpleNamespace,
- build_brace_pattern)
-
-_DEBUG = False
-LIST_KEYWORDS = False
-
-"""
-parser.py
-
-This module parses the signature text and creates properties for the
-signature objects.
-
-PySide has a new function 'CppGenerator::writeSignatureInfo()'
-that extracts the gathered information about the function arguments
-and defaults as good as it can. But what PySide generates is still
-very C-ish and has many constants that Python doesn't understand.
-
-The function 'try_to_guess()' below understands a lot of PySide's
-peculiar way to assume local context. If it is able to do the guess,
-then the result is inserted into the dict, so the search happens
-not again. For everything that is not covered by these automatic
-guesses, we provide an entry in 'type_map' that resolves it.
-
-In effect, 'type_map' maps text to real Python objects.
-"""
-
-def dprint(*args, **kw):
- if _DEBUG:
- import pprint
- for arg in args:
- pprint.pprint(arg)
- sys.stdout.flush()
-
-
-_cache = {}
-
-def _parse_arglist(argstr):
- # The following is a split re. The string is broken into pieces which are
- # between the recognized strings. Because the re has groups, both the
- # strings and the separators are returned, where the strings are not
- # interesting at all: They are just the commata.
- key = "_parse_arglist"
- if key not in _cache:
- regex = build_brace_pattern(level=3, separators=",")
- _cache[key] = re.compile(regex, flags=re.VERBOSE)
- split = _cache[key].split
- # Note: this list is interspersed with "," and surrounded by ""
- return [x.strip() for x in split(argstr) if x.strip() not in ("", ",")]
-
-
-def _parse_line(line):
- line_re = r"""
- ((?P<multi> ([0-9]+)) : )? # the optional multi-index
- (?P<funcname> \w+(\.\w+)*) # the function name
- \( (?P<arglist> .*?) \) # the argument list
- ( -> (?P<returntype> .*) )? # the optional return type
- $
- """
- ret = SimpleNamespace(**re.match(line_re, line, re.VERBOSE).groupdict())
- # PYSIDE-1095: Handle arbitrary default expressions
- argstr = ret.arglist.replace("->", ".deref.")
- arglist = _parse_arglist(argstr)
- args = []
- for arg in arglist:
- name, ann = arg.split(":")
- if name in keyword.kwlist:
- if LIST_KEYWORDS:
- print("KEYWORD", ret)
- name = name + "_"
- if "=" in ann:
- ann, default = ann.split("=", 1)
- tup = name, ann, default
- else:
- tup = name, ann
- args.append(tup)
- ret.arglist = args
- multi = ret.multi
- if multi is not None:
- ret.multi = int(multi)
- funcname = ret.funcname
- parts = funcname.split(".")
- if parts[-1] in keyword.kwlist:
- ret.funcname = funcname + "_"
- return vars(ret)
-
-
-def make_good_value(thing, valtype):
- try:
- if thing.endswith("()"):
- thing = 'Default("{}")'.format(thing[:-2])
- else:
- ret = eval(thing, namespace)
- if valtype and repr(ret).startswith("<"):
- thing = 'Instance("{}")'.format(thing)
- return eval(thing, namespace)
- except Exception:
- pass
-
-
-def try_to_guess(thing, valtype):
- if "." not in thing and "(" not in thing:
- text = "{}.{}".format(valtype, thing)
- ret = make_good_value(text, valtype)
- if ret is not None:
- return ret
- typewords = valtype.split(".")
- valwords = thing.split(".")
- braceless = valwords[0] # Yes, not -1. Relevant is the overlapped word.
- if "(" in braceless:
- braceless = braceless[:braceless.index("(")]
- for idx, w in enumerate(typewords):
- if w == braceless:
- text = ".".join(typewords[:idx] + valwords)
- ret = make_good_value(text, valtype)
- if ret is not None:
- return ret
- return None
-
-def get_name(thing):
- if isinstance(thing, type):
- return getattr(thing, "__qualname__", thing.__name__)
- else:
- return thing.__name__
-
-def _resolve_value(thing, valtype, line):
- if thing in ("0", "None") and valtype:
- if valtype.startswith("PySide2.") or valtype.startswith("typing."):
- return None
- map = type_map[valtype]
- # typing.Any: '_SpecialForm' object has no attribute '__name__'
- name = get_name(map) if hasattr(map, "__name__") else str(map)
- thing = "zero({})".format(name)
- if thing in type_map:
- return type_map[thing]
- res = make_good_value(thing, valtype)
- if res is not None:
- type_map[thing] = res
- return res
- res = try_to_guess(thing, valtype) if valtype else None
- if res is not None:
- type_map[thing] = res
- return res
- warnings.warn("""pyside_type_init:
-
- UNRECOGNIZED: {!r}
- OFFENDING LINE: {!r}
- """.format(thing, line), RuntimeWarning)
- return thing
-
-
-def _resolve_arraytype(thing, line):
- search = re.search(r"\[(\d*)\]$", thing)
- thing = thing[:search.start()]
- if thing.endswith("]"):
- thing = _resolve_arraytype(thing, line)
- if search.group(1):
- # concrete array, use a tuple
- nelem = int(search.group(1))
- thing = ", ".join([thing] * nelem)
- thing = "Tuple[" + thing + "]"
- else:
- thing = "QList[" + thing + "]"
- return thing
-
-
-def to_string(thing):
- if isinstance(thing, str):
- return thing
- if hasattr(thing, "__name__"):
- dot = "." in str(thing)
- name = get_name(thing)
- return thing.__module__ + "." + name if dot else name
- # Note: This captures things from the typing module:
- return str(thing)
-
-
-matrix_pattern = "PySide2.QtGui.QGenericMatrix"
-
-def handle_matrix(arg):
- n, m, typstr = tuple(map(lambda x:x.strip(), arg.split(",")))
- assert typstr == "float"
- result = "PySide2.QtGui.QMatrix{n}x{m}".format(**locals())
- return eval(result, namespace)
-
-
-debugging_aid = """
-from inspect import currentframe
-
-def lno(level):
- lineno = currentframe().f_back.f_lineno
- spaces = level * " "
- return "{lineno}{spaces}".format(**locals())
-"""
-
-
-def _resolve_type(thing, line, level, var_handler):
- # Capture total replacements, first. Happens in
- # "PySide2.QtCore.QCborStreamReader.StringResult[PySide2.QtCore.QByteArray]"
- if thing in type_map:
- return type_map[thing]
- # Now the nested structures are handled.
- if "[" in thing:
- # handle primitive arrays
- if re.search(r"\[\d*\]$", thing):
- thing = _resolve_arraytype(thing, line)
- # Handle a container return type. (see PYSIDE-921 in cppgenerator.cpp)
- contr, thing = re.match(r"(.*?)\[(.*?)\]$", thing).groups()
- # Special case: Handle the generic matrices.
- if contr == matrix_pattern:
- return handle_matrix(thing)
- contr = var_handler(_resolve_type(contr, line, level+1, var_handler))
- if isinstance(contr, _NotCalled):
- raise SystemError("Container types must exist:", repr(contr))
- contr = to_string(contr)
- pieces = []
- for part in _parse_arglist(thing):
- part = var_handler(_resolve_type(part, line, level+1, var_handler))
- if isinstance(part, _NotCalled):
- # fix the tag (i.e. "Missing") by repr
- part = repr(part)
- pieces.append(to_string(part))
- thing = ", ".join(pieces)
- result = "{contr}[{thing}]".format(**locals())
- return eval(result, namespace)
- return _resolve_value(thing, None, line)
-
-
-def _handle_generic(obj, repl):
- """
- Assign repl if obj is an ArrayLikeVariable
-
- This is a neat trick. Example:
-
- obj repl result
- ---------------------- -------- ---------
- ArrayLikeVariable List List
- ArrayLikeVariable(str) List List[str]
- ArrayLikeVariable Sequence Sequence
- ArrayLikeVariable(str) Sequence Sequence[str]
- """
- if isinstance(obj, ArrayLikeVariable):
- return repl[obj.type]
- if isinstance(obj, type) and issubclass(obj, ArrayLikeVariable):
- # was "if obj is ArrayLikeVariable"
- return repl
- return obj
-
-
-def handle_argvar(obj):
- """
- Decide how array-like variables are resolved in arguments
-
- Currently, the best approximation is types.Sequence.
- We want to change that to types.Iterable in the near future.
- """
- return _handle_generic(obj, typing.Sequence)
-
-
-def handle_retvar(obj):
- """
- Decide how array-like variables are resolved in results
-
- This will probably stay typing.List forever.
- """
- return _handle_generic(obj, typing.List)
-
-
-def calculate_props(line):
- parsed = SimpleNamespace(**_parse_line(line.strip()))
- arglist = parsed.arglist
- annotations = {}
- _defaults = []
- for idx, tup in enumerate(arglist):
- name, ann = tup[:2]
- if ann == "...":
- name = "*args" if name.startswith("arg_") else "*" + name
- # copy the pathed fields back
- ann = 'nullptr' # maps to None
- tup = name, ann
- arglist[idx] = tup
- annotations[name] = _resolve_type(ann, line, 0, handle_argvar)
- if len(tup) == 3:
- default = _resolve_value(tup[2], ann, line)
- _defaults.append(default)
- defaults = tuple(_defaults)
- returntype = parsed.returntype
- if returntype is not None:
- annotations["return"] = _resolve_type(returntype, line, 0, handle_retvar)
- props = SimpleNamespace()
- props.defaults = defaults
- props.kwdefaults = {}
- props.annotations = annotations
- props.varnames = varnames = tuple(tup[0] for tup in arglist)
- funcname = parsed.funcname
- props.fullname = funcname
- shortname = funcname[funcname.rindex(".")+1:]
- props.name = shortname
- props.multi = parsed.multi
- fix_variables(props, line)
- return vars(props)
-
-
-def fix_variables(props, line):
- annos = props.annotations
- if not any(isinstance(ann, (ResultVariable, ArrayLikeVariable))
- for ann in annos.values()):
- return
- retvar = annos.get("return", None)
- if retvar and isinstance(retvar, (ResultVariable, ArrayLikeVariable)):
- # Special case: a ResultVariable which is the result will always be an array!
- annos["return"] = retvar = typing.List[retvar.type]
- fullname = props.fullname
- varnames = list(props.varnames)
- defaults = list(props.defaults)
- diff = len(varnames) - len(defaults)
-
- safe_annos = annos.copy()
- retvars = [retvar] if retvar else []
- deletions = []
- for idx, name in enumerate(varnames):
- ann = safe_annos[name]
- if isinstance(ann, ArrayLikeVariable):
- ann = typing.Sequence[ann.type]
- annos[name] = ann
- if not isinstance(ann, ResultVariable):
- continue
- # We move the variable to the end and remove it.
- retvars.append(ann.type)
- deletions.append(idx)
- del annos[name]
- for idx in reversed(deletions):
- # varnames: 0 1 2 3 4 5 6 7
- # defaults: 0 1 2 3 4
- # diff: 3
- del varnames[idx]
- if idx >= diff:
- del defaults[idx - diff]
- else:
- diff -= 1
- if retvars:
- rvs = []
- retvars = list(handle_retvar(rv) if isinstance(rv, ArrayLikeVariable) else rv
- for rv in retvars)
- if len(retvars) == 1:
- returntype = retvars[0]
- else:
- typestr = "typing.Tuple[{}]".format(", ".join(map(to_string, retvars)))
- returntype = eval(typestr, namespace)
- props.annotations["return"] = returntype
- props.varnames = tuple(varnames)
- props.defaults = tuple(defaults)
-
-
-def fixup_multilines(lines):
- """
- Multilines can collapse when certain distinctions between C++ types
- vanish after mapping to Python.
- This function fixes this by re-computing multiline-ness.
- """
- res = []
- multi_lines = []
- for line in lines:
- multi = re.match(r"([0-9]+):", line)
- if multi:
- idx, rest = int(multi.group(1)), line[multi.end():]
- multi_lines.append(rest)
- if idx > 0:
- continue
- # remove duplicates
- multi_lines = sorted(set(multi_lines))
- # renumber or return a single line
- nmulti = len(multi_lines)
- if nmulti > 1:
- for idx, line in enumerate(multi_lines):
- res.append("{}:{}".format(nmulti-idx-1, line))
- else:
- res.append(multi_lines[0])
- multi_lines = []
- else:
- res.append(line)
- return res
-
-
-def pyside_type_init(type_key, sig_strings):
- dprint()
- dprint("Initialization of type key '{}'".format(type_key))
- update_mapping()
- lines = fixup_multilines(sig_strings)
- ret = {}
- multi_props = []
- for line in lines:
- props = calculate_props(line)
- shortname = props["name"]
- multi = props["multi"]
- if multi is None:
- ret[shortname] = props
- dprint(props)
- else:
- multi_props.append(props)
- if multi > 0:
- continue
- fullname = props.pop("fullname")
- multi_props = {"multi": multi_props, "fullname": fullname}
- ret[shortname] = multi_props
- dprint(multi_props)
- multi_props = []
- return ret
-
-# end of file
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/qt_attribution.json b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/qt_attribution.json
deleted file mode 100644
index fbe4c51ab..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/signature/qt_attribution.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "Id": "python",
- "Name": "Python",
- "QDocModule": "QtForPython",
- "QtUsage": "Used for Qt for Python in the signature extension.",
- "Description": "Qt for Python is an add-on for Python. The signature packages of PySide uses certain copied and adapted source files (backport_inspect.py, typing27.py). See the folder sources/shiboken2/files.dir/shibokensupport/signature .",
- "Homepage": "http://www.python.org/",
- "Version": "3.7.0",
- "LicenseId": "Python-2.0",
- "License": "Python License 2.0",
- "LicenseFile": "PSF-3.7.0.txt",
- "Copyright": "© Copyright 2001-2018, Python Software Foundation."
-}
diff --git a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/typing27.py b/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/typing27.py
deleted file mode 100644
index 41ed456cc..000000000
--- a/sources/shiboken2/shibokenmodule/files.dir/shibokensupport/typing27.py
+++ /dev/null
@@ -1,2636 +0,0 @@
-# This Python file uses the following encoding: utf-8
-# It has been edited by fix-complaints.py .
-
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-"""
-PSF LICENSE AGREEMENT FOR PYTHON 3.7.0
-
-1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
- the Individual or Organization ("Licensee") accessing and otherwise using Python
- 3.7.0 software in source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, PSF hereby
- grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
- analyze, test, perform and/or display publicly, prepare derivative works,
- distribute, and otherwise use Python 3.7.0 alone or in any derivative
- version, provided, however, that PSF's License Agreement and PSF's notice of
- copyright, i.e., "Copyright © 2001-2018 Python Software Foundation; All Rights
- Reserved" are retained in Python 3.7.0 alone or in any derivative version
- prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on or
- incorporates Python 3.7.0 or any part thereof, and wants to make the
- derivative work available to others as provided herein, then Licensee hereby
- agrees to include in any such work a brief summary of the changes made to Python
- 3.7.0.
-
-4. PSF is making Python 3.7.0 available to Licensee on an "AS IS" basis.
- PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
- EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
- WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
- USE OF PYTHON 3.7.0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.7.0
- FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
- MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.7.0, OR ANY DERIVATIVE
- THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material breach of
- its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any relationship
- of agency, partnership, or joint venture between PSF and Licensee. This License
- Agreement does not grant permission to use PSF trademarks or trade name in a
- trademark sense to endorse or promote products or services of Licensee, or any
- third party.
-
-8. By copying, installing or otherwise using Python 3.7.0, Licensee agrees
- to be bound by the terms and conditions of this License Agreement.
-"""
-
-# This is the typing module for Python 2.7
-# https://github.com/python/typing
-# 2019-08-22
-
-from __future__ import absolute_import, unicode_literals
-
-import abc
-from abc import abstractmethod, abstractproperty
-import collections
-import functools
-import re as stdlib_re # Avoid confusion with the re we export.
-import sys
-import types
-import copy
-try:
- import collections.abc as collections_abc
-except ImportError:
- import collections as collections_abc # Fallback for PY3.2.
-
-
-# Please keep __all__ alphabetized within each category.
-__all__ = [
- # Super-special typing primitives.
- 'Any',
- 'Callable',
- 'ClassVar',
- 'Final',
- 'Generic',
- 'Literal',
- 'Optional',
- 'Protocol',
- 'Tuple',
- 'Type',
- 'TypeVar',
- 'Union',
-
- # ABCs (from collections.abc).
- 'AbstractSet', # collections.abc.Set.
- 'GenericMeta', # subclass of abc.ABCMeta and a metaclass
- # for 'Generic' and ABCs below.
- 'ByteString',
- 'Container',
- 'ContextManager',
- 'Hashable',
- 'ItemsView',
- 'Iterable',
- 'Iterator',
- 'KeysView',
- 'Mapping',
- 'MappingView',
- 'MutableMapping',
- 'MutableSequence',
- 'MutableSet',
- 'Sequence',
- 'Sized',
- 'ValuesView',
-
- # Structural checks, a.k.a. protocols.
- 'Reversible',
- 'SupportsAbs',
- 'SupportsComplex',
- 'SupportsFloat',
- 'SupportsIndex',
- 'SupportsInt',
-
- # Concrete collection types.
- 'Counter',
- 'Deque',
- 'Dict',
- 'DefaultDict',
- 'List',
- 'Set',
- 'FrozenSet',
- 'NamedTuple', # Not really a type.
- 'TypedDict', # Not really a type.
- 'Generator',
-
- # One-off things.
- 'AnyStr',
- 'cast',
- 'final',
- 'get_type_hints',
- 'NewType',
- 'no_type_check',
- 'no_type_check_decorator',
- 'NoReturn',
- 'overload',
- 'runtime_checkable',
- 'Text',
- 'TYPE_CHECKING',
-]
-
-# The pseudo-submodules 're' and 'io' are part of the public
-# namespace, but excluded from __all__ because they might stomp on
-# legitimate imports of those modules.
-
-
-def _qualname(x):
- # PYSIDE-1286: Support __qualname__ in Python 2
- return getattr(x, "__qualname__", x.__name__)
-
-
-def _trim_name(nm):
- whitelist = ('_TypeAlias', '_ForwardRef', '_TypingBase', '_FinalTypingBase')
- if nm.startswith('_') and nm not in whitelist:
- nm = nm[1:]
- return nm
-
-
-class TypingMeta(type):
- """Metaclass for most types defined in typing module
- (not a part of public API).
-
- This also defines a dummy constructor (all the work for most typing
- constructs is done in __new__) and a nicer repr().
- """
-
- _is_protocol = False
-
- def __new__(cls, name, bases, namespace):
- return super(TypingMeta, cls).__new__(cls, str(name), bases, namespace)
-
- @classmethod
- def assert_no_subclassing(cls, bases):
- for base in bases:
- if isinstance(base, cls):
- raise TypeError("Cannot subclass %s" %
- (', '.join(map(_type_repr, bases)) or '()'))
-
- def __init__(self, *args, **kwds):
- pass
-
- def _eval_type(self, globalns, localns):
- """Override this in subclasses to interpret forward references.
-
- For example, List['C'] is internally stored as
- List[_ForwardRef('C')], which should evaluate to List[C],
- where C is an object found in globalns or localns (searching
- localns first, of course).
- """
- return self
-
- def _get_type_vars(self, tvars):
- pass
-
- def __repr__(self):
- qname = _trim_name(_qualname(self))
- return '%s.%s' % (self.__module__, qname)
-
-
-class _TypingBase(object):
- """Internal indicator of special typing constructs."""
- __metaclass__ = TypingMeta
- __slots__ = ('__weakref__',)
-
- def __init__(self, *args, **kwds):
- pass
-
- def __new__(cls, *args, **kwds):
- """Constructor.
-
- This only exists to give a better error message in case
- someone tries to subclass a special typing object (not a good idea).
- """
- if (len(args) == 3 and
- isinstance(args[0], str) and
- isinstance(args[1], tuple)):
- # Close enough.
- raise TypeError("Cannot subclass %r" % cls)
- return super(_TypingBase, cls).__new__(cls)
-
- # Things that are not classes also need these.
- def _eval_type(self, globalns, localns):
- return self
-
- def _get_type_vars(self, tvars):
- pass
-
- def __repr__(self):
- cls = type(self)
- qname = _trim_name(_qualname(cls))
- return '%s.%s' % (cls.__module__, qname)
-
- def __call__(self, *args, **kwds):
- raise TypeError("Cannot instantiate %r" % type(self))
-
-
-class _FinalTypingBase(_TypingBase):
- """Internal mix-in class to prevent instantiation.
-
- Prevents instantiation unless _root=True is given in class call.
- It is used to create pseudo-singleton instances Any, Union, Optional, etc.
- """
-
- __slots__ = ()
-
- def __new__(cls, *args, **kwds):
- self = super(_FinalTypingBase, cls).__new__(cls, *args, **kwds)
- if '_root' in kwds and kwds['_root'] is True:
- return self
- raise TypeError("Cannot instantiate %r" % cls)
-
- def __reduce__(self):
- return _trim_name(type(self).__name__)
-
-
-class _ForwardRef(_TypingBase):
- """Internal wrapper to hold a forward reference."""
-
- __slots__ = ('__forward_arg__', '__forward_code__',
- '__forward_evaluated__', '__forward_value__')
-
- def __init__(self, arg):
- super(_ForwardRef, self).__init__(arg)
- if not isinstance(arg, basestring):
- raise TypeError('Forward reference must be a string -- got %r' % (arg,))
- try:
- code = compile(arg, '<string>', 'eval')
- except SyntaxError:
- raise SyntaxError('Forward reference must be an expression -- got %r' %
- (arg,))
- self.__forward_arg__ = arg
- self.__forward_code__ = code
- self.__forward_evaluated__ = False
- self.__forward_value__ = None
-
- def _eval_type(self, globalns, localns):
- if not self.__forward_evaluated__ or localns is not globalns:
- if globalns is None and localns is None:
- globalns = localns = {}
- elif globalns is None:
- globalns = localns
- elif localns is None:
- localns = globalns
- self.__forward_value__ = _type_check(
- eval(self.__forward_code__, globalns, localns),
- "Forward references must evaluate to types.")
- self.__forward_evaluated__ = True
- return self.__forward_value__
-
- def __eq__(self, other):
- if not isinstance(other, _ForwardRef):
- return NotImplemented
- return (self.__forward_arg__ == other.__forward_arg__ and
- self.__forward_value__ == other.__forward_value__)
-
- def __hash__(self):
- return hash((self.__forward_arg__, self.__forward_value__))
-
- def __instancecheck__(self, obj):
- raise TypeError("Forward references cannot be used with isinstance().")
-
- def __subclasscheck__(self, cls):
- raise TypeError("Forward references cannot be used with issubclass().")
-
- def __repr__(self):
- return '_ForwardRef(%r)' % (self.__forward_arg__,)
-
-
-class _TypeAlias(_TypingBase):
- """Internal helper class for defining generic variants of concrete types.
-
- Note that this is not a type; let's call it a pseudo-type. It cannot
- be used in instance and subclass checks in parameterized form, i.e.
- ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
- ``False``.
- """
-
- __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
-
- def __init__(self, name, type_var, impl_type, type_checker):
- """Initializer.
-
- Args:
- name: The name, e.g. 'Pattern'.
- type_var: The type parameter, e.g. AnyStr, or the
- specific type, e.g. str.
- impl_type: The implementation type.
- type_checker: Function that takes an impl_type instance.
- and returns a value that should be a type_var instance.
- """
- assert isinstance(name, basestring), repr(name)
- assert isinstance(impl_type, type), repr(impl_type)
- assert not isinstance(impl_type, TypingMeta), repr(impl_type)
- assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
- self.name = name
- self.type_var = type_var
- self.impl_type = impl_type
- self.type_checker = type_checker
-
- def __repr__(self):
- return "%s[%s]" % (self.name, _type_repr(self.type_var))
-
- def __getitem__(self, parameter):
- if not isinstance(self.type_var, TypeVar):
- raise TypeError("%s cannot be further parameterized." % self)
- if self.type_var.__constraints__ and isinstance(parameter, type):
- if not issubclass(parameter, self.type_var.__constraints__):
- raise TypeError("%s is not a valid substitution for %s." %
- (parameter, self.type_var))
- if isinstance(parameter, TypeVar) and parameter is not self.type_var:
- raise TypeError("%s cannot be re-parameterized." % self)
- return self.__class__(self.name, parameter,
- self.impl_type, self.type_checker)
-
- def __eq__(self, other):
- if not isinstance(other, _TypeAlias):
- return NotImplemented
- return self.name == other.name and self.type_var == other.type_var
-
- def __hash__(self):
- return hash((self.name, self.type_var))
-
- def __instancecheck__(self, obj):
- if not isinstance(self.type_var, TypeVar):
- raise TypeError("Parameterized type aliases cannot be used "
- "with isinstance().")
- return isinstance(obj, self.impl_type)
-
- def __subclasscheck__(self, cls):
- if not isinstance(self.type_var, TypeVar):
- raise TypeError("Parameterized type aliases cannot be used "
- "with issubclass().")
- return issubclass(cls, self.impl_type)
-
-
-def _get_type_vars(types, tvars):
- for t in types:
- if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
- t._get_type_vars(tvars)
-
-
-def _type_vars(types):
- tvars = []
- _get_type_vars(types, tvars)
- return tuple(tvars)
-
-
-def _eval_type(t, globalns, localns):
- if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
- return t._eval_type(globalns, localns)
- return t
-
-
-def _type_check(arg, msg):
- """Check that the argument is a type, and return it (internal helper).
-
- As a special case, accept None and return type(None) instead.
- Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
-
- The msg argument is a human-readable error message, e.g.
-
- "Union[arg, ...]: arg should be a type."
-
- We append the repr() of the actual value (truncated to 100 chars).
- """
- if arg is None:
- return type(None)
- if isinstance(arg, basestring):
- arg = _ForwardRef(arg)
- if (
- isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
- not isinstance(arg, (type, _TypingBase)) and not callable(arg)
- ):
- raise TypeError(msg + " Got %.100r." % (arg,))
- # Bare Union etc. are not valid as type arguments
- if (
- type(arg).__name__ in ('_Union', '_Optional') and
- not getattr(arg, '__origin__', None) or
- isinstance(arg, TypingMeta) and arg._gorg in (Generic, Protocol)
- ):
- raise TypeError("Plain %s is not valid as type argument" % arg)
- return arg
-
-
-def _type_repr(obj):
- """Return the repr() of an object, special-casing types (internal helper).
-
- If obj is a type, we return a shorter version than the default
- type.__repr__, based on the module and qualified name, which is
- typically enough to uniquely identify a type. For everything
- else, we fall back on repr(obj).
- """
- if isinstance(obj, type) and not isinstance(obj, TypingMeta):
- if obj.__module__ == '__builtin__':
- return _qualname(obj)
- return '%s.%s' % (obj.__module__, _qualname(obj))
- if obj is Ellipsis:
- return '...'
- if isinstance(obj, types.FunctionType):
- return obj.__name__
- return repr(obj)
-
-
-class ClassVarMeta(TypingMeta):
- """Metaclass for _ClassVar"""
-
- def __new__(cls, name, bases, namespace):
- cls.assert_no_subclassing(bases)
- self = super(ClassVarMeta, cls).__new__(cls, name, bases, namespace)
- return self
-
-
-class _ClassVar(_FinalTypingBase):
- """Special type construct to mark class variables.
-
- An annotation wrapped in ClassVar indicates that a given
- attribute is intended to be used as a class variable and
- should not be set on instances of that class. Usage::
-
- class Starship:
- stats = {} # type: ClassVar[Dict[str, int]] # class variable
- damage = 10 # type: int # instance variable
-
- ClassVar accepts only types and cannot be further subscribed.
-
- Note that ClassVar is not a class itself, and should not
- be used with isinstance() or issubclass().
- """
-
- __metaclass__ = ClassVarMeta
- __slots__ = ('__type__',)
-
- def __init__(self, tp=None, _root=False):
- self.__type__ = tp
-
- def __getitem__(self, item):
- cls = type(self)
- if self.__type__ is None:
- return cls(_type_check(item,
- '{} accepts only types.'.format(cls.__name__[1:])),
- _root=True)
- raise TypeError('{} cannot be further subscripted'
- .format(cls.__name__[1:]))
-
- def _eval_type(self, globalns, localns):
- return type(self)(_eval_type(self.__type__, globalns, localns),
- _root=True)
-
- def __repr__(self):
- r = super(_ClassVar, self).__repr__()
- if self.__type__ is not None:
- r += '[{}]'.format(_type_repr(self.__type__))
- return r
-
- def __hash__(self):
- return hash((type(self).__name__, self.__type__))
-
- def __eq__(self, other):
- if not isinstance(other, _ClassVar):
- return NotImplemented
- if self.__type__ is not None:
- return self.__type__ == other.__type__
- return self is other
-
-
-ClassVar = _ClassVar(_root=True)
-
-
-class _FinalMeta(TypingMeta):
- """Metaclass for _Final"""
-
- def __new__(cls, name, bases, namespace):
- cls.assert_no_subclassing(bases)
- self = super(_FinalMeta, cls).__new__(cls, name, bases, namespace)
- return self
-
-
-class _Final(_FinalTypingBase):
- """A special typing construct to indicate that a name
- cannot be re-assigned or overridden in a subclass.
- For example:
-
- MAX_SIZE: Final = 9000
- MAX_SIZE += 1 # Error reported by type checker
-
- class Connection:
- TIMEOUT: Final[int] = 10
- class FastConnector(Connection):
- TIMEOUT = 1 # Error reported by type checker
-
- There is no runtime checking of these properties.
- """
-
- __metaclass__ = _FinalMeta
- __slots__ = ('__type__',)
-
- def __init__(self, tp=None, **kwds):
- self.__type__ = tp
-
- def __getitem__(self, item):
- cls = type(self)
- if self.__type__ is None:
- return cls(_type_check(item,
- '{} accepts only single type.'.format(cls.__name__[1:])),
- _root=True)
- raise TypeError('{} cannot be further subscripted'
- .format(cls.__name__[1:]))
-
- def _eval_type(self, globalns, localns):
- new_tp = _eval_type(self.__type__, globalns, localns)
- if new_tp == self.__type__:
- return self
- return type(self)(new_tp, _root=True)
-
- def __repr__(self):
- r = super(_Final, self).__repr__()
- if self.__type__ is not None:
- r += '[{}]'.format(_type_repr(self.__type__))
- return r
-
- def __hash__(self):
- return hash((type(self).__name__, self.__type__))
-
- def __eq__(self, other):
- if not isinstance(other, _Final):
- return NotImplemented
- if self.__type__ is not None:
- return self.__type__ == other.__type__
- return self is other
-
-
-Final = _Final(_root=True)
-
-
-def final(f):
- """This decorator can be used to indicate to type checkers that
- the decorated method cannot be overridden, and decorated class
- cannot be subclassed. For example:
-
- class Base:
- @final
- def done(self) -> None:
- ...
- class Sub(Base):
- def done(self) -> None: # Error reported by type checker
- ...
- @final
- class Leaf:
- ...
- class Other(Leaf): # Error reported by type checker
- ...
-
- There is no runtime checking of these properties.
- """
- return f
-
-
-class _LiteralMeta(TypingMeta):
- """Metaclass for _Literal"""
-
- def __new__(cls, name, bases, namespace):
- cls.assert_no_subclassing(bases)
- self = super(_LiteralMeta, cls).__new__(cls, name, bases, namespace)
- return self
-
-
-class _Literal(_FinalTypingBase):
- """A type that can be used to indicate to type checkers that the
- corresponding value has a value literally equivalent to the
- provided parameter. For example:
-
- var: Literal[4] = 4
-
- The type checker understands that 'var' is literally equal to the
- value 4 and no other value.
-
- Literal[...] cannot be subclassed. There is no runtime checking
- verifying that the parameter is actually a value instead of a type.
- """
-
- __metaclass__ = _LiteralMeta
- __slots__ = ('__values__',)
-
- def __init__(self, values=None, **kwds):
- self.__values__ = values
-
- def __getitem__(self, item):
- cls = type(self)
- if self.__values__ is None:
- if not isinstance(item, tuple):
- item = (item,)
- return cls(values=item,
- _root=True)
- raise TypeError('{} cannot be further subscripted'
- .format(cls.__name__[1:]))
-
- def _eval_type(self, globalns, localns):
- return self
-
- def __repr__(self):
- r = super(_Literal, self).__repr__()
- if self.__values__ is not None:
- r += '[{}]'.format(', '.join(map(_type_repr, self.__values__)))
- return r
-
- def __hash__(self):
- return hash((type(self).__name__, self.__values__))
-
- def __eq__(self, other):
- if not isinstance(other, _Literal):
- return NotImplemented
- if self.__values__ is not None:
- return self.__values__ == other.__values__
- return self is other
-
-
-Literal = _Literal(_root=True)
-
-
-class AnyMeta(TypingMeta):
- """Metaclass for Any."""
-
- def __new__(cls, name, bases, namespace):
- cls.assert_no_subclassing(bases)
- self = super(AnyMeta, cls).__new__(cls, name, bases, namespace)
- return self
-
-
-class _Any(_FinalTypingBase):
- """Special type indicating an unconstrained type.
-
- - Any is compatible with every type.
- - Any assumed to have all methods.
- - All values assumed to be instances of Any.
-
- Note that all the above statements are true from the point of view of
- static type checkers. At runtime, Any should not be used with instance
- or class checks.
- """
- __metaclass__ = AnyMeta
- __slots__ = ()
-
- def __instancecheck__(self, obj):
- raise TypeError("Any cannot be used with isinstance().")
-
- def __subclasscheck__(self, cls):
- raise TypeError("Any cannot be used with issubclass().")
-
-
-Any = _Any(_root=True)
-
-
-class NoReturnMeta(TypingMeta):
- """Metaclass for NoReturn."""
-
- def __new__(cls, name, bases, namespace):
- cls.assert_no_subclassing(bases)
- self = super(NoReturnMeta, cls).__new__(cls, name, bases, namespace)
- return self
-
-
-class _NoReturn(_FinalTypingBase):
- """Special type indicating functions that never return.
- Example::
-
- from typing import NoReturn
-
- def stop() -> NoReturn:
- raise Exception('no way')
-
- This type is invalid in other positions, e.g., ``List[NoReturn]``
- will fail in static type checkers.
- """
- __metaclass__ = NoReturnMeta
- __slots__ = ()
-
- def __instancecheck__(self, obj):
- raise TypeError("NoReturn cannot be used with isinstance().")
-
- def __subclasscheck__(self, cls):
- raise TypeError("NoReturn cannot be used with issubclass().")
-
-
-NoReturn = _NoReturn(_root=True)
-
-
-class TypeVarMeta(TypingMeta):
- def __new__(cls, name, bases, namespace):
- cls.assert_no_subclassing(bases)
- return super(TypeVarMeta, cls).__new__(cls, name, bases, namespace)
-
-
-class TypeVar(_TypingBase):
- """Type variable.
-
- Usage::
-
- T = TypeVar('T') # Can be anything
- A = TypeVar('A', str, bytes) # Must be str or bytes
-
- Type variables exist primarily for the benefit of static type
- checkers. They serve as the parameters for generic types as well
- as for generic function definitions. See class Generic for more
- information on generic types. Generic functions work as follows:
-
- def repeat(x: T, n: int) -> List[T]:
- '''Return a list containing n references to x.'''
- return [x]*n
-
- def longest(x: A, y: A) -> A:
- '''Return the longest of two strings.'''
- return x if len(x) >= len(y) else y
-
- The latter example's signature is essentially the overloading
- of (str, str) -> str and (bytes, bytes) -> bytes. Also note
- that if the arguments are instances of some subclass of str,
- the return type is still plain str.
-
- At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
-
- Type variables defined with covariant=True or contravariant=True
- can be used do declare covariant or contravariant generic types.
- See PEP 484 for more details. By default generic types are invariant
- in all type variables.
-
- Type variables can be introspected. e.g.:
-
- T.__name__ == 'T'
- T.__constraints__ == ()
- T.__covariant__ == False
- T.__contravariant__ = False
- A.__constraints__ == (str, bytes)
- """
-
- __metaclass__ = TypeVarMeta
- __slots__ = ('__name__', '__bound__', '__constraints__',
- '__covariant__', '__contravariant__')
-
- def __init__(self, name, *constraints, **kwargs):
- super(TypeVar, self).__init__(name, *constraints, **kwargs)
- bound = kwargs.get('bound', None)
- covariant = kwargs.get('covariant', False)
- contravariant = kwargs.get('contravariant', False)
- self.__name__ = name
- if covariant and contravariant:
- raise ValueError("Bivariant types are not supported.")
- self.__covariant__ = bool(covariant)
- self.__contravariant__ = bool(contravariant)
- if constraints and bound is not None:
- raise TypeError("Constraints cannot be combined with bound=...")
- if constraints and len(constraints) == 1:
- raise TypeError("A single constraint is not allowed")
- msg = "TypeVar(name, constraint, ...): constraints must be types."
- self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
- if bound:
- self.__bound__ = _type_check(bound, "Bound must be a type.")
- else:
- self.__bound__ = None
-
- def _get_type_vars(self, tvars):
- if self not in tvars:
- tvars.append(self)
-
- def __repr__(self):
- if self.__covariant__:
- prefix = '+'
- elif self.__contravariant__:
- prefix = '-'
- else:
- prefix = '~'
- return prefix + self.__name__
-
- def __instancecheck__(self, instance):
- raise TypeError("Type variables cannot be used with isinstance().")
-
- def __subclasscheck__(self, cls):
- raise TypeError("Type variables cannot be used with issubclass().")
-
-
-# Some unconstrained type variables. These are used by the container types.
-# (These are not for export.)
-T = TypeVar('T') # Any type.
-KT = TypeVar('KT') # Key type.
-VT = TypeVar('VT') # Value type.
-T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
-V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
-VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
-T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
-
-# A useful type variable with constraints. This represents string types.
-# (This one *is* for export!)
-AnyStr = TypeVar('AnyStr', bytes, unicode)
-
-
-def _replace_arg(arg, tvars, args):
- """An internal helper function: replace arg if it is a type variable
- found in tvars with corresponding substitution from args or
- with corresponding substitution sub-tree if arg is a generic type.
- """
-
- if tvars is None:
- tvars = []
- if hasattr(arg, '_subs_tree') and isinstance(arg, (GenericMeta, _TypingBase)):
- return arg._subs_tree(tvars, args)
- if isinstance(arg, TypeVar):
- for i, tvar in enumerate(tvars):
- if arg == tvar:
- return args[i]
- return arg
-
-
-# Special typing constructs Union, Optional, Generic, Callable and Tuple
-# use three special attributes for internal bookkeeping of generic types:
-# * __parameters__ is a tuple of unique free type parameters of a generic
-# type, for example, Dict[T, T].__parameters__ == (T,);
-# * __origin__ keeps a reference to a type that was subscripted,
-# e.g., Union[T, int].__origin__ == Union;
-# * __args__ is a tuple of all arguments used in subscripting,
-# e.g., Dict[T, int].__args__ == (T, int).
-
-
-def _subs_tree(cls, tvars=None, args=None):
- """An internal helper function: calculate substitution tree
- for generic cls after replacing its type parameters with
- substitutions in tvars -> args (if any).
- Repeat the same following __origin__'s.
-
- Return a list of arguments with all possible substitutions
- performed. Arguments that are generic classes themselves are represented
- as tuples (so that no new classes are created by this function).
- For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
- """
-
- if cls.__origin__ is None:
- return cls
- # Make of chain of origins (i.e. cls -> cls.__origin__)
- current = cls.__origin__
- orig_chain = []
- while current.__origin__ is not None:
- orig_chain.append(current)
- current = current.__origin__
- # Replace type variables in __args__ if asked ...
- tree_args = []
- for arg in cls.__args__:
- tree_args.append(_replace_arg(arg, tvars, args))
- # ... then continue replacing down the origin chain.
- for ocls in orig_chain:
- new_tree_args = []
- for arg in ocls.__args__:
- new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
- tree_args = new_tree_args
- return tree_args
-
-
-def _remove_dups_flatten(parameters):
- """An internal helper for Union creation and substitution: flatten Union's
- among parameters, then remove duplicates and strict subclasses.
- """
-
- # Flatten out Union[Union[...], ...].
- params = []
- for p in parameters:
- if isinstance(p, _Union) and p.__origin__ is Union:
- params.extend(p.__args__)
- elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
- params.extend(p[1:])
- else:
- params.append(p)
- # Weed out strict duplicates, preserving the first of each occurrence.
- all_params = set(params)
- if len(all_params) < len(params):
- new_params = []
- for t in params:
- if t in all_params:
- new_params.append(t)
- all_params.remove(t)
- params = new_params
- assert not all_params, all_params
- # Weed out subclasses.
- # E.g. Union[int, Employee, Manager] == Union[int, Employee].
- # If object is present it will be sole survivor among proper classes.
- # Never discard type variables.
- # (In particular, Union[str, AnyStr] != AnyStr.)
- all_params = set(params)
- for t1 in params:
- if not isinstance(t1, type):
- continue
- if any(isinstance(t2, type) and issubclass(t1, t2)
- for t2 in all_params - {t1}
- if not (isinstance(t2, GenericMeta) and
- t2.__origin__ is not None)):
- all_params.remove(t1)
- return tuple(t for t in params if t in all_params)
-
-
-def _check_generic(cls, parameters):
- # Check correct count for parameters of a generic cls (internal helper).
- if not cls.__parameters__:
- raise TypeError("%s is not a generic class" % repr(cls))
- alen = len(parameters)
- elen = len(cls.__parameters__)
- if alen != elen:
- raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
- ("many" if alen > elen else "few", repr(cls), alen, elen))
-
-
-_cleanups = []
-
-
-def _tp_cache(func):
- maxsize = 128
- cache = {}
- _cleanups.append(cache.clear)
-
- @functools.wraps(func)
- def inner(*args):
- key = args
- try:
- return cache[key]
- except TypeError:
- # Assume it's an unhashable argument.
- return func(*args)
- except KeyError:
- value = func(*args)
- if len(cache) >= maxsize:
- # If the cache grows too much, just start over.
- cache.clear()
- cache[key] = value
- return value
-
- return inner
-
-
-class UnionMeta(TypingMeta):
- """Metaclass for Union."""
-
- def __new__(cls, name, bases, namespace):
- cls.assert_no_subclassing(bases)
- return super(UnionMeta, cls).__new__(cls, name, bases, namespace)
-
-
-class _Union(_FinalTypingBase):
- """Union type; Union[X, Y] means either X or Y.
-
- To define a union, use e.g. Union[int, str]. Details:
-
- - The arguments must be types and there must be at least one.
-
- - None as an argument is a special case and is replaced by
- type(None).
-
- - Unions of unions are flattened, e.g.::
-
- Union[Union[int, str], float] == Union[int, str, float]
-
- - Unions of a single argument vanish, e.g.::
-
- Union[int] == int # The constructor actually returns int
-
- - Redundant arguments are skipped, e.g.::
-
- Union[int, str, int] == Union[int, str]
-
- - When comparing unions, the argument order is ignored, e.g.::
-
- Union[int, str] == Union[str, int]
-
- - When two arguments have a subclass relationship, the least
- derived argument is kept, e.g.::
-
- class Employee: pass
- class Manager(Employee): pass
- Union[int, Employee, Manager] == Union[int, Employee]
- Union[Manager, int, Employee] == Union[int, Employee]
- Union[Employee, Manager] == Employee
-
- - Similar for object::
-
- Union[int, object] == object
-
- - You cannot subclass or instantiate a union.
-
- - You can use Optional[X] as a shorthand for Union[X, None].
- """
-
- __metaclass__ = UnionMeta
- __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
-
- def __new__(cls, parameters=None, origin=None, *args, **kwds):
- self = super(_Union, cls).__new__(cls, parameters, origin, *args, **kwds)
- if origin is None:
- self.__parameters__ = None
- self.__args__ = None
- self.__origin__ = None
- self.__tree_hash__ = hash(frozenset(('Union',)))
- return self
- if not isinstance(parameters, tuple):
- raise TypeError("Expected parameters=<tuple>")
- if origin is Union:
- parameters = _remove_dups_flatten(parameters)
- # It's not a union if there's only one type left.
- if len(parameters) == 1:
- return parameters[0]
- self.__parameters__ = _type_vars(parameters)
- self.__args__ = parameters
- self.__origin__ = origin
- # Pre-calculate the __hash__ on instantiation.
- # This improves speed for complex substitutions.
- subs_tree = self._subs_tree()
- if isinstance(subs_tree, tuple):
- self.__tree_hash__ = hash(frozenset(subs_tree))
- else:
- self.__tree_hash__ = hash(subs_tree)
- return self
-
- def _eval_type(self, globalns, localns):
- if self.__args__ is None:
- return self
- ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
- ev_origin = _eval_type(self.__origin__, globalns, localns)
- if ev_args == self.__args__ and ev_origin == self.__origin__:
- # Everything is already evaluated.
- return self
- return self.__class__(ev_args, ev_origin, _root=True)
-
- def _get_type_vars(self, tvars):
- if self.__origin__ and self.__parameters__:
- _get_type_vars(self.__parameters__, tvars)
-
- def __repr__(self):
- if self.__origin__ is None:
- return super(_Union, self).__repr__()
- tree = self._subs_tree()
- if not isinstance(tree, tuple):
- return repr(tree)
- return tree[0]._tree_repr(tree)
-
- def _tree_repr(self, tree):
- arg_list = []
- for arg in tree[1:]:
- if not isinstance(arg, tuple):
- arg_list.append(_type_repr(arg))
- else:
- arg_list.append(arg[0]._tree_repr(arg))
- return super(_Union, self).__repr__() + '[%s]' % ', '.join(arg_list)
-
- @_tp_cache
- def __getitem__(self, parameters):
- if parameters == ():
- raise TypeError("Cannot take a Union of no types.")
- if not isinstance(parameters, tuple):
- parameters = (parameters,)
- if self.__origin__ is None:
- msg = "Union[arg, ...]: each arg must be a type."
- else:
- msg = "Parameters to generic types must be types."
- parameters = tuple(_type_check(p, msg) for p in parameters)
- if self is not Union:
- _check_generic(self, parameters)
- return self.__class__(parameters, origin=self, _root=True)
-
- def _subs_tree(self, tvars=None, args=None):
- if self is Union:
- return Union # Nothing to substitute
- tree_args = _subs_tree(self, tvars, args)
- tree_args = _remove_dups_flatten(tree_args)
- if len(tree_args) == 1:
- return tree_args[0] # Union of a single type is that type
- return (Union,) + tree_args
-
- def __eq__(self, other):
- if isinstance(other, _Union):
- return self.__tree_hash__ == other.__tree_hash__
- elif self is not Union:
- return self._subs_tree() == other
- else:
- return self is other
-
- def __hash__(self):
- return self.__tree_hash__
-
- def __instancecheck__(self, obj):
- raise TypeError("Unions cannot be used with isinstance().")
-
- def __subclasscheck__(self, cls):
- raise TypeError("Unions cannot be used with issubclass().")
-
-
-Union = _Union(_root=True)
-
-
-class OptionalMeta(TypingMeta):
- """Metaclass for Optional."""
-
- def __new__(cls, name, bases, namespace):
- cls.assert_no_subclassing(bases)
- return super(OptionalMeta, cls).__new__(cls, name, bases, namespace)
-
-
-class _Optional(_FinalTypingBase):
- """Optional type.
-
- Optional[X] is equivalent to Union[X, None].
- """
-
- __metaclass__ = OptionalMeta
- __slots__ = ()
-
- @_tp_cache
- def __getitem__(self, arg):
- arg = _type_check(arg, "Optional[t] requires a single type.")
- return Union[arg, type(None)]
-
-
-Optional = _Optional(_root=True)
-
-
-def _next_in_mro(cls):
- """Helper for Generic.__new__.
-
- Returns the class after the last occurrence of Generic or
- Generic[...] in cls.__mro__.
- """
- next_in_mro = object
- # Look for the last occurrence of Generic or Generic[...].
- for i, c in enumerate(cls.__mro__[:-1]):
- if isinstance(c, GenericMeta) and c._gorg is Generic:
- next_in_mro = cls.__mro__[i + 1]
- return next_in_mro
-
-
-def _make_subclasshook(cls):
- """Construct a __subclasshook__ callable that incorporates
- the associated __extra__ class in subclass checks performed
- against cls.
- """
- if isinstance(cls.__extra__, abc.ABCMeta):
- # The logic mirrors that of ABCMeta.__subclasscheck__.
- # Registered classes need not be checked here because
- # cls and its extra share the same _abc_registry.
- def __extrahook__(cls, subclass):
- res = cls.__extra__.__subclasshook__(subclass)
- if res is not NotImplemented:
- return res
- if cls.__extra__ in getattr(subclass, '__mro__', ()):
- return True
- for scls in cls.__extra__.__subclasses__():
- if isinstance(scls, GenericMeta):
- continue
- if issubclass(subclass, scls):
- return True
- return NotImplemented
- else:
- # For non-ABC extras we'll just call issubclass().
- def __extrahook__(cls, subclass):
- if cls.__extra__ and issubclass(subclass, cls.__extra__):
- return True
- return NotImplemented
- return classmethod(__extrahook__)
-
-
-class GenericMeta(TypingMeta, abc.ABCMeta):
- """Metaclass for generic types.
-
- This is a metaclass for typing.Generic and generic ABCs defined in
- typing module. User defined subclasses of GenericMeta can override
- __new__ and invoke super().__new__. Note that GenericMeta.__new__
- has strict rules on what is allowed in its bases argument:
- * plain Generic is disallowed in bases;
- * Generic[...] should appear in bases at most once;
- * if Generic[...] is present, then it should list all type variables
- that appear in other bases.
- In addition, type of all generic bases is erased, e.g., C[int] is
- stripped to plain C.
- """
-
- def __new__(cls, name, bases, namespace,
- tvars=None, args=None, origin=None, extra=None, orig_bases=None):
- """Create a new generic class. GenericMeta.__new__ accepts
- keyword arguments that are used for internal bookkeeping, therefore
- an override should pass unused keyword arguments to super().
- """
- if tvars is not None:
- # Called from __getitem__() below.
- assert origin is not None
- assert all(isinstance(t, TypeVar) for t in tvars), tvars
- else:
- # Called from class statement.
- assert tvars is None, tvars
- assert args is None, args
- assert origin is None, origin
-
- # Get the full set of tvars from the bases.
- tvars = _type_vars(bases)
- # Look for Generic[T1, ..., Tn].
- # If found, tvars must be a subset of it.
- # If not found, tvars is it.
- # Also check for and reject plain Generic,
- # and reject multiple Generic[...].
- gvars = None
- for base in bases:
- if base is Generic:
- raise TypeError("Cannot inherit from plain Generic")
- if (isinstance(base, GenericMeta) and
- base.__origin__ in (Generic, Protocol)):
- if gvars is not None:
- raise TypeError(
- "Cannot inherit from Generic[...] or"
- " Protocol[...] multiple times.")
- gvars = base.__parameters__
- if gvars is None:
- gvars = tvars
- else:
- tvarset = set(tvars)
- gvarset = set(gvars)
- if not tvarset <= gvarset:
- raise TypeError(
- "Some type variables (%s) "
- "are not listed in %s[%s]" %
- (", ".join(str(t) for t in tvars if t not in gvarset),
- "Generic" if any(b.__origin__ is Generic
- for b in bases) else "Protocol",
- ", ".join(str(g) for g in gvars)))
- tvars = gvars
-
- initial_bases = bases
- if extra is None:
- extra = namespace.get('__extra__')
- if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
- bases = (extra,) + bases
- bases = tuple(b._gorg if isinstance(b, GenericMeta) else b for b in bases)
-
- # remove bare Generic from bases if there are other generic bases
- if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
- bases = tuple(b for b in bases if b is not Generic)
- namespace.update({'__origin__': origin, '__extra__': extra})
- self = super(GenericMeta, cls).__new__(cls, name, bases, namespace)
- super(GenericMeta, self).__setattr__('_gorg',
- self if not origin else origin._gorg)
-
- self.__parameters__ = tvars
- # Be prepared that GenericMeta will be subclassed by TupleMeta
- # and CallableMeta, those two allow ..., (), or [] in __args___.
- self.__args__ = tuple(Ellipsis if a is _TypingEllipsis else
- () if a is _TypingEmpty else
- a for a in args) if args else None
- # Speed hack (https://github.com/python/typing/issues/196).
- self.__next_in_mro__ = _next_in_mro(self)
- # Preserve base classes on subclassing (__bases__ are type erased now).
- if orig_bases is None:
- self.__orig_bases__ = initial_bases
-
- # This allows unparameterized generic collections to be used
- # with issubclass() and isinstance() in the same way as their
- # collections.abc counterparts (e.g., isinstance([], Iterable)).
- if (
- '__subclasshook__' not in namespace and extra or
- # allow overriding
- getattr(self.__subclasshook__, '__name__', '') == '__extrahook__'
- ):
- self.__subclasshook__ = _make_subclasshook(self)
-
- if origin and hasattr(origin, '__qualname__'): # Fix for Python 3.2.
- self.__qualname__ = origin.__qualname__
- self.__tree_hash__ = (hash(self._subs_tree()) if origin else
- super(GenericMeta, self).__hash__())
- return self
-
- def __init__(self, *args, **kwargs):
- super(GenericMeta, self).__init__(*args, **kwargs)
- if isinstance(self.__extra__, abc.ABCMeta):
- self._abc_registry = self.__extra__._abc_registry
- self._abc_cache = self.__extra__._abc_cache
- elif self.__origin__ is not None:
- self._abc_registry = self.__origin__._abc_registry
- self._abc_cache = self.__origin__._abc_cache
-
- # _abc_negative_cache and _abc_negative_cache_version
- # realized as descriptors, since GenClass[t1, t2, ...] always
- # share subclass info with GenClass.
- # This is an important memory optimization.
- @property
- def _abc_negative_cache(self):
- if isinstance(self.__extra__, abc.ABCMeta):
- return self.__extra__._abc_negative_cache
- return self._gorg._abc_generic_negative_cache
-
- @_abc_negative_cache.setter
- def _abc_negative_cache(self, value):
- if self.__origin__ is None:
- if isinstance(self.__extra__, abc.ABCMeta):
- self.__extra__._abc_negative_cache = value
- else:
- self._abc_generic_negative_cache = value
-
- @property
- def _abc_negative_cache_version(self):
- if isinstance(self.__extra__, abc.ABCMeta):
- return self.__extra__._abc_negative_cache_version
- return self._gorg._abc_generic_negative_cache_version
-
- @_abc_negative_cache_version.setter
- def _abc_negative_cache_version(self, value):
- if self.__origin__ is None:
- if isinstance(self.__extra__, abc.ABCMeta):
- self.__extra__._abc_negative_cache_version = value
- else:
- self._abc_generic_negative_cache_version = value
-
- def _get_type_vars(self, tvars):
- if self.__origin__ and self.__parameters__:
- _get_type_vars(self.__parameters__, tvars)
-
- def _eval_type(self, globalns, localns):
- ev_origin = (self.__origin__._eval_type(globalns, localns)
- if self.__origin__ else None)
- ev_args = tuple(_eval_type(a, globalns, localns) for a
- in self.__args__) if self.__args__ else None
- if ev_origin == self.__origin__ and ev_args == self.__args__:
- return self
- return self.__class__(self.__name__,
- self.__bases__,
- dict(self.__dict__),
- tvars=_type_vars(ev_args) if ev_args else None,
- args=ev_args,
- origin=ev_origin,
- extra=self.__extra__,
- orig_bases=self.__orig_bases__)
-
- def __repr__(self):
- if self.__origin__ is None:
- return super(GenericMeta, self).__repr__()
- return self._tree_repr(self._subs_tree())
-
- def _tree_repr(self, tree):
- arg_list = []
- for arg in tree[1:]:
- if arg == ():
- arg_list.append('()')
- elif not isinstance(arg, tuple):
- arg_list.append(_type_repr(arg))
- else:
- arg_list.append(arg[0]._tree_repr(arg))
- return super(GenericMeta, self).__repr__() + '[%s]' % ', '.join(arg_list)
-
- def _subs_tree(self, tvars=None, args=None):
- if self.__origin__ is None:
- return self
- tree_args = _subs_tree(self, tvars, args)
- return (self._gorg,) + tuple(tree_args)
-
- def __eq__(self, other):
- if not isinstance(other, GenericMeta):
- return NotImplemented
- if self.__origin__ is None or other.__origin__ is None:
- return self is other
- return self.__tree_hash__ == other.__tree_hash__
-
- def __hash__(self):
- return self.__tree_hash__
-
- @_tp_cache
- def __getitem__(self, params):
- if not isinstance(params, tuple):
- params = (params,)
- if not params and self._gorg is not Tuple:
- raise TypeError(
- "Parameter list to %s[...] cannot be empty" % _qualname(self))
- msg = "Parameters to generic types must be types."
- params = tuple(_type_check(p, msg) for p in params)
- if self in (Generic, Protocol):
- # Generic can only be subscripted with unique type variables.
- if not all(isinstance(p, TypeVar) for p in params):
- raise TypeError(
- "Parameters to %s[...] must all be type variables" % self.__name__)
- if len(set(params)) != len(params):
- raise TypeError(
- "Parameters to %s[...] must all be unique" % self.__name__)
- tvars = params
- args = params
- elif self in (Tuple, Callable):
- tvars = _type_vars(params)
- args = params
- elif self.__origin__ in (Generic, Protocol):
- # Can't subscript Generic[...] or Protocol[...].
- raise TypeError("Cannot subscript already-subscripted %s" %
- repr(self))
- else:
- # Subscripting a regular Generic subclass.
- _check_generic(self, params)
- tvars = _type_vars(params)
- args = params
-
- prepend = (self,) if self.__origin__ is None else ()
- return self.__class__(self.__name__,
- prepend + self.__bases__,
- dict(self.__dict__),
- tvars=tvars,
- args=args,
- origin=self,
- extra=self.__extra__,
- orig_bases=self.__orig_bases__)
-
- def __subclasscheck__(self, cls):
- if self.__origin__ is not None:
- # This should only be modules within the standard
- # library. singledispatch is the only exception, because
- # it's a Python 2 backport of functools.singledispatch.
- if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools',
- 'singledispatch']:
- raise TypeError("Parameterized generics cannot be used with class "
- "or instance checks")
- return False
- if self is Generic:
- raise TypeError("Class %r cannot be used with class "
- "or instance checks" % self)
- return super(GenericMeta, self).__subclasscheck__(cls)
-
- def __instancecheck__(self, instance):
- # Since we extend ABC.__subclasscheck__ and
- # ABC.__instancecheck__ inlines the cache checking done by the
- # latter, we must extend __instancecheck__ too. For simplicity
- # we just skip the cache check -- instance checks for generic
- # classes are supposed to be rare anyways.
- if hasattr(instance, "__class__"):
- return issubclass(instance.__class__, self)
- return False
-
- def __setattr__(self, attr, value):
- # We consider all the subscripted genrics as proxies for original class
- if (
- attr.startswith('__') and attr.endswith('__') or
- attr.startswith('_abc_')
- ):
- super(GenericMeta, self).__setattr__(attr, value)
- else:
- super(GenericMeta, self._gorg).__setattr__(attr, value)
-
-
-def _copy_generic(self):
- """Hack to work around https://bugs.python.org/issue11480 on Python 2"""
- return self.__class__(self.__name__, self.__bases__, dict(self.__dict__),
- self.__parameters__, self.__args__, self.__origin__,
- self.__extra__, self.__orig_bases__)
-
-
-copy._copy_dispatch[GenericMeta] = _copy_generic
-
-
-# Prevent checks for Generic to crash when defining Generic.
-Generic = None
-
-
-def _generic_new(base_cls, cls, *args, **kwds):
- # Assure type is erased on instantiation,
- # but attempt to store it in __orig_class__
- if cls.__origin__ is None:
- if (base_cls.__new__ is object.__new__ and
- cls.__init__ is not object.__init__):
- return base_cls.__new__(cls)
- else:
- return base_cls.__new__(cls, *args, **kwds)
- else:
- origin = cls._gorg
- if (base_cls.__new__ is object.__new__ and
- cls.__init__ is not object.__init__):
- obj = base_cls.__new__(origin)
- else:
- obj = base_cls.__new__(origin, *args, **kwds)
- try:
- obj.__orig_class__ = cls
- except AttributeError:
- pass
- obj.__init__(*args, **kwds)
- return obj
-
-
-class Generic(object):
- """Abstract base class for generic types.
-
- A generic type is typically declared by inheriting from
- this class parameterized with one or more type variables.
- For example, a generic mapping type might be defined as::
-
- class Mapping(Generic[KT, VT]):
- def __getitem__(self, key: KT) -> VT:
- ...
- # Etc.
-
- This class can then be used as follows::
-
- def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
- try:
- return mapping[key]
- except KeyError:
- return default
- """
-
- __metaclass__ = GenericMeta
- __slots__ = ()
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Generic:
- raise TypeError("Type Generic cannot be instantiated; "
- "it can be used only as a base class")
- return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
-
-
-class _TypingEmpty(object):
- """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
- to allow empty list/tuple in specific places, without allowing them
- to sneak in where prohibited.
- """
-
-
-class _TypingEllipsis(object):
- """Internal placeholder for ... (ellipsis)."""
-
-
-class TupleMeta(GenericMeta):
- """Metaclass for Tuple (internal)."""
-
- @_tp_cache
- def __getitem__(self, parameters):
- if self.__origin__ is not None or self._gorg is not Tuple:
- # Normal generic rules apply if this is not the first subscription
- # or a subscription of a subclass.
- return super(TupleMeta, self).__getitem__(parameters)
- if parameters == ():
- return super(TupleMeta, self).__getitem__((_TypingEmpty,))
- if not isinstance(parameters, tuple):
- parameters = (parameters,)
- if len(parameters) == 2 and parameters[1] is Ellipsis:
- msg = "Tuple[t, ...]: t must be a type."
- p = _type_check(parameters[0], msg)
- return super(TupleMeta, self).__getitem__((p, _TypingEllipsis))
- msg = "Tuple[t0, t1, ...]: each t must be a type."
- parameters = tuple(_type_check(p, msg) for p in parameters)
- return super(TupleMeta, self).__getitem__(parameters)
-
- def __instancecheck__(self, obj):
- if self.__args__ is None:
- return isinstance(obj, tuple)
- raise TypeError("Parameterized Tuple cannot be used "
- "with isinstance().")
-
- def __subclasscheck__(self, cls):
- if self.__args__ is None:
- return issubclass(cls, tuple)
- raise TypeError("Parameterized Tuple cannot be used "
- "with issubclass().")
-
-
-copy._copy_dispatch[TupleMeta] = _copy_generic
-
-
-class Tuple(tuple):
- """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
-
- Example: Tuple[T1, T2] is a tuple of two elements corresponding
- to type variables T1 and T2. Tuple[int, float, str] is a tuple
- of an int, a float and a string.
-
- To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
- """
-
- __metaclass__ = TupleMeta
- __extra__ = tuple
- __slots__ = ()
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Tuple:
- raise TypeError("Type Tuple cannot be instantiated; "
- "use tuple() instead")
- return _generic_new(tuple, cls, *args, **kwds)
-
-
-class CallableMeta(GenericMeta):
- """ Metaclass for Callable."""
-
- def __repr__(self):
- if self.__origin__ is None:
- return super(CallableMeta, self).__repr__()
- return self._tree_repr(self._subs_tree())
-
- def _tree_repr(self, tree):
- if self._gorg is not Callable:
- return super(CallableMeta, self)._tree_repr(tree)
- # For actual Callable (not its subclass) we override
- # super(CallableMeta, self)._tree_repr() for nice formatting.
- arg_list = []
- for arg in tree[1:]:
- if not isinstance(arg, tuple):
- arg_list.append(_type_repr(arg))
- else:
- arg_list.append(arg[0]._tree_repr(arg))
- if arg_list[0] == '...':
- return repr(tree[0]) + '[..., %s]' % arg_list[1]
- return (repr(tree[0]) +
- '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
-
- def __getitem__(self, parameters):
- """A thin wrapper around __getitem_inner__ to provide the latter
- with hashable arguments to improve speed.
- """
-
- if self.__origin__ is not None or self._gorg is not Callable:
- return super(CallableMeta, self).__getitem__(parameters)
- if not isinstance(parameters, tuple) or len(parameters) != 2:
- raise TypeError("Callable must be used as "
- "Callable[[arg, ...], result].")
- args, result = parameters
- if args is Ellipsis:
- parameters = (Ellipsis, result)
- else:
- if not isinstance(args, list):
- raise TypeError("Callable[args, result]: args must be a list."
- " Got %.100r." % (args,))
- parameters = (tuple(args), result)
- return self.__getitem_inner__(parameters)
-
- @_tp_cache
- def __getitem_inner__(self, parameters):
- args, result = parameters
- msg = "Callable[args, result]: result must be a type."
- result = _type_check(result, msg)
- if args is Ellipsis:
- return super(CallableMeta, self).__getitem__((_TypingEllipsis, result))
- msg = "Callable[[arg, ...], result]: each arg must be a type."
- args = tuple(_type_check(arg, msg) for arg in args)
- parameters = args + (result,)
- return super(CallableMeta, self).__getitem__(parameters)
-
-
-copy._copy_dispatch[CallableMeta] = _copy_generic
-
-
-class Callable(object):
- """Callable type; Callable[[int], str] is a function of (int) -> str.
-
- The subscription syntax must always be used with exactly two
- values: the argument list and the return type. The argument list
- must be a list of types or ellipsis; the return type must be a single type.
-
- There is no syntax to indicate optional or keyword arguments,
- such function types are rarely used as callback types.
- """
-
- __metaclass__ = CallableMeta
- __extra__ = collections_abc.Callable
- __slots__ = ()
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Callable:
- raise TypeError("Type Callable cannot be instantiated; "
- "use a non-abstract subclass instead")
- return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
-
-
-def cast(typ, val):
- """Cast a value to a type.
-
- This returns the value unchanged. To the type checker this
- signals that the return value has the designated type, but at
- runtime we intentionally don't check anything (we want this
- to be as fast as possible).
- """
- return val
-
-
-def _get_defaults(func):
- """Internal helper to extract the default arguments, by name."""
- code = func.__code__
- pos_count = code.co_argcount
- arg_names = code.co_varnames
- arg_names = arg_names[:pos_count]
- defaults = func.__defaults__ or ()
- kwdefaults = func.__kwdefaults__
- res = dict(kwdefaults) if kwdefaults else {}
- pos_offset = pos_count - len(defaults)
- for name, value in zip(arg_names[pos_offset:], defaults):
- assert name not in res
- res[name] = value
- return res
-
-
-def get_type_hints(obj, globalns=None, localns=None):
- """In Python 2 this is not supported and always returns None."""
- return None
-
-
-def no_type_check(arg):
- """Decorator to indicate that annotations are not type hints.
-
- The argument must be a class or function; if it is a class, it
- applies recursively to all methods and classes defined in that class
- (but not to methods defined in its superclasses or subclasses).
-
- This mutates the function(s) or class(es) in place.
- """
- if isinstance(arg, type):
- arg_attrs = arg.__dict__.copy()
- for attr, val in arg.__dict__.items():
- if val in arg.__bases__ + (arg,):
- arg_attrs.pop(attr)
- for obj in arg_attrs.values():
- if isinstance(obj, types.FunctionType):
- obj.__no_type_check__ = True
- if isinstance(obj, type):
- no_type_check(obj)
- try:
- arg.__no_type_check__ = True
- except TypeError: # built-in classes
- pass
- return arg
-
-
-def no_type_check_decorator(decorator):
- """Decorator to give another decorator the @no_type_check effect.
-
- This wraps the decorator with something that wraps the decorated
- function in @no_type_check.
- """
-
- @functools.wraps(decorator)
- def wrapped_decorator(*args, **kwds):
- func = decorator(*args, **kwds)
- func = no_type_check(func)
- return func
-
- return wrapped_decorator
-
-
-def _overload_dummy(*args, **kwds):
- """Helper for @overload to raise when called."""
- raise NotImplementedError(
- "You should not call an overloaded function. "
- "A series of @overload-decorated functions "
- "outside a stub module should always be followed "
- "by an implementation that is not @overload-ed.")
-
-
-def overload(func):
- """Decorator for overloaded functions/methods.
-
- In a stub file, place two or more stub definitions for the same
- function in a row, each decorated with @overload. For example:
-
- @overload
- def utf8(value: None) -> None: ...
- @overload
- def utf8(value: bytes) -> bytes: ...
- @overload
- def utf8(value: str) -> bytes: ...
-
- In a non-stub file (i.e. a regular .py file), do the same but
- follow it with an implementation. The implementation should *not*
- be decorated with @overload. For example:
-
- @overload
- def utf8(value: None) -> None: ...
- @overload
- def utf8(value: bytes) -> bytes: ...
- @overload
- def utf8(value: str) -> bytes: ...
- def utf8(value):
- # implementation goes here
- """
- return _overload_dummy
-
-
-_PROTO_WHITELIST = ['Callable', 'Iterable', 'Iterator',
- 'Hashable', 'Sized', 'Container', 'Collection',
- 'Reversible', 'ContextManager']
-
-
-class _ProtocolMeta(GenericMeta):
- """Internal metaclass for Protocol.
-
- This exists so Protocol classes can be generic without deriving
- from Generic.
- """
- def __init__(cls, *args, **kwargs):
- super(_ProtocolMeta, cls).__init__(*args, **kwargs)
- if not cls.__dict__.get('_is_protocol', None):
- cls._is_protocol = any(b is Protocol or
- isinstance(b, _ProtocolMeta) and
- b.__origin__ is Protocol
- for b in cls.__bases__)
- if cls._is_protocol:
- for base in cls.__mro__[1:]:
- if not (base in (object, Generic) or
- base.__module__ == '_abcoll' and
- base.__name__ in _PROTO_WHITELIST or
- isinstance(base, TypingMeta) and base._is_protocol or
- isinstance(base, GenericMeta) and base.__origin__ is Generic):
- raise TypeError('Protocols can only inherit from other protocols,'
- ' got %r' % base)
- cls._callable_members_only = all(callable(getattr(cls, attr))
- for attr in cls._get_protocol_attrs())
-
- def _no_init(self, *args, **kwargs):
- if type(self)._is_protocol:
- raise TypeError('Protocols cannot be instantiated')
- cls.__init__ = _no_init
-
- def _proto_hook(cls, other):
- if not cls.__dict__.get('_is_protocol', None):
- return NotImplemented
- if not isinstance(other, type):
- # Similar error as for issubclass(1, int)
- # (also not a chance for old-style classes)
- raise TypeError('issubclass() arg 1 must be a new-style class')
- for attr in cls._get_protocol_attrs():
- for base in other.__mro__:
- if attr in base.__dict__:
- if base.__dict__[attr] is None:
- return NotImplemented
- break
- else:
- return NotImplemented
- return True
- if '__subclasshook__' not in cls.__dict__:
- cls.__subclasshook__ = classmethod(_proto_hook)
-
- def __instancecheck__(self, instance):
- # We need this method for situations where attributes are assigned in __init__
- if isinstance(instance, type):
- # This looks like a fundamental limitation of Python 2.
- # It cannot support runtime protocol metaclasses, On Python 2 classes
- # cannot be correctly inspected as instances of protocols.
- return False
- if ((not getattr(self, '_is_protocol', False) or
- self._callable_members_only) and
- issubclass(instance.__class__, self)):
- return True
- if self._is_protocol:
- if all(hasattr(instance, attr) and
- (not callable(getattr(self, attr)) or
- getattr(instance, attr) is not None)
- for attr in self._get_protocol_attrs()):
- return True
- return super(GenericMeta, self).__instancecheck__(instance)
-
- def __subclasscheck__(self, cls):
- if (self.__dict__.get('_is_protocol', None) and
- not self.__dict__.get('_is_runtime_protocol', None)):
- if (sys._getframe(1).f_globals['__name__'] in ['abc', 'functools'] or
- # This is needed because we remove subclasses from unions on Python 2.
- sys._getframe(2).f_globals['__name__'] == 'typing'):
- return False
- raise TypeError("Instance and class checks can only be used with"
- " @runtime_checkable protocols")
- if (self.__dict__.get('_is_runtime_protocol', None) and
- not self._callable_members_only):
- if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools']:
- return super(GenericMeta, self).__subclasscheck__(cls)
- raise TypeError("Protocols with non-method members"
- " don't support issubclass()")
- return super(_ProtocolMeta, self).__subclasscheck__(cls)
-
- def _get_protocol_attrs(self):
- attrs = set()
- for base in self.__mro__[:-1]: # without object
- if base.__name__ in ('Protocol', 'Generic'):
- continue
- annotations = getattr(base, '__annotations__', {})
- for attr in list(base.__dict__.keys()) + list(annotations.keys()):
- if (not attr.startswith('_abc_') and attr not in (
- '__abstractmethods__', '__annotations__', '__weakref__',
- '_is_protocol', '_is_runtime_protocol', '__dict__',
- '__args__', '__slots__', '_get_protocol_attrs',
- '__next_in_mro__', '__parameters__', '__origin__',
- '__orig_bases__', '__extra__', '__tree_hash__',
- '__doc__', '__subclasshook__', '__init__', '__new__',
- '__module__', '_MutableMapping__marker',
- '__metaclass__', '_gorg', '_callable_members_only')):
- attrs.add(attr)
- return attrs
-
-
-class Protocol(object):
- """Base class for protocol classes. Protocol classes are defined as::
-
- class Proto(Protocol):
- def meth(self):
- # type: () -> int
- pass
-
- Such classes are primarily used with static type checkers that recognize
- structural subtyping (static duck-typing), for example::
-
- class C:
- def meth(self):
- # type: () -> int
- return 0
-
- def func(x):
- # type: (Proto) -> int
- return x.meth()
-
- func(C()) # Passes static type check
-
- See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable
- act as simple-minded runtime protocols that checks only the presence of
- given attributes, ignoring their type signatures.
-
- Protocol classes can be generic, they are defined as::
-
- class GenProto(Protocol[T]):
- def meth(self):
- # type: () -> T
- pass
- """
-
- __metaclass__ = _ProtocolMeta
- __slots__ = ()
- _is_protocol = True
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Protocol:
- raise TypeError("Type Protocol cannot be instantiated; "
- "it can be used only as a base class")
- return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
-
-
-def runtime_checkable(cls):
- """Mark a protocol class as a runtime protocol, so that it
- can be used with isinstance() and issubclass(). Raise TypeError
- if applied to a non-protocol class.
-
- This allows a simple-minded structural check very similar to the
- one-offs in collections.abc such as Hashable.
- """
- if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
- raise TypeError('@runtime_checkable can be only applied to protocol classes,'
- ' got %r' % cls)
- cls._is_runtime_protocol = True
- return cls
-
-
-# Various ABCs mimicking those in collections.abc.
-# A few are simply re-exported for completeness.
-
-Hashable = collections_abc.Hashable # Not generic.
-
-
-class Iterable(Generic[T_co]):
- __slots__ = ()
- __extra__ = collections_abc.Iterable
-
-
-class Iterator(Iterable[T_co]):
- __slots__ = ()
- __extra__ = collections_abc.Iterator
-
-
-@runtime_checkable
-class SupportsInt(Protocol):
- __slots__ = ()
-
- @abstractmethod
- def __int__(self):
- pass
-
-
-@runtime_checkable
-class SupportsFloat(Protocol):
- __slots__ = ()
-
- @abstractmethod
- def __float__(self):
- pass
-
-
-@runtime_checkable
-class SupportsComplex(Protocol):
- __slots__ = ()
-
- @abstractmethod
- def __complex__(self):
- pass
-
-
-@runtime_checkable
-class SupportsIndex(Protocol):
- __slots__ = ()
-
- @abstractmethod
- def __index__(self):
- pass
-
-
-@runtime_checkable
-class SupportsAbs(Protocol[T_co]):
- __slots__ = ()
-
- @abstractmethod
- def __abs__(self):
- pass
-
-
-if hasattr(collections_abc, 'Reversible'):
- class Reversible(Iterable[T_co]):
- __slots__ = ()
- __extra__ = collections_abc.Reversible
-else:
- @runtime_checkable
- class Reversible(Protocol[T_co]):
- __slots__ = ()
-
- @abstractmethod
- def __reversed__(self):
- pass
-
-
-Sized = collections_abc.Sized # Not generic.
-
-
-class Container(Generic[T_co]):
- __slots__ = ()
- __extra__ = collections_abc.Container
-
-
-# Callable was defined earlier.
-
-
-class AbstractSet(Sized, Iterable[T_co], Container[T_co]):
- __slots__ = ()
- __extra__ = collections_abc.Set
-
-
-class MutableSet(AbstractSet[T]):
- __slots__ = ()
- __extra__ = collections_abc.MutableSet
-
-
-# NOTE: It is only covariant in the value type.
-class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co]):
- __slots__ = ()
- __extra__ = collections_abc.Mapping
-
-
-class MutableMapping(Mapping[KT, VT]):
- __slots__ = ()
- __extra__ = collections_abc.MutableMapping
-
-
-if hasattr(collections_abc, 'Reversible'):
- class Sequence(Sized, Reversible[T_co], Container[T_co]):
- __slots__ = ()
- __extra__ = collections_abc.Sequence
-else:
- class Sequence(Sized, Iterable[T_co], Container[T_co]):
- __slots__ = ()
- __extra__ = collections_abc.Sequence
-
-
-class MutableSequence(Sequence[T]):
- __slots__ = ()
- __extra__ = collections_abc.MutableSequence
-
-
-class ByteString(Sequence[int]):
- pass
-
-
-ByteString.register(str)
-ByteString.register(bytearray)
-
-
-class List(list, MutableSequence[T]):
- __slots__ = ()
- __extra__ = list
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is List:
- raise TypeError("Type List cannot be instantiated; "
- "use list() instead")
- return _generic_new(list, cls, *args, **kwds)
-
-
-class Deque(collections.deque, MutableSequence[T]):
- __slots__ = ()
- __extra__ = collections.deque
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Deque:
- return collections.deque(*args, **kwds)
- return _generic_new(collections.deque, cls, *args, **kwds)
-
-
-class Set(set, MutableSet[T]):
- __slots__ = ()
- __extra__ = set
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Set:
- raise TypeError("Type Set cannot be instantiated; "
- "use set() instead")
- return _generic_new(set, cls, *args, **kwds)
-
-
-class FrozenSet(frozenset, AbstractSet[T_co]):
- __slots__ = ()
- __extra__ = frozenset
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is FrozenSet:
- raise TypeError("Type FrozenSet cannot be instantiated; "
- "use frozenset() instead")
- return _generic_new(frozenset, cls, *args, **kwds)
-
-
-class MappingView(Sized, Iterable[T_co]):
- __slots__ = ()
- __extra__ = collections_abc.MappingView
-
-
-class KeysView(MappingView[KT], AbstractSet[KT]):
- __slots__ = ()
- __extra__ = collections_abc.KeysView
-
-
-class ItemsView(MappingView[Tuple[KT, VT_co]],
- AbstractSet[Tuple[KT, VT_co]],
- Generic[KT, VT_co]):
- __slots__ = ()
- __extra__ = collections_abc.ItemsView
-
-
-class ValuesView(MappingView[VT_co]):
- __slots__ = ()
- __extra__ = collections_abc.ValuesView
-
-
-class ContextManager(Generic[T_co]):
- __slots__ = ()
-
- def __enter__(self):
- return self
-
- @abc.abstractmethod
- def __exit__(self, exc_type, exc_value, traceback):
- return None
-
- @classmethod
- def __subclasshook__(cls, C):
- if cls is ContextManager:
- # In Python 3.6+, it is possible to set a method to None to
- # explicitly indicate that the class does not implement an ABC
- # (https://bugs.python.org/issue25958), but we do not support
- # that pattern here because this fallback class is only used
- # in Python 3.5 and earlier.
- if (any("__enter__" in B.__dict__ for B in C.__mro__) and
- any("__exit__" in B.__dict__ for B in C.__mro__)):
- return True
- return NotImplemented
-
-
-class Dict(dict, MutableMapping[KT, VT]):
- __slots__ = ()
- __extra__ = dict
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Dict:
- raise TypeError("Type Dict cannot be instantiated; "
- "use dict() instead")
- return _generic_new(dict, cls, *args, **kwds)
-
-
-class DefaultDict(collections.defaultdict, MutableMapping[KT, VT]):
- __slots__ = ()
- __extra__ = collections.defaultdict
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is DefaultDict:
- return collections.defaultdict(*args, **kwds)
- return _generic_new(collections.defaultdict, cls, *args, **kwds)
-
-
-class Counter(collections.Counter, Dict[T, int]):
- __slots__ = ()
- __extra__ = collections.Counter
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Counter:
- return collections.Counter(*args, **kwds)
- return _generic_new(collections.Counter, cls, *args, **kwds)
-
-
-# Determine what base class to use for Generator.
-if hasattr(collections_abc, 'Generator'):
- # Sufficiently recent versions of 3.5 have a Generator ABC.
- _G_base = collections_abc.Generator
-else:
- # Fall back on the exact type.
- _G_base = types.GeneratorType
-
-
-class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]):
- __slots__ = ()
- __extra__ = _G_base
-
- def __new__(cls, *args, **kwds):
- if cls._gorg is Generator:
- raise TypeError("Type Generator cannot be instantiated; "
- "create a subclass instead")
- return _generic_new(_G_base, cls, *args, **kwds)
-
-
-# Internal type variable used for Type[].
-CT_co = TypeVar('CT_co', covariant=True, bound=type)
-
-
-# This is not a real generic class. Don't use outside annotations.
-class Type(Generic[CT_co]):
- """A special construct usable to annotate class objects.
-
- For example, suppose we have the following classes::
-
- class User: ... # Abstract base for User classes
- class BasicUser(User): ...
- class ProUser(User): ...
- class TeamUser(User): ...
-
- And a function that takes a class argument that's a subclass of
- User and returns an instance of the corresponding class::
-
- U = TypeVar('U', bound=User)
- def new_user(user_class: Type[U]) -> U:
- user = user_class()
- # (Here we could write the user object to a database)
- return user
-
- joe = new_user(BasicUser)
-
- At this point the type checker knows that joe has type BasicUser.
- """
- __slots__ = ()
- __extra__ = type
-
-
-def NamedTuple(typename, fields):
- """Typed version of namedtuple.
-
- Usage::
-
- Employee = typing.NamedTuple('Employee', [('name', str), ('id', int)])
-
- This is equivalent to::
-
- Employee = collections.namedtuple('Employee', ['name', 'id'])
-
- The resulting class has one extra attribute: _field_types,
- giving a dict mapping field names to types. (The field names
- are in the _fields attribute, which is part of the namedtuple
- API.)
- """
- fields = [(n, t) for n, t in fields]
- cls = collections.namedtuple(typename, [n for n, t in fields])
- cls._field_types = dict(fields)
- # Set the module to the caller's module (otherwise it'd be 'typing').
- try:
- cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
- except (AttributeError, ValueError):
- pass
- return cls
-
-
-def _check_fails(cls, other):
- try:
- if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools', 'typing']:
- # Typed dicts are only for static structural subtyping.
- raise TypeError('TypedDict does not support instance and class checks')
- except (AttributeError, ValueError):
- pass
- return False
-
-
-def _dict_new(cls, *args, **kwargs):
- return dict(*args, **kwargs)
-
-
-def _typeddict_new(cls, _typename, _fields=None, **kwargs):
- total = kwargs.pop('total', True)
- if _fields is None:
- _fields = kwargs
- elif kwargs:
- raise TypeError("TypedDict takes either a dict or keyword arguments,"
- " but not both")
-
- ns = {'__annotations__': dict(_fields), '__total__': total}
- try:
- # Setting correct module is necessary to make typed dict classes pickleable.
- ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
- except (AttributeError, ValueError):
- pass
-
- return _TypedDictMeta(_typename, (), ns)
-
-
-class _TypedDictMeta(type):
- def __new__(cls, name, bases, ns, total=True):
- # Create new typed dict class object.
- # This method is called directly when TypedDict is subclassed,
- # or via _typeddict_new when TypedDict is instantiated. This way
- # TypedDict supports all three syntaxes described in its docstring.
- # Subclasses and instances of TypedDict return actual dictionaries
- # via _dict_new.
- ns['__new__'] = _typeddict_new if name == b'TypedDict' else _dict_new
- tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
-
- anns = ns.get('__annotations__', {})
- msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
- anns = {n: _type_check(tp, msg) for n, tp in anns.items()}
- for base in bases:
- anns.update(base.__dict__.get('__annotations__', {}))
- tp_dict.__annotations__ = anns
- if not hasattr(tp_dict, '__total__'):
- tp_dict.__total__ = total
- return tp_dict
-
- __instancecheck__ = __subclasscheck__ = _check_fails
-
-
-TypedDict = _TypedDictMeta(b'TypedDict', (dict,), {})
-TypedDict.__module__ = __name__
-TypedDict.__doc__ = \
- """A simple typed name space. At runtime it is equivalent to a plain dict.
-
- TypedDict creates a dictionary type that expects all of its
- instances to have a certain set of keys, with each key
- associated with a value of a consistent type. This expectation
- is not checked at runtime but is only enforced by type checkers.
- Usage::
-
- Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
-
- a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
- b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
-
- assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
-
- The type info could be accessed via Point2D.__annotations__. TypedDict
- supports an additional equivalent form::
-
- Point2D = TypedDict('Point2D', x=int, y=int, label=str)
- """
-
-
-def NewType(name, tp):
- """NewType creates simple unique types with almost zero
- runtime overhead. NewType(name, tp) is considered a subtype of tp
- by static type checkers. At runtime, NewType(name, tp) returns
- a dummy function that simply returns its argument. Usage::
-
- UserId = NewType('UserId', int)
-
- def name_by_id(user_id):
- # type: (UserId) -> str
- ...
-
- UserId('user') # Fails type check
-
- name_by_id(42) # Fails type check
- name_by_id(UserId(42)) # OK
-
- num = UserId(5) + 1 # type: int
- """
-
- def new_type(x):
- return x
-
- # Some versions of Python 2 complain because of making all strings unicode
- new_type.__name__ = str(name)
- new_type.__supertype__ = tp
- return new_type
-
-
-# Python-version-specific alias (Python 2: unicode; Python 3: str)
-Text = unicode
-
-
-# Constant that's True when type checking, but False here.
-TYPE_CHECKING = False
-
-
-class IO(Generic[AnyStr]):
- """Generic base class for TextIO and BinaryIO.
-
- This is an abstract, generic version of the return of open().
-
- NOTE: This does not distinguish between the different possible
- classes (text vs. binary, read vs. write vs. read/write,
- append-only, unbuffered). The TextIO and BinaryIO subclasses
- below capture the distinctions between text vs. binary, which is
- pervasive in the interface; however we currently do not offer a
- way to track the other distinctions in the type system.
- """
-
- __slots__ = ()
-
- @abstractproperty
- def mode(self):
- pass
-
- @abstractproperty
- def name(self):
- pass
-
- @abstractmethod
- def close(self):
- pass
-
- @abstractproperty
- def closed(self):
- pass
-
- @abstractmethod
- def fileno(self):
- pass
-
- @abstractmethod
- def flush(self):
- pass
-
- @abstractmethod
- def isatty(self):
- pass
-
- @abstractmethod
- def read(self, n=-1):
- pass
-
- @abstractmethod
- def readable(self):
- pass
-
- @abstractmethod
- def readline(self, limit=-1):
- pass
-
- @abstractmethod
- def readlines(self, hint=-1):
- pass
-
- @abstractmethod
- def seek(self, offset, whence=0):
- pass
-
- @abstractmethod
- def seekable(self):
- pass
-
- @abstractmethod
- def tell(self):
- pass
-
- @abstractmethod
- def truncate(self, size=None):
- pass
-
- @abstractmethod
- def writable(self):
- pass
-
- @abstractmethod
- def write(self, s):
- pass
-
- @abstractmethod
- def writelines(self, lines):
- pass
-
- @abstractmethod
- def __enter__(self):
- pass
-
- @abstractmethod
- def __exit__(self, type, value, traceback):
- pass
-
-
-class BinaryIO(IO[bytes]):
- """Typed version of the return of open() in binary mode."""
-
- __slots__ = ()
-
- @abstractmethod
- def write(self, s):
- pass
-
- @abstractmethod
- def __enter__(self):
- pass
-
-
-class TextIO(IO[unicode]):
- """Typed version of the return of open() in text mode."""
-
- __slots__ = ()
-
- @abstractproperty
- def buffer(self):
- pass
-
- @abstractproperty
- def encoding(self):
- pass
-
- @abstractproperty
- def errors(self):
- pass
-
- @abstractproperty
- def line_buffering(self):
- pass
-
- @abstractproperty
- def newlines(self):
- pass
-
- @abstractmethod
- def __enter__(self):
- pass
-
-
-class io(object):
- """Wrapper namespace for IO generic classes."""
-
- __all__ = ['IO', 'TextIO', 'BinaryIO']
- IO = IO
- TextIO = TextIO
- BinaryIO = BinaryIO
-
-
-io.__name__ = __name__ + b'.io'
-sys.modules[io.__name__] = io
-
-
-Pattern = _TypeAlias('Pattern', AnyStr, type(stdlib_re.compile('')),
- lambda p: p.pattern)
-Match = _TypeAlias('Match', AnyStr, type(stdlib_re.match('', '')),
- lambda m: m.re.pattern)
-
-
-class re(object):
- """Wrapper namespace for re type aliases."""
-
- __all__ = ['Pattern', 'Match']
- Pattern = Pattern
- Match = Match
-
-
-re.__name__ = __name__ + b'.re'
-sys.modules[re.__name__] = re
diff --git a/sources/shiboken2/shibokenmodule/nothing.h b/sources/shiboken2/shibokenmodule/nothing.h
deleted file mode 100644
index e69de29bb..000000000
--- a/sources/shiboken2/shibokenmodule/nothing.h
+++ /dev/null
diff --git a/sources/shiboken2/shibokenmodule/shibokenmodule.txt.in b/sources/shiboken2/shibokenmodule/shibokenmodule.txt.in
deleted file mode 100644
index c5adc6091..000000000
--- a/sources/shiboken2/shibokenmodule/shibokenmodule.txt.in
+++ /dev/null
@@ -1,16 +0,0 @@
-[generator-project]
-
-generator-set = shiboken
-
-header-file = @CMAKE_CURRENT_SOURCE_DIR@/nothing.h
-typesystem-file = @CMAKE_CURRENT_SOURCE_DIR@/typesystem_shiboken.xml
-
-output-directory = @CMAKE_CURRENT_BINARY_DIR@
-
-# include-path = @libsample_SOURCE_DIR@
-
-typesystem-path = @CMAKE_CURRENT_SOURCE_DIR@
-
-avoid-protected-hack
-#enable-parent-ctor-heuristic
-#use-isnull-as-nb_nonzero
diff --git a/sources/shiboken2/shibokenmodule/typesystem_shiboken.xml b/sources/shiboken2/shibokenmodule/typesystem_shiboken.xml
deleted file mode 100644
index 3eba557fb..000000000
--- a/sources/shiboken2/shibokenmodule/typesystem_shiboken.xml
+++ /dev/null
@@ -1,129 +0,0 @@
-<?xml version="1.0" ?>
-<typesystem package="shiboken2">
- <custom-type name="PyObject" />
- <custom-type name="PyType" />
- <primitive-type name="bool" />
- <primitive-type name="unsigned long" />
- <primitive-type name="size_t" />
- <add-function signature="isValid(PyObject*)" return-type="bool">
- <inject-code>
- bool isValid = Shiboken::Object::isValid(%1, false);
- %PYARG_0 = %CONVERTTOPYTHON[bool](isValid);
- </inject-code>
- </add-function>
-
- <add-function signature="invalidate(PyObject*)">
- <inject-code>
- Shiboken::Object::invalidate(%1);
- </inject-code>
- </add-function>
-
- <add-function signature="wrapInstance(size_t, PyType)" return-type="PyObject*">
- <inject-code>
- if (Shiboken::ObjectType::checkType((PyTypeObject*)%2))
- %PYARG_0 = Shiboken::Object::newObject((SbkObjectType*)%2, (void*)%1, false, true);
- else
- PyErr_SetString(PyExc_TypeError, "You need a shiboken-based type.");
- </inject-code>
- </add-function>
-
- <add-function signature="getCppPointer(PyObject*)" return-type="PyObject*">
- <inject-code>
- if (Shiboken::Object::checkType(%1)) {
- std::vector&lt;void*> ptrs = Shiboken::Object::cppPointers((SbkObject*)%1);
- %PYARG_0 = PyTuple_New(ptrs.size());
- for (std::size_t i = 0; i &lt; ptrs.size(); ++i)
- PyTuple_SET_ITEM(%PYARG_0, i, PyLong_FromVoidPtr(ptrs[i]));
- } else {
- PyErr_SetString(PyExc_TypeError, "You need a shiboken-based type.");
- }
- </inject-code>
- </add-function>
-
- <add-function signature="delete(PyObject*)">
- <inject-code>
- if (Shiboken::Object::checkType(%1)) {
- Shiboken::Object::callCppDestructors((SbkObject*)%1);
- } else {
- PyErr_SetString(PyExc_TypeError, "You need a shiboken-based type.");
- }
- </inject-code>
- </add-function>
-
- <add-function signature="ownedByPython(PyObject*)" return-type="bool">
- <inject-code>
- if (Shiboken::Object::checkType(%1)) {
- bool hasOwnership = Shiboken::Object::hasOwnership((SbkObject*)%1);
- %PYARG_0 = %CONVERTTOPYTHON[bool](hasOwnership);
- } else {
- PyErr_SetString(PyExc_TypeError, "You need a shiboken-based type.");
- }
- </inject-code>
- </add-function>
-
- <add-function signature="createdByPython(PyObject*)" return-type="bool">
- <inject-code>
- if (Shiboken::Object::checkType(%1)) {
- bool wasCreatedByPython = Shiboken::Object::wasCreatedByPython((SbkObject*)%1);
- %PYARG_0 = %CONVERTTOPYTHON[bool](wasCreatedByPython);
- } else {
- PyErr_SetString(PyExc_TypeError, "You need a shiboken-based type.");
- }
- </inject-code>
- </add-function>
-
- <add-function signature="dump(PyObject*)" return-type="PyObject*">
- <inject-code>
- if (!Shiboken::Object::checkType(%1)) {
- %PYARG_0 = Shiboken::String::fromCString("Ordinary Python type.");
- } else {
- std::string str = Shiboken::Object::info((SbkObject*)%1);
- %PYARG_0 = Shiboken::String::fromCString(str.c_str());
- }
- </inject-code>
- </add-function>
-
- <add-function signature="getAllValidWrappers(void)" return-type="PyObject*">
- <inject-code>
- std::set&lt;PyObject*&gt; setAll = Shiboken::BindingManager::instance().getAllPyObjects();
- PyObject* listAll = PyList_New(0);
- if (listAll == NULL)
- return NULL;
-
- const std::set&lt;PyObject*&gt;::iterator end = setAll.end();
- for (std::set&lt;PyObject*&gt;::iterator iter = setAll.begin(); iter != end; ++iter) {
- if (*iter != NULL) {
- if (PyList_Append(listAll, *iter) != 0) {
- Py_DECREF(listAll);
- return NULL;
- }
- }
- }
- return listAll;
- </inject-code>
- </add-function>
-
- <add-function signature="_unpickle_enum(PyObject*, PyObject*)" return-type="PyObject*">
- <inject-code>
- %PYARG_0 = Shiboken::Enum::unpickleEnum(%1, %2);
- </inject-code>
- </add-function>
-
- <extra-includes>
- <include file-name="sbkversion.h" location="local"/>
- <include file-name="voidptr.h" location="local"/>
- </extra-includes>
- <inject-code position="end">
- // Add __version__ and __version_info__ attributes to the module
- PyObject* version = PyTuple_New(5);
- PyTuple_SET_ITEM(version, 0, PyInt_FromLong(SHIBOKEN_MAJOR_VERSION));
- PyTuple_SET_ITEM(version, 1, PyInt_FromLong(SHIBOKEN_MINOR_VERSION));
- PyTuple_SET_ITEM(version, 2, PyInt_FromLong(SHIBOKEN_MICRO_VERSION));
- PyTuple_SET_ITEM(version, 3, Shiboken::String::fromCString(SHIBOKEN_RELEASE_LEVEL));
- PyTuple_SET_ITEM(version, 4, PyInt_FromLong(SHIBOKEN_SERIAL));
- PyModule_AddObject(module, "__version_info__", version);
- PyModule_AddStringConstant(module, "__version__", SHIBOKEN_VERSION);
-
- VoidPtr::addVoidPtrToModule(module);
- </inject-code>
-</typesystem>
diff --git a/sources/shiboken2/tests/CMakeLists.txt b/sources/shiboken2/tests/CMakeLists.txt
deleted file mode 100644
index 0a9a6f11a..000000000
--- a/sources/shiboken2/tests/CMakeLists.txt
+++ /dev/null
@@ -1,93 +0,0 @@
-if(BUILD_TESTS)
- find_package(Qt${QT_MAJOR_VERSION}Test 5.12 REQUIRED)
-endif()
-
-add_subdirectory(libminimal)
-if(NOT DEFINED MINIMAL_TESTS)
- add_subdirectory(libsample)
- add_subdirectory(libsmart)
- add_subdirectory(libother)
-endif()
-
-if(WIN32 OR DEFINED AVOID_PROTECTED_HACK)
- message(STATUS "Tests will be generated avoiding the protected hack!")
- set(GENERATOR_EXTRA_FLAGS --avoid-protected-hack)
-else()
- message(STATUS "Tests will be generated using the protected hack!")
- set(GENERATOR_EXTRA_FLAGS )
-endif()
-
-add_subdirectory(minimalbinding)
-if(NOT DEFINED MINIMAL_TESTS)
- add_subdirectory(samplebinding)
- add_subdirectory(smartbinding)
- add_subdirectory(otherbinding)
-endif()
-
-if(DEFINED MINIMAL_TESTS)
- file(GLOB TEST_FILES minimalbinding/*_test.py)
-else()
- file(GLOB TEST_FILES minimalbinding/*_test.py
- samplebinding/*_test.py
- otherbinding/*_test.py
- smartbinding/*_test.py
- shibokenmodule/*_test.py)
-endif()
-list(SORT TEST_FILES)
-
-set(test_blacklist "")
-
-find_package(PythonInterp REQUIRED)
-if(NOT CTEST_TESTING_TIMEOUT)
- set(CTEST_TESTING_TIMEOUT 60)
-endif()
-
-if(CMAKE_VERSION VERSION_LESS 2.8)
- message("CMake version greater than 2.8 necessary to run tests")
-else()
- get_filename_component(BUILD_DIR "${libminimal_BINARY_DIR}" DIRECTORY)
- get_filename_component(BUILD_DIR "${BUILD_DIR}" DIRECTORY)
- get_filename_component(BUILD_DIR "${BUILD_DIR}" DIRECTORY)
- foreach(test_file ${TEST_FILES})
- string(REGEX MATCH "/([^/]+)(binding|module)/([^/]+)_test.py" tmp ${test_file})
- set(test_name "${CMAKE_MATCH_1}_${CMAKE_MATCH_3}")
- list(FIND test_blacklist ${test_name} expect_fail)
- add_test(${test_name} ${PYTHON_EXECUTABLE} ${test_file})
- set_tests_properties(${test_name} PROPERTIES ENVIRONMENT "BUILD_DIR=${BUILD_DIR}")
- set_tests_properties(${test_name} PROPERTIES TIMEOUT ${CTEST_TESTING_TIMEOUT})
- if (${expect_fail} GREATER -1)
- set_tests_properties(${test_name} PROPERTIES WILL_FAIL TRUE)
- endif()
- endforeach()
-endif()
-
-add_subdirectory(dumpcodemodel)
-
-# FIXME Skipped until add an option to choose the generator
-# add_subdirectory(test_generator)
-
-if (NOT APIEXTRACTOR_DOCSTRINGS_DISABLED)
-# project(sphinxtabletest)
-#
-# # TODO
-# set(sphinxtabletest_SRC sphinxtabletest.cpp)
-# qt4_automoc(${sphinxtabletest_SRC})
-#
-# include_directories(${QT_INCLUDE_DIR}
-# ${QT_QTCORE_INCLUDE_DIR}
-# ${CMAKE_CURRENT_BINARY_DIR}
-# ${qtdoc_generator_SOURCE_DIR})
-#
-# add_executable(sphinxtabletest ${sphinxtabletest_SRC})
-#
-# target_link_libraries(sphinxtabletest
-# ${QT_QTTEST_LIBRARY}
-# ${APIEXTRACTOR_LIBRARY}
-# qtdoc_generator
-# genrunner)
-#
-# add_test("sphinxtable" sphinxtabletest)
-# if (INSTALL_TESTS)
-# install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/sphinxtabletest DESTINATION ${TEST_INSTALL_DIR})
-# endif()
-endif()
diff --git a/sources/shiboken2/tests/dumpcodemodel/CMakeLists.txt b/sources/shiboken2/tests/dumpcodemodel/CMakeLists.txt
deleted file mode 100644
index 5c5e2c7b0..000000000
--- a/sources/shiboken2/tests/dumpcodemodel/CMakeLists.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-add_executable(dumpcodemodel main.cpp)
-
-target_include_directories(dumpcodemodel
- PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${apiextractor_SOURCE_DIR})
-
-target_link_libraries(dumpcodemodel PUBLIC apiextractor Qt${QT_MAJOR_VERSION}::Core)
diff --git a/sources/shiboken2/tests/dumpcodemodel/main.cpp b/sources/shiboken2/tests/dumpcodemodel/main.cpp
deleted file mode 100644
index 52d64be94..000000000
--- a/sources/shiboken2/tests/dumpcodemodel/main.cpp
+++ /dev/null
@@ -1,227 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <abstractmetabuilder_p.h>
-#include <parser/codemodel.h>
-#include <clangparser/compilersupport.h>
-
-#include <QtCore/QCoreApplication>
-#include <QtCore/QCommandLineOption>
-#include <QtCore/QCommandLineParser>
-#include <QtCore/QDateTime>
-#include <QtCore/QDebug>
-#include <QtCore/QDir>
-#include <QtCore/QFile>
-#include <QtCore/QXmlStreamWriter>
-
-#include <iostream>
-#include <algorithm>
-#include <iterator>
-
-static inline QString languageLevelDescription()
-{
- return QLatin1String("C++ Language level (c++11..c++17, default=")
- + QLatin1String(clang::languageLevelOption(clang::emulatedCompilerLanguageLevel()))
- + QLatin1Char(')');
-}
-
-static void formatDebugOutput(const FileModelItem &dom, bool verbose)
-{
- QString output;
- {
- QDebug debug(&output);
- if (verbose)
- debug.setVerbosity(3);
- debug << dom.data();
- }
- std::cout << qPrintable(output) << '\n';
-}
-
-static const char *primitiveTypes[] = {
- "int", "unsigned", "short", "unsigned short", "long", "unsigned long",
- "float", "double"
-};
-
-static inline QString nameAttribute() { return QStringLiteral("name"); }
-
-static void formatXmlNamespace(QXmlStreamWriter &writer, const NamespaceModelItem &nsp);
-static void formatXmlClass(QXmlStreamWriter &writer, const ClassModelItem &klass);
-
-static void formatXmlEnum(QXmlStreamWriter &writer, const EnumModelItem &en)
-{
- writer.writeStartElement(QStringLiteral("enum-type"));
- writer.writeAttribute(nameAttribute(), en->name());
- writer.writeEndElement();
-}
-
-static void formatXmlScopeMembers(QXmlStreamWriter &writer, const ScopeModelItem &nsp)
-{
- for (const auto &klass : nsp->classes()) {
- if (klass->classType() != CodeModel::Union && klass->templateParameters().isEmpty())
- formatXmlClass(writer, klass);
- }
- for (const auto &en : nsp->enums())
- formatXmlEnum(writer, en);
-}
-
-static bool isPublicCopyConstructor(const FunctionModelItem &f)
-{
- return f->functionType() == CodeModel::CopyConstructor
- && f->accessPolicy() == CodeModel::Public && !f->isDeleted();
-}
-
-static void formatXmlClass(QXmlStreamWriter &writer, const ClassModelItem &klass)
-{
- // Heuristics for value types: check on public copy constructors.
- const auto functions = klass->functions();
- const bool isValueType = std::any_of(functions.cbegin(), functions.cend(),
- isPublicCopyConstructor);
- writer.writeStartElement(isValueType ? QStringLiteral("value-type")
- : QStringLiteral("object-type"));
- writer.writeAttribute(nameAttribute(), klass->name());
- formatXmlScopeMembers(writer, klass);
- writer.writeEndElement();
-}
-
-static void formatXmlNamespaceMembers(QXmlStreamWriter &writer, const NamespaceModelItem &nsp)
-{
- for (const auto &nested : nsp->namespaces())
- formatXmlNamespace(writer, nested);
- for (auto func : nsp->functions()) {
- const QString signature = func->typeSystemSignature();
- if (!signature.contains(QLatin1String("operator"))) { // Skip free operators
- writer.writeStartElement(QStringLiteral("function"));
- writer.writeAttribute(QStringLiteral("signature"), signature);
- writer.writeEndElement();
- }
- }
- formatXmlScopeMembers(writer, nsp);
-}
-
-static void formatXmlNamespace(QXmlStreamWriter &writer, const NamespaceModelItem &nsp)
-{
- writer.writeStartElement(QStringLiteral("namespace-type"));
- writer.writeAttribute(nameAttribute(), nsp->name());
- formatXmlNamespaceMembers(writer, nsp);
- writer.writeEndElement();
-}
-
-static void formatXmlOutput(const FileModelItem &dom)
-{
- QString output;
- QXmlStreamWriter writer(&output);
- writer.setAutoFormatting(true);
- writer.writeStartDocument();
- writer.writeStartElement(QStringLiteral("typesystem"));
- writer.writeAttribute(QStringLiteral("package"), QStringLiteral("insert_name"));
- writer.writeComment(QStringLiteral("Auto-generated ") +
- QDateTime::currentDateTime().toString(Qt::ISODate));
- for (auto p : primitiveTypes) {
- writer.writeStartElement(QStringLiteral("primitive-type"));
- writer.writeAttribute(nameAttribute(), QLatin1String(p));
- writer.writeEndElement();
- }
- formatXmlNamespaceMembers(writer, dom);
- writer.writeEndElement();
- writer.writeEndDocument();
- std::cout << qPrintable(output) << '\n';
-}
-
-static const char descriptionFormat[] = R"(
-Type system dumper
-
-Parses a C++ header and dumps out the classes found in typesystem XML syntax.
-Arguments are arguments to the compiler the last of which should be the header
-or source file.
-It is recommended to create a .hh include file including the desired headers
-and pass that along with the required include paths.
-
-Based on Qt %1 and LibClang v%2.)";
-
-int main(int argc, char **argv)
-{
- QCoreApplication app(argc, argv);
-
- QCommandLineParser parser;
- parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
- parser.setOptionsAfterPositionalArgumentsMode(QCommandLineParser::ParseAsPositionalArguments);
- const QString description =
- QString::fromLatin1(descriptionFormat).arg(QLatin1String(qVersion()),
- clang::libClangVersion().toString());
- parser.setApplicationDescription(description);
- parser.addHelpOption();
- parser.addVersionOption();
- QCommandLineOption verboseOption(QStringLiteral("verbose"),
- QStringLiteral("Display verbose output about types"));
- parser.addOption(verboseOption);
- QCommandLineOption debugOption(QStringLiteral("debug"),
- QStringLiteral("Display debug output"));
- parser.addOption(debugOption);
-
- QCommandLineOption languageLevelOption(QStringLiteral("std"),
- languageLevelDescription(),
- QStringLiteral("level"));
- parser.addOption(languageLevelOption);
- parser.addPositionalArgument(QStringLiteral("argument"),
- QStringLiteral("C++ compiler argument"),
- QStringLiteral("argument(s)"));
-
- parser.process(app);
- const QStringList &positionalArguments = parser.positionalArguments();
- if (positionalArguments.isEmpty())
- parser.showHelp(1);
-
- QByteArrayList arguments;
- std::transform(positionalArguments.cbegin(), positionalArguments.cend(),
- std::back_inserter(arguments), QFile::encodeName);
-
- LanguageLevel level = LanguageLevel::Default;
- if (parser.isSet(languageLevelOption)) {
- const QByteArray value = parser.value(languageLevelOption).toLatin1();
- level = clang::languageLevelFromOption(value.constData());
- if (level == LanguageLevel::Default) {
- std::cerr << "Invalid value \"" << value.constData()
- << "\" for language level option.\n";
- return -2;
- }
- }
-
- const FileModelItem dom = AbstractMetaBuilderPrivate::buildDom(arguments, level, 0);
- if (dom.isNull()) {
- QString message = QLatin1String("Unable to parse ") + positionalArguments.join(QLatin1Char(' '));
- std::cerr << qPrintable(message) << '\n';
- return -2;
- }
-
- if (parser.isSet(debugOption))
- formatDebugOutput(dom, parser.isSet(verboseOption));
- else
- formatXmlOutput(dom);
-
- return 0;
-}
diff --git a/sources/shiboken2/tests/libminimal/CMakeLists.txt b/sources/shiboken2/tests/libminimal/CMakeLists.txt
deleted file mode 100644
index f906bdb84..000000000
--- a/sources/shiboken2/tests/libminimal/CMakeLists.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-project(libminimal)
-
-set(libminimal_SRC
-obj.cpp
-listuser.cpp
-typedef.cpp
-)
-
-add_library(libminimal SHARED ${libminimal_SRC})
-target_include_directories(libminimal PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
-target_compile_definitions(libminimal PRIVATE LIBMINIMAL_BUILD)
-set_property(TARGET libminimal PROPERTY PREFIX "")
-
diff --git a/sources/shiboken2/tests/libminimal/libminimalmacros.h b/sources/shiboken2/tests/libminimal/libminimalmacros.h
deleted file mode 100644
index a9c417624..000000000
--- a/sources/shiboken2/tests/libminimal/libminimalmacros.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef LIBMINIMALMACROS_H
-#define LIBMINIMALMACROS_H
-
-#if defined _WIN32 || defined __CYGWIN__
- #if LIBMINIMAL_BUILD
- #define LIBMINIMAL_API __declspec(dllexport)
- #else
- #define LIBMINIMAL_API __declspec(dllimport)
- #endif
-#else
-#if __GNUC__ >= 4
- #define LIBMINIMAL_API __attribute__ ((visibility("default")))
-#else
- #define LIBMINIMAL_API
-#endif
-#endif
-
-#endif
diff --git a/sources/shiboken2/tests/libminimal/listuser.cpp b/sources/shiboken2/tests/libminimal/listuser.cpp
deleted file mode 100644
index 4ce00f39c..000000000
--- a/sources/shiboken2/tests/libminimal/listuser.cpp
+++ /dev/null
@@ -1,124 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <numeric>
-#include <cstdlib>
-#include "listuser.h"
-
-std::list<int>
-ListUser::createIntList(int num)
-{
- std::list<int> retval;
- for (int i = 0; i < num; ++i)
- retval.push_back(i);
- return retval;
-}
-
-int
-ListUser::sumIntList(std::list<int> intList)
-{
- int total = 0;
- for (std::list<int>::iterator iter = intList.begin(); iter != intList.end(); iter++)
- total += *iter;
- return total;
-}
-
-std::list<MinBool>
-ListUser::createMinBoolList(MinBool mb1, MinBool mb2)
-{
- std::list<MinBool> retval;
- retval.push_back(mb1);
- retval.push_back(mb2);
- return retval;
-}
-
-MinBool
-ListUser::oredMinBoolList(std::list<MinBool> minBoolList)
-{
- MinBool result(false);
- for (std::list<MinBool>::iterator iter = minBoolList.begin(); iter != minBoolList.end(); iter++)
- result |= *iter;
- return result;
-}
-
-std::list<Val>
-ListUser::createValList(int num)
-{
- std::list<Val> retval;
- for (int i = 0; i < num; ++i)
- retval.push_back(Val(i));
- return retval;
-}
-
-int
-ListUser::sumValList(std::list<Val> valList)
-{
- int total = 0;
- for (std::list<Val>::iterator iter = valList.begin(); iter != valList.end(); iter++)
- total += iter->valId();
- return total;
-}
-
-std::list<Obj*>
-ListUser::createObjList(Obj* o1, Obj* o2)
-{
- std::list<Obj*> retval;
- retval.push_back(o1);
- retval.push_back(o2);
- return retval;
-}
-
-int
-ListUser::sumObjList(std::list<Obj*> objList)
-{
- int total = 0;
- for (std::list<Obj*>::iterator iter = objList.begin(); iter != objList.end(); iter++)
- total += (*iter)->objId();
- return total;
-}
-
-std::list<std::list<int> >
-ListUser::createListOfIntLists(int num)
-{
- std::list<std::list<int> > retval;
- for (int i = 0; i < num; ++i)
- retval.push_back(createIntList(num));
- return retval;
-}
-
-int
-ListUser::sumListOfIntLists(std::list<std::list<int> > intListList)
-{
- int total = 0;
- for (std::list<std::list<int> >::iterator it0 = intListList.begin(); it0 != intListList.end(); it0++) {
- for (std::list<int>::iterator it1 = (*it0).begin(); it1 != (*it0).end(); it1++)
- total += *it1;
- }
- return total;
-}
-
diff --git a/sources/shiboken2/tests/libminimal/listuser.h b/sources/shiboken2/tests/libminimal/listuser.h
deleted file mode 100644
index 6c7e6aedd..000000000
--- a/sources/shiboken2/tests/libminimal/listuser.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef LISTUSER_H
-#define LISTUSER_H
-
-#include <list>
-#include "obj.h"
-#include "val.h"
-#include "minbool.h"
-
-#include "libminimalmacros.h"
-
-struct LIBMINIMAL_API ListUser
-{
- virtual ~ListUser() {}
-
- // List of C++ primitive type items
- virtual std::list<int> createIntList(int num);
- std::list<int> callCreateIntList(int num) { return createIntList(num); }
- virtual int sumIntList(std::list<int> intList);
- int callSumIntList(std::list<int> intList) { return sumIntList(intList); }
-
- // List of C++ MinBool objects used as primitives in Python
- virtual std::list<MinBool> createMinBoolList(MinBool mb1, MinBool mb2);
- std::list<MinBool> callCreateMinBoolList(MinBool mb1, MinBool mb2) { return createMinBoolList(mb1, mb2); }
- virtual MinBool oredMinBoolList(std::list<MinBool> minBoolList);
- MinBool callOredMinBoolList(std::list<MinBool> minBoolList) { return oredMinBoolList(minBoolList); }
-
- // List of C++ value types
- virtual std::list<Val> createValList(int num);
- std::list<Val> callCreateValList(int num) { return createValList(num); }
- virtual int sumValList(std::list<Val> valList);
- int callSumValList(std::list<Val> valList) { return sumValList(valList); }
-
- // List of C++ object types
- virtual std::list<Obj*> createObjList(Obj* o1, Obj* o2);
- std::list<Obj*> callCreateObjList(Obj* o1, Obj* o2) { return createObjList(o1, o2); }
- virtual int sumObjList(std::list<Obj*> objList);
- int callSumObjList(std::list<Obj*> objList) { return sumObjList(objList); }
-
- // List of lists of C++ primitive type items
- virtual std::list<std::list<int> > createListOfIntLists(int num);
- std::list<std::list<int> > callCreateListOfIntLists(int num) { return createListOfIntLists(num); }
- virtual int sumListOfIntLists(std::list<std::list<int> > intListList);
- int callSumListOfIntLists(std::list<std::list<int> > intListList) { return sumListOfIntLists(intListList); }
-};
-
-#endif // LISTUSER_H
-
diff --git a/sources/shiboken2/tests/libminimal/minbool.h b/sources/shiboken2/tests/libminimal/minbool.h
deleted file mode 100644
index 72a2cbabe..000000000
--- a/sources/shiboken2/tests/libminimal/minbool.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MINBOOL_H
-#define MINBOOL_H
-
-#include "libminimalmacros.h"
-
-class LIBMINIMAL_API MinBool
-{
-public:
- inline explicit MinBool(bool b) : m_value(b) {}
- bool value() const { return m_value; }
- inline MinBool operator!() const { return MinBool(!m_value); }
- inline MinBool& operator|=(const MinBool& other) {
- m_value = m_value | other.m_value;
- return *this;
- }
-private:
- bool m_value;
-};
-
-inline bool operator==(MinBool b1, bool b2) { return (!b1).value() == !b2; }
-inline bool operator==(bool b1, MinBool b2) { return (!b1) == (!b2).value(); }
-inline bool operator==(MinBool b1, MinBool b2) { return (!b1).value() == (!b2).value(); }
-inline bool operator!=(MinBool b1, bool b2) { return (!b1).value() != !b2; }
-inline bool operator!=(bool b1, MinBool b2) { return (!b1) != (!b2).value(); }
-inline bool operator!=(MinBool b1, MinBool b2) { return (!b1).value() != (!b2).value(); }
-
-class LIBMINIMAL_API MinBoolUser
-{
-public:
- MinBoolUser() : m_minbool(MinBool(false)) {}
- virtual ~MinBoolUser() {}
- inline MinBool minBool() { return m_minbool; }
- inline void setMinBool(MinBool minBool) { m_minbool = minBool; }
- virtual MinBool invertedMinBool() { return !m_minbool; }
- inline MinBool callInvertedMinBool() { return invertedMinBool(); }
-private:
- MinBool m_minbool;
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libminimal/obj.cpp b/sources/shiboken2/tests/libminimal/obj.cpp
deleted file mode 100644
index fd6e9f7d9..000000000
--- a/sources/shiboken2/tests/libminimal/obj.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "obj.h"
-
-Obj::Obj(int objId) : m_objId(objId)
-{
-}
-
-Obj::~Obj()
-{
-}
-
-bool
-Obj::virtualMethod(int val)
-{
- return !bool(val%2);
-}
-
diff --git a/sources/shiboken2/tests/libminimal/obj.h b/sources/shiboken2/tests/libminimal/obj.h
deleted file mode 100644
index a5e20d496..000000000
--- a/sources/shiboken2/tests/libminimal/obj.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OBJ_H
-#define OBJ_H
-
-#include "libminimalmacros.h"
-
-class LIBMINIMAL_API Obj
-{
-public:
- explicit Obj(int objId);
- virtual ~Obj();
-
- int objId() { return m_objId; }
- void setObjId(int objId) { m_objId = objId; }
-
- virtual bool virtualMethod(int val);
- bool callVirtualMethod(int val) { return virtualMethod(val); }
-
- virtual Obj* passObjectType(Obj* obj) { return obj; }
- Obj* callPassObjectType(Obj* obj) { return passObjectType(obj); }
-
- virtual Obj* passObjectTypeReference(Obj& obj) { return &obj; }
- Obj* callPassObjectTypeReference(Obj& obj) { return passObjectTypeReference(obj); }
-
-private:
- Obj(const Obj&);
- Obj& operator=(const Obj&);
- int m_objId;
-};
-
-#endif // OBJ_H
-
diff --git a/sources/shiboken2/tests/libminimal/typedef.cpp b/sources/shiboken2/tests/libminimal/typedef.cpp
deleted file mode 100644
index e0886d982..000000000
--- a/sources/shiboken2/tests/libminimal/typedef.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "typedef.h"
-
-//
-// Test wrapping of a typedef
-//
-bool arrayFuncInt(std::vector<int> a)
-{
- return a.empty();
-}
-
-bool arrayFuncIntTypedef(MyArray a)
-{
- return arrayFuncInt(a);
-}
-
-std::vector<int> arrayFuncIntReturn(int size)
-{
- return std::vector<int>(size);
-}
-
-MyArray arrayFuncIntReturnTypedef(int size)
-{
- return arrayFuncIntReturn(size);
-}
-
-//
-// Test wrapping of a typedef of a typedef
-//
-bool arrayFunc(std::vector<int> a)
-{
- return a.empty();
-}
-
-bool arrayFuncTypedef(MyArray a)
-{
- return arrayFunc(a);
-}
-
-std::vector<int> arrayFuncReturn(int size)
-{
- return std::vector<int>(size);
-}
-
-MyArray arrayFuncReturnTypedef(int size)
-{
- return arrayFuncReturn(size);
-}
diff --git a/sources/shiboken2/tests/libminimal/typedef.h b/sources/shiboken2/tests/libminimal/typedef.h
deleted file mode 100644
index b8d6faacd..000000000
--- a/sources/shiboken2/tests/libminimal/typedef.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TYPEDEF_H
-#define TYPEDEF_H
-
-#include "libminimalmacros.h"
-
-#include <vector>
-
-// Test wrapping of a typedef
-using MyArrayInt = std::vector<int>;
-
-LIBMINIMAL_API bool arrayFuncInt(std::vector<int> a);
-LIBMINIMAL_API bool arrayFuncIntTypedef(MyArrayInt a);
-
-LIBMINIMAL_API std::vector<int> arrayFuncIntReturn(int size);
-LIBMINIMAL_API MyArrayInt arrayFuncIntReturnTypedef(int size);
-
-// Test wrapping of a typedef of a typedef
-using MyArray = MyArrayInt;
-
-LIBMINIMAL_API bool arrayFunc(std::vector<int> a);
-LIBMINIMAL_API bool arrayFuncTypedef(MyArray a);
-
-LIBMINIMAL_API std::vector<int> arrayFuncReturn(int size);
-LIBMINIMAL_API MyArray arrayFuncReturnTypedef(int size);
-
-#endif
diff --git a/sources/shiboken2/tests/libminimal/val.h b/sources/shiboken2/tests/libminimal/val.h
deleted file mode 100644
index 9af7ab70a..000000000
--- a/sources/shiboken2/tests/libminimal/val.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef VAL_H
-#define VAL_H
-
-#include "libminimalmacros.h"
-
-class LIBMINIMAL_API Val
-{
-public:
- explicit Val(int valId) : m_valId(valId) {}
- virtual ~Val() {}
-
- int valId() { return m_valId; }
- void setValId(int valId) { m_valId = valId; }
-
- virtual Val passValueType(Val val) { return val; }
- Val callPassValueType(Val val) { return passValueType(val); }
-
- virtual Val* passValueTypePointer(Val* val) { return val; }
- Val* callPassValueTypePointer(Val* val) { return passValueTypePointer(val); }
-
- virtual Val* passValueTypeReference(Val& val) { return &val; }
- Val* callPassValueTypeReference(Val& val) { return passValueTypeReference(val); }
-
- enum ValEnum { One, Other };
- ValEnum oneOrTheOtherEnumValue(ValEnum enumValue) { return enumValue == One ? Other : One; }
-private:
- int m_valId;
-};
-
-#endif // VAL_H
-
diff --git a/sources/shiboken2/tests/libother/CMakeLists.txt b/sources/shiboken2/tests/libother/CMakeLists.txt
deleted file mode 100644
index d1e4c4354..000000000
--- a/sources/shiboken2/tests/libother/CMakeLists.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-project(libother)
-
-set(libother_SRC
-number.cpp
-otherderived.cpp
-otherobjecttype.cpp
-othermultiplederived.cpp
-smartptrtester.cpp
-)
-
-add_library(libother SHARED ${libother_SRC})
-target_include_directories(libother PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
-target_compile_definitions(libother PRIVATE LIBOTHER_BUILD)
-target_link_libraries(libother PUBLIC libsample libsmart)
-set_property(TARGET libother PROPERTY PREFIX "")
-
-
diff --git a/sources/shiboken2/tests/libother/extendsnoimplicitconversion.h b/sources/shiboken2/tests/libother/extendsnoimplicitconversion.h
deleted file mode 100644
index e1bcf0961..000000000
--- a/sources/shiboken2/tests/libother/extendsnoimplicitconversion.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef EXTENDSNOIMPLICITCONVERSION_H
-#define EXTENDSNOIMPLICITCONVERSION_H
-
-#include "libothermacros.h"
-#include "noimplicitconversion.h"
-
-class ExtendsNoImplicitConversion
-{
-public:
- explicit ExtendsNoImplicitConversion(int objId) : m_objId(objId) {};
- inline int objId() const { return m_objId; }
- inline operator NoImplicitConversion() const { return NoImplicitConversion(m_objId); }
-private:
- int m_objId;
-};
-#endif // EXTENDSNOIMPLICITCONVERSION_H
-
diff --git a/sources/shiboken2/tests/libother/libothermacros.h b/sources/shiboken2/tests/libother/libothermacros.h
deleted file mode 100644
index 757e9a304..000000000
--- a/sources/shiboken2/tests/libother/libothermacros.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef LIBOTHERMACROS_H
-#define LIBOTHERMACROS_H
-
-#if defined _WIN32 || defined __CYGWIN__
- #if LIBOTHER_BUILD
- #define LIBOTHER_API __declspec(dllexport)
- #else
- #define LIBOTHER_API __declspec(dllimport)
- #endif
-#else
-#if __GNUC__ >= 4
- #define LIBOTHER_API __attribute__ ((visibility("default")))
-#else
- #define LIBOTHER_API
-#endif
-#endif
-
-#endif
diff --git a/sources/shiboken2/tests/libother/number.cpp b/sources/shiboken2/tests/libother/number.cpp
deleted file mode 100644
index bc97de6a6..000000000
--- a/sources/shiboken2/tests/libother/number.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "number.h"
-#include <cstring>
-#include <sstream>
-
-using namespace std;
-
-Str
-Number::toStr() const
-{
- ostringstream in;
- in << m_value;
- return in.str().c_str();
-}
-
-Point
-operator*(const Point& p, const Number& n)
-{
- return Point(p.x() * n.value(), p.y() * n.value());
-}
-
-Complex
-Number::toComplex() const
-{
- return Complex(m_value);
-}
-
-Number
-Number::fromComplex(Complex cpx)
-{
- return Number(cpx.real());
-}
diff --git a/sources/shiboken2/tests/libother/number.h b/sources/shiboken2/tests/libother/number.h
deleted file mode 100644
index 222c6e1a6..000000000
--- a/sources/shiboken2/tests/libother/number.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef NUMBER_H
-#define NUMBER_H
-
-#include "libothermacros.h"
-#include "str.h"
-#include "point.h"
-#include "complex.h"
-
-class LIBOTHER_API Number
-{
-public:
- explicit Number(int value) : m_value(value) {};
- inline int value() const { return m_value; }
-
- Str toStr() const;
- inline operator Str() const { return toStr(); }
-
- friend LIBOTHER_API Point operator*(const Point&, const Number&);
-
- Complex toComplex() const;
- static Number fromComplex(Complex cpx);
-
-private:
- int m_value;
-};
-
-LIBOTHER_API Point operator*(const Point&, const Number&);
-
-#endif // NUMBER_H
diff --git a/sources/shiboken2/tests/libother/otherderived.cpp b/sources/shiboken2/tests/libother/otherderived.cpp
deleted file mode 100644
index d23f6ad23..000000000
--- a/sources/shiboken2/tests/libother/otherderived.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "otherderived.h"
-
-OtherDerived::OtherDerived(int id) : Abstract(id)
-{
-}
-
-OtherDerived::~OtherDerived()
-{
-}
-
-Abstract*
-OtherDerived::createObject()
-{
- static int id = 100;
- return new OtherDerived(id++);
-}
-
-void
-OtherDerived::pureVirtual()
-{
-}
-
-void*
-OtherDerived::pureVirtualReturningVoidPtr()
-{
- return nullptr;
-}
-
-void
-OtherDerived::unpureVirtual()
-{
-}
-
-void OtherDerived::pureVirtualPrivate()
-{
-}
diff --git a/sources/shiboken2/tests/libother/otherderived.h b/sources/shiboken2/tests/libother/otherderived.h
deleted file mode 100644
index 72e1e2302..000000000
--- a/sources/shiboken2/tests/libother/otherderived.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OTHERDERIVED_H
-#define OTHERDERIVED_H
-
-#include "libothermacros.h"
-#include "abstract.h"
-#include "derived.h"
-#include "objecttype.h"
-#include "complex.h"
-
-class ObjectType;
-
-class LIBOTHER_API OtherDerived : public Abstract
-{
-public:
- OtherDerived(int id = -1);
- ~OtherDerived() override;
- void pureVirtual() override;
- void* pureVirtualReturningVoidPtr() override;
- void unpureVirtual() override;
- PrintFormat returnAnEnum() override { return Short; }
-
- inline void useObjectTypeFromOtherModule(ObjectType*) {}
- inline Event useValueTypeFromOtherModule(const Event& e) { return e; }
- inline Complex useValueTypeFromOtherModule(const Complex& c) { return c; }
- inline void useEnumTypeFromOtherModule(OverloadedFuncEnum) {}
-
- // factory method
- static Abstract* createObject();
-
- void hideFunction(HideType*) override {}
-
-protected:
- inline const char* getClassName() { return className(); }
- virtual const char* className() override { return "OtherDerived"; }
-
-private:
- void pureVirtualPrivate() override;
-};
-#endif // OTHERDERIVED_H
-
diff --git a/sources/shiboken2/tests/libother/othermultiplederived.cpp b/sources/shiboken2/tests/libother/othermultiplederived.cpp
deleted file mode 100644
index e7ee4f96d..000000000
--- a/sources/shiboken2/tests/libother/othermultiplederived.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "othermultiplederived.h"
-
-VirtualMethods OtherMultipleDerived::returnUselessClass()
-{
- return VirtualMethods();
-}
-
-Base1* OtherMultipleDerived::createObject(const std::string& objName)
-{
- if (objName == "Base1")
- return new Base1;
- else if (objName == "MDerived1")
- return new MDerived1;
- else if (objName == "SonOfMDerived1")
- return new SonOfMDerived1;
- else if (objName == "MDerived3")
- return new MDerived3;
- else if (objName == "OtherMultipleDerived")
- return new OtherMultipleDerived;
- return nullptr;
-}
-
diff --git a/sources/shiboken2/tests/libother/othermultiplederived.h b/sources/shiboken2/tests/libother/othermultiplederived.h
deleted file mode 100644
index 84a426ac9..000000000
--- a/sources/shiboken2/tests/libother/othermultiplederived.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OTHERMULTIPLEDERIVED_H
-#define OTHERMULTIPLEDERIVED_H
-
-#include "libothermacros.h"
-#include "multiple_derived.h"
-#include "virtualmethods.h"
-
-class ObjectType;
-
-class LIBOTHER_API OtherMultipleDerived : public MDerived1
-{
-public:
- // this will use CppCopier from other module (bug#142)
- VirtualMethods returnUselessClass();
- static Base1* createObject(const std::string& objName);
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libother/otherobjecttype.cpp b/sources/shiboken2/tests/libother/otherobjecttype.cpp
deleted file mode 100644
index 1f782ecd8..000000000
--- a/sources/shiboken2/tests/libother/otherobjecttype.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "otherobjecttype.h"
-
-Collector&
-operator<<(Collector& collector, const OtherObjectType& obj)
-{
- collector << obj.identifier()*2;
- return collector;
-}
-
-int OtherObjectType::enumAsInt(SampleNamespace::SomeClass::PublicScopedEnum value)
-{
- return static_cast<int>(value);
-}
-
-int OtherObjectType::enumAsIntForInvisibleNamespace(Invisible::EnumOnNamespace value)
-{
- return static_cast<int>(value);
-}
diff --git a/sources/shiboken2/tests/libother/otherobjecttype.h b/sources/shiboken2/tests/libother/otherobjecttype.h
deleted file mode 100644
index efd394347..000000000
--- a/sources/shiboken2/tests/libother/otherobjecttype.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OTHEROBJECTTYPE_H
-#define OTHEROBJECTTYPE_H
-
-#include <list>
-#include "str.h"
-
-#include "libothermacros.h"
-#include "objecttype.h"
-#include "collector.h"
-#include "samplenamespace.h"
-
-
-class LIBOTHER_API OtherObjectType : public ObjectType
-{
-public:
- static int enumAsInt(SampleNamespace::SomeClass::PublicScopedEnum value);
- static int enumAsIntForInvisibleNamespace(Invisible::EnumOnNamespace value);
-};
-
-
-LIBOTHER_API Collector& operator<<(Collector&, const OtherObjectType&);
-
-#endif // OTHEROBJECTTYPE_H
-
diff --git a/sources/shiboken2/tests/libother/smartptrtester.cpp b/sources/shiboken2/tests/libother/smartptrtester.cpp
deleted file mode 100644
index 9636c7521..000000000
--- a/sources/shiboken2/tests/libother/smartptrtester.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "smartptrtester.h"
-
-SharedPtr<Str> SmartPtrTester::createSharedPtrStr(const char *what)
-{
- return SharedPtr<Str>(new Str(what));
-}
-
-std::string SmartPtrTester::valueOfSharedPtrStr(const SharedPtr<Str> &str)
-{
- return str->cstring();
-}
-
-SharedPtr<Integer> SmartPtrTester::createSharedPtrInteger(int v)
-{
- auto i = SharedPtr<Integer>(new Integer);
- i->m_int = v;
- return i;
-}
-
-int SmartPtrTester::valueOfSharedPtrInteger(const SharedPtr<Integer> &v)
-{
- return v->m_int;
-}
-
-void SmartPtrTester::fiddleInt(const SharedPtr<int> &) // no binding, should not cause errors
-{
-}
diff --git a/sources/shiboken2/tests/libother/smartptrtester.h b/sources/shiboken2/tests/libother/smartptrtester.h
deleted file mode 100644
index a560bcf2f..000000000
--- a/sources/shiboken2/tests/libother/smartptrtester.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SMARTPTRTESTER_H
-#define SMARTPTRTESTER_H
-
-#include "libothermacros.h"
-
-#include <smart.h>
-#include <str.h>
-
-class LIBOTHER_API SmartPtrTester
-{
-public:
- SharedPtr<Str> createSharedPtrStr(const char *what);
- std::string valueOfSharedPtrStr(const SharedPtr<Str> &);
-
- SharedPtr<Integer> createSharedPtrInteger(int v);
- int valueOfSharedPtrInteger(const SharedPtr<Integer> &);
-
- void fiddleInt(const SharedPtr<int> &);
-};
-
-#endif // SMARTPTRTESTER_H
diff --git a/sources/shiboken2/tests/libsample/CMakeLists.txt b/sources/shiboken2/tests/libsample/CMakeLists.txt
deleted file mode 100644
index ae13cd9f2..000000000
--- a/sources/shiboken2/tests/libsample/CMakeLists.txt
+++ /dev/null
@@ -1,59 +0,0 @@
-project(libsample)
-
-set(libsample_SRC
-abstract.cpp
-blackbox.cpp
-bytearray.cpp
-bucket.cpp
-collector.cpp
-complex.cpp
-onlycopy.cpp
-derived.cpp
-echo.cpp
-exceptiontest.cpp
-functions.cpp
-handle.cpp
-implicitconv.cpp
-injectcode.cpp
-listuser.cpp
-modifications.cpp
-mapuser.cpp
-modified_constructor.cpp
-multiple_derived.cpp
-objectmodel.cpp
-objecttype.cpp
-objecttypeholder.cpp
-objecttypelayout.cpp
-objecttypeoperators.cpp
-objectview.cpp
-overload.cpp
-overloadsort.cpp
-pairuser.cpp
-pen.cpp
-photon.cpp
-point.cpp
-pointf.cpp
-polygon.cpp
-protected.cpp
-reference.cpp
-renaming.cpp
-sample.cpp
-samplenamespace.cpp
-sbkdate.cpp
-simplefile.cpp
-size.cpp
-sometime.cpp
-str.cpp
-strlist.cpp
-templateptr.cpp
-transform.cpp
-virtualmethods.cpp
-expression.cpp
-filter.cpp
-)
-
-add_library(libsample SHARED ${libsample_SRC})
-target_include_directories(libsample PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
-target_compile_definitions(libsample PRIVATE LIBSAMPLE_BUILD)
-set_property(TARGET libsample PROPERTY PREFIX "")
-
diff --git a/sources/shiboken2/tests/libsample/abstract.cpp b/sources/shiboken2/tests/libsample/abstract.cpp
deleted file mode 100644
index e60c792c4..000000000
--- a/sources/shiboken2/tests/libsample/abstract.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "abstract.h"
-#include "objecttype.h"
-
-using namespace std;
-
-const int Abstract::staticPrimitiveField = 0;
-
-Abstract::Abstract(int id) : m_id(id)
-{
- primitiveField = 123;
- valueTypeField = Point(12, 34);
- objectTypeField = nullptr;
- bitField = 0;
-}
-
-Abstract::~Abstract()
-{
-}
-
-void
-Abstract::unpureVirtual()
-{
-}
-
-void
-Abstract::callUnpureVirtual()
-{
- this->unpureVirtual();
-}
-
-
-void
-Abstract::callPureVirtual()
-{
- this->pureVirtual();
-}
-
-void
-Abstract::show(PrintFormat format)
-{
- cout << '<';
- switch(format) {
- case Short:
- cout << this;
- break;
- case Verbose:
- cout << "class " << className() << " | cptr: " << this;
- cout << ", id: " << m_id;
- break;
- case OnlyId:
- cout << "id: " << m_id;
- break;
- case ClassNameAndId:
- cout << className() << " - id: " << m_id;
- break;
- }
- cout << '>';
-}
-
-void Abstract::callVirtualGettingEnum(PrintFormat p)
-{
- virtualGettingAEnum(p);
-}
-
-void Abstract::virtualGettingAEnum(Abstract::PrintFormat p)
-{
-}
-
diff --git a/sources/shiboken2/tests/libsample/abstract.h b/sources/shiboken2/tests/libsample/abstract.h
deleted file mode 100644
index 09906f1ee..000000000
--- a/sources/shiboken2/tests/libsample/abstract.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ABSTRACT_H
-#define ABSTRACT_H
-
-#include "libsamplemacros.h"
-#include "point.h"
-#include "complex.h"
-
-class ObjectType;
-
-// this class is not exported to python
-class HideType
-{
-};
-
-class LIBSAMPLE_API Abstract
-{
-private:
- enum PrivateEnum {
- PrivValue0,
- PrivValue1,
- PrivValue2 = PrivValue1 + 2
- };
-public:
- enum PrintFormat {
- Short,
- Verbose,
- OnlyId,
- ClassNameAndId,
- DummyItemToTestPrivateEnum1 = Abstract::PrivValue1,
- DummyItemToTestPrivateEnum2 = PrivValue2,
- };
-
- enum Type {
- TpAbstract, TpDerived
- };
-
- static const int staticPrimitiveField;
- int primitiveField;
- Complex userPrimitiveField;
- Point valueTypeField;
- ObjectType* objectTypeField;
-
- Abstract(int id = -1);
- virtual ~Abstract();
-
- inline int id() { return m_id; }
-
- // factory method
- inline static Abstract* createObject() { return nullptr; }
-
- // method that receives an Object Type
- inline static int getObjectId(Abstract* obj) { return obj->id(); }
-
- virtual void pureVirtual() = 0;
- virtual void* pureVirtualReturningVoidPtr() = 0;
- virtual void unpureVirtual();
-
- virtual PrintFormat returnAnEnum() = 0;
- void callVirtualGettingEnum(PrintFormat p);
- virtual void virtualGettingAEnum(PrintFormat p);
-
- void callPureVirtual();
- void callUnpureVirtual();
-
- void show(PrintFormat format = Verbose);
- virtual Type type() const { return TpAbstract; }
-
- virtual void hideFunction(HideType* arg) = 0;
-
-protected:
- virtual const char* className() { return "Abstract"; }
-
- // Protected bit-field structure member.
- unsigned int bitField: 1;
-
-private:
- virtual void pureVirtualPrivate() = 0;
- int m_id;
-};
-#endif // ABSTRACT_H
diff --git a/sources/shiboken2/tests/libsample/blackbox.cpp b/sources/shiboken2/tests/libsample/blackbox.cpp
deleted file mode 100644
index 0546ba7c2..000000000
--- a/sources/shiboken2/tests/libsample/blackbox.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "blackbox.h"
-
-using namespace std;
-
-BlackBox::~BlackBox()
-{
- // Free all maps.
- while (!m_objects.empty()) {
- delete (*m_objects.begin()).second;
- m_objects.erase(m_objects.begin());
- }
- while (!m_points.empty()) {
- delete (*m_points.begin()).second;
- m_points.erase(m_points.begin());
- }
-}
-
-int
-BlackBox::keepObjectType(ObjectType* object)
-{
- m_ticket++;
- std::pair<int, ObjectType*> item(m_ticket, object);
- m_objects.insert(item);
- object->setParent(nullptr);
-
- return m_ticket;
-}
-
-ObjectType*
-BlackBox::retrieveObjectType(int ticket)
-{
- map<int, ObjectType*>::iterator it = m_objects.find(ticket);
- if (it != m_objects.end()) {
- ObjectType* second = it->second;
- m_objects.erase(it);
- return second;
- }
- return nullptr;
-}
-
-void
-BlackBox::disposeObjectType(int ticket)
-{
- ObjectType* object = retrieveObjectType(ticket);
- if (object)
- delete object;
-}
-
-int
-BlackBox::keepPoint(Point* point)
-{
- m_ticket++;
- std::pair<int, Point*> item(m_ticket, point);
- m_points.insert(item);
-
- return m_ticket;
-}
-
-Point*
-BlackBox::retrievePoint(int ticket)
-{
- map<int, Point*>::iterator it = m_points.find(ticket);
- if (it != m_points.end()) {
- Point* second = it->second;
- m_points.erase(it);
- return second;
- }
- return nullptr;
-}
-
-void
-BlackBox::disposePoint(int ticket)
-{
- Point* point = retrievePoint(ticket);
- if (point)
- delete point;
-}
-
-
-std::list<ObjectType*>
-BlackBox::objects()
-{
- std::list<ObjectType*> l;
- map<int, ObjectType*>::iterator it;
-
- for ( it = m_objects.begin() ; it != m_objects.end(); it++ )
- l.push_back((*it).second);
-
- return l;
-}
-
-std::list<Point*>
-BlackBox::points()
-{
- std::list<Point*> l;
- map<int, Point*>::iterator it;
-
- for ( it = m_points.begin() ; it != m_points.end(); it++ )
- l.push_back((*it).second);
-
- return l;
-}
-
diff --git a/sources/shiboken2/tests/libsample/blackbox.h b/sources/shiboken2/tests/libsample/blackbox.h
deleted file mode 100644
index 629a217cc..000000000
--- a/sources/shiboken2/tests/libsample/blackbox.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef BLACKBOX_H
-#define BLACKBOX_H
-
-#include "libsamplemacros.h"
-#include <map>
-#include "objecttype.h"
-#include "point.h"
-
-class LIBSAMPLE_API BlackBox
-{
-public:
- typedef std::map<int, ObjectType*> ObjectTypeMap;
- typedef std::map<int, Point*> PointMap;
-
- BlackBox() { m_ticket = -1;}
- ~BlackBox();
-
- int keepObjectType(ObjectType* object);
- ObjectType* retrieveObjectType(int ticket);
- void disposeObjectType(int ticket);
-
- int keepPoint(Point* point);
- Point* retrievePoint(int ticket);
- void disposePoint(int ticket);
-
- std::list<ObjectType*> objects();
- std::list<Point*> points();
-
- inline void referenceToValuePointer(Point*&) {}
- inline void referenceToObjectPointer(ObjectType*&) {}
-
-private:
- ObjectTypeMap m_objects;
- PointMap m_points;
- int m_ticket;
-};
-
-#endif // BLACKBOX_H
-
diff --git a/sources/shiboken2/tests/libsample/bucket.cpp b/sources/shiboken2/tests/libsample/bucket.cpp
deleted file mode 100644
index 91e546d6e..000000000
--- a/sources/shiboken2/tests/libsample/bucket.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "bucket.h"
-#include <iostream>
-
-#ifdef _WIN32 // _WIN32 is defined by all Windows 32 and 64 bit compilers, but not by others.
-#include <windows.h>
-#define SLEEP(x) Sleep(x)
-#else
-#include <unistd.h>
-#define SLEEP(x) usleep(x)
-#endif
-
-
-using namespace std;
-
-Bucket::Bucket() : m_locked(false)
-{
-}
-
-void Bucket::push(int x)
-{
- m_data.push_back(x);
-}
-
-int Bucket::pop(void)
-{
- int x = 0;
-
- if (m_data.size() > 0) {
- x = m_data.front();
- m_data.pop_front();
- }
-
- return x;
-}
-
-bool Bucket::empty()
-{
- return m_data.empty();
-}
-
-void Bucket::lock()
-{
- m_locked = true;
- while (m_locked) { SLEEP(300); }
-}
-
-void Bucket::unlock()
-{
- m_locked = false;
-}
-
-bool Bucket::virtualBlockerMethod()
-{
- lock();
- // The return value was added just for diversity sake.
- return true;
-}
-
diff --git a/sources/shiboken2/tests/libsample/bucket.h b/sources/shiboken2/tests/libsample/bucket.h
deleted file mode 100644
index 09f933863..000000000
--- a/sources/shiboken2/tests/libsample/bucket.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef BUCKET_H
-#define BUCKET_H
-
-#include "libsamplemacros.h"
-#include "objecttype.h"
-#include <list>
-
-class ObjectType;
-
-class LIBSAMPLE_API Bucket : public ObjectType
-{
-public:
- Bucket();
- void push(int);
- int pop();
- bool empty();
- void lock();
- inline bool locked() { return m_locked; }
- void unlock();
-
- virtual bool virtualBlockerMethod();
- inline bool callVirtualBlockerMethodButYouDontKnowThis() { return virtualBlockerMethod(); }
-
-private:
- std::list<int> m_data;
-
- volatile bool m_locked;
-};
-
-#endif // BUCKET_H
-
diff --git a/sources/shiboken2/tests/libsample/bytearray.cpp b/sources/shiboken2/tests/libsample/bytearray.cpp
deleted file mode 100644
index 021d2a079..000000000
--- a/sources/shiboken2/tests/libsample/bytearray.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <cstring>
-#include "bytearray.h"
-
-ByteArray::ByteArray()
-{
- m_data = std::vector<char>(1);
- m_data[0] = '\0';
-}
-
-ByteArray::ByteArray(char c)
-{
- m_data = std::vector<char>(2);
- m_data[0] = c;
- m_data[1] = '\0';
-}
-
-ByteArray::ByteArray(const char* data)
-{
- size_t len = strlen(data);
- m_data = std::vector<char>(len + 1);
- memcpy(&m_data[0], data, len);
- m_data[len] = '\0';
-}
-
-ByteArray::ByteArray(const char* data, int len)
-{
- m_data = std::vector<char>(len + 1);
- memcpy(&m_data[0], data, len);
- m_data[len] = '\0';
-}
-
-ByteArray::ByteArray(const ByteArray& other)
-{
- m_data = std::vector<char>(other.size() + 1);
- memcpy(&m_data[0], &other.m_data[0], other.size());
- m_data[other.size()] = '\0';
-}
-
-int
-ByteArray::size() const
-{
- return m_data.size() - 1;
-}
-
-char
-ByteArray::at(int pos) const
-{
- return m_data[pos];
-}
-
-const char*
-ByteArray::data() const
-{
- return &(m_data[0]);
-}
-
-ByteArray&
-ByteArray::append(char c)
-{
- m_data.pop_back();
- m_data.push_back(c);
- m_data.push_back('\0');
- return *this;
-}
-
-ByteArray&
-ByteArray::append(const char* data)
-{
- m_data.pop_back();
- for (int i = 0; i < (int)strlen(data); ++i)
- m_data.push_back(data[i]);
- m_data.push_back('\0');
- return *this;
-}
-
-ByteArray&
-ByteArray::append(const char* data, int len)
-{
- m_data.pop_back();
- for (int i = 0; i < len; ++i)
- m_data.push_back(data[i]);
- m_data.push_back('\0');
- return *this;
-}
-
-ByteArray&
-ByteArray::append(const ByteArray& other)
-{
- m_data.pop_back();
- for (int i = 0; i < (int)other.m_data.size(); ++i)
- m_data.push_back(other.m_data[i]);
- m_data.push_back('\0');
- return *this;
-}
-
-static bool compare(const std::vector<char>& mine, const char* other)
-{
- for (int i = 0; i < (int)mine.size() - 1; ++i) {
- if (mine[i] != other[i])
- return false;
- }
- return true;
-}
-
-bool
-ByteArray::operator==(const ByteArray& other) const
-{
- return compare(m_data, &other.m_data[0]);
-}
-bool
-operator==(const ByteArray& ba1, const char* ba2)
-{
- return compare(ba1.m_data, ba2);
-}
-bool
-operator==(const char* ba1, const ByteArray& ba2)
-{
- return compare(ba2.m_data, ba1);
-}
-
-bool
-ByteArray::operator!=(const ByteArray& other) const
-{
- return !(m_data == other.m_data);
-}
-bool
-operator!=(const ByteArray& ba1, const char* ba2)
-{
- return !(ba1 == ba2);
-}
-bool
-operator!=(const char* ba1, const ByteArray& ba2)
-{
- return !(ba1 == ba2);
-}
-
-ByteArray&
-ByteArray::operator+=(char c)
-{
- return append(c);
-}
-ByteArray&
-ByteArray::operator+=(const char* data)
-{
- return append(data);
-}
-ByteArray&
-ByteArray::operator+=(const ByteArray& other)
-{
- return append(other);
-}
-
-ByteArray
-operator+(const ByteArray& ba1, const ByteArray& ba2)
-{
- return ByteArray(ba1) += ba2;
-}
-ByteArray
-operator+(const ByteArray& ba1, const char* ba2)
-{
- return ByteArray(ba1) += ByteArray(ba2);
-}
-ByteArray
-operator+(const char* ba1, const ByteArray& ba2)
-{
- return ByteArray(ba1) += ba2;
-}
-ByteArray
-operator+(const ByteArray& ba1, char ba2)
-{
- return ByteArray(ba1) += ByteArray(ba2);
-}
-ByteArray
-operator+(char ba1, const ByteArray& ba2)
-{
- return ByteArray(ba1) += ba2;
-}
-
-unsigned int
-ByteArray::hash(const ByteArray& byteArray)
-{
- unsigned int result = 0;
- for (int i = 0; i < (int)byteArray.m_data.size(); ++i)
- result = 5 * result + byteArray.m_data[i];
- return result;
-}
diff --git a/sources/shiboken2/tests/libsample/bytearray.h b/sources/shiboken2/tests/libsample/bytearray.h
deleted file mode 100644
index 5dfb63fd5..000000000
--- a/sources/shiboken2/tests/libsample/bytearray.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef BYTEARRAY_H
-#define BYTEARRAY_H
-
-#include "str.h"
-#include "libsamplemacros.h"
-#include <vector>
-
-class LIBSAMPLE_API ByteArray
-{
-public:
- ByteArray();
- ByteArray(char data);
- ByteArray(const char* data);
- ByteArray(const char* data, int len);
- ByteArray(const ByteArray& other);
-
- int size() const;
- char at(int i) const;
- char operator[](int i) const;
-
- const char* data() const;
-
- ByteArray& append(char c);
- ByteArray& append(const char* data);
- ByteArray& append(const char* data, int len);
- ByteArray& append(const ByteArray& other);
-
- bool operator==(const ByteArray& other) const;
- bool operator!=(const ByteArray& other) const;
-
- ByteArray& operator+=(char c);
- ByteArray& operator+=(const char* data);
- ByteArray& operator+=(const ByteArray& other);
-
- static unsigned int hash(const ByteArray& byteArray);
-private:
- std::vector<char> m_data;
- friend LIBSAMPLE_API bool operator==(const ByteArray& ba1, const char* ba2);
- friend LIBSAMPLE_API bool operator==(const char* ba1, const ByteArray& ba2);
- friend LIBSAMPLE_API bool operator!=(const ByteArray& ba1, const char* ba2);
- friend LIBSAMPLE_API bool operator!=(const char* ba1, const ByteArray& ba2);
-
- friend LIBSAMPLE_API ByteArray operator+(const ByteArray& ba1, const ByteArray& ba2);
- friend LIBSAMPLE_API ByteArray operator+(const ByteArray& ba1, const char* ba2);
- friend LIBSAMPLE_API ByteArray operator+(const char* ba1, const ByteArray& ba2);
- friend LIBSAMPLE_API ByteArray operator+(const ByteArray& ba1, char ba2);
- friend LIBSAMPLE_API ByteArray operator+(char ba1, const ByteArray& ba2);
-};
-
-LIBSAMPLE_API bool operator==(const ByteArray& ba1, const char* ba2);
-LIBSAMPLE_API bool operator==(const char* ba1, const ByteArray& ba2);
-LIBSAMPLE_API bool operator!=(const ByteArray& ba1, const char* ba2);
-LIBSAMPLE_API bool operator!=(const char* ba1, const ByteArray& ba2);
-
-LIBSAMPLE_API ByteArray operator+(const ByteArray& ba1, const ByteArray& ba2);
-LIBSAMPLE_API ByteArray operator+(const ByteArray& ba1, const char* ba2);
-LIBSAMPLE_API ByteArray operator+(const char* ba1, const ByteArray& ba2);
-LIBSAMPLE_API ByteArray operator+(const ByteArray& ba1, char ba2);
-LIBSAMPLE_API ByteArray operator+(char ba1, const ByteArray& ba2);
-
-#endif // BYTEARRAY_H
diff --git a/sources/shiboken2/tests/libsample/collector.cpp b/sources/shiboken2/tests/libsample/collector.cpp
deleted file mode 100644
index 398f79918..000000000
--- a/sources/shiboken2/tests/libsample/collector.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "collector.h"
-
-void Collector::clear()
-{
- m_items.clear();
-}
-
-Collector& Collector::operator<<(ObjectType::Identifier item)
-{
- m_items.push_back(item);
- return *this;
-}
-
-Collector& Collector::operator<<(const ObjectType *obj)
-{
- m_items.push_back(obj->identifier());
- return *this;
-}
-
-std::list<ObjectType::Identifier> Collector::items()
-{
- return m_items;
-}
-
-int Collector::size()
-{
- return (int) m_items.size();
-}
-
-Collector &operator<<(Collector &s, const IntWrapper &w)
-{
- s << w.value;
- return s;
-}
diff --git a/sources/shiboken2/tests/libsample/collector.h b/sources/shiboken2/tests/libsample/collector.h
deleted file mode 100644
index 6d51c624c..000000000
--- a/sources/shiboken2/tests/libsample/collector.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef COLLECTOR_H
-#define COLLECTOR_H
-
-#include <list>
-#include "libsamplemacros.h"
-
-#include "objecttype.h"
-
-class LIBSAMPLE_API Collector
-{
-public:
- Collector() {}
- virtual ~Collector() {}
-
- void clear();
-
- Collector& operator<<(ObjectType::Identifier item);
-
- Collector& operator<<(const ObjectType *);
-
- std::list<ObjectType::Identifier> items();
- int size();
-
-private:
- std::list<ObjectType::Identifier> m_items;
-
- Collector(const Collector&);
- Collector& operator=(const Collector&);
-};
-
-/* Helper for testing external operators */
-class IntWrapper
-{
-public:
- IntWrapper(int x=0):value(x){}
-
- int value;
-};
-
-LIBSAMPLE_API Collector &operator<<(Collector&, const IntWrapper&);
-
-#endif // COLLECTOR_H
-
diff --git a/sources/shiboken2/tests/libsample/complex.cpp b/sources/shiboken2/tests/libsample/complex.cpp
deleted file mode 100644
index a9b7f03c3..000000000
--- a/sources/shiboken2/tests/libsample/complex.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "complex.h"
-
-using namespace std;
-
-Complex::Complex(double real, double imag)
- : m_real(real), m_imag(imag)
-{
-}
-
-Complex
-Complex::operator+(Complex& other)
-{
- Complex result;
- result.setReal(m_real + other.real());
- result.setImaginary(m_imag + other.imag());
- return result;
-}
-
-void
-Complex::show()
-{
- cout << "(real: " << m_real << ", imag: " << m_imag << ")";
-}
-
-
diff --git a/sources/shiboken2/tests/libsample/complex.h b/sources/shiboken2/tests/libsample/complex.h
deleted file mode 100644
index d0f6c1408..000000000
--- a/sources/shiboken2/tests/libsample/complex.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef COMPLEX_H
-#define COMPLEX_H
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API Complex
-{
-public:
- Complex(double real = 0.0, double imag = 0.0);
- ~Complex() {}
-
- inline double real() const { return m_real; }
- inline void setReal(double real) { m_real = real; }
- inline double imag() const { return m_imag; }
- inline void setImaginary(double imag) { m_imag = imag; }
-
- Complex operator+(Complex& other);
-
- void show();
-
-private:
- double m_real;
- double m_imag;
-};
-
-#endif // COMPLEX_H
-
diff --git a/sources/shiboken2/tests/libsample/ctorconvrule.h b/sources/shiboken2/tests/libsample/ctorconvrule.h
deleted file mode 100644
index ceab8d6dc..000000000
--- a/sources/shiboken2/tests/libsample/ctorconvrule.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CTORCONVRULE_H
-#define CTORCONVRULE_H
-
-#include "libsamplemacros.h"
-
-class CtorConvRule
-{
-public:
- explicit CtorConvRule(long value) : m_value(value) {}
- virtual ~CtorConvRule() {}
- virtual void dummyVirtualMethod() {}
- long value() { return m_value; }
-private:
- long m_value;
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/cvlist.h b/sources/shiboken2/tests/libsample/cvlist.h
deleted file mode 100644
index 50ad8bfe8..000000000
--- a/sources/shiboken2/tests/libsample/cvlist.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef CONSTVALUELIST_H
-#define CONSTVALUELIST_H
-
-#include <list>
-#include "libsamplemacros.h"
-
-class CVValueType
-{
- CVValueType();
-};
-
-typedef std::list<const CVValueType*> const_ptr_value_list;
-
-// This tests binding generation for a container of a const value type. The
-// class doesn't need to do anything; this is just to verify that the generated
-// binding code (the container conversion in particular) is const-valid.
-
-class CVListUser
-{
-public:
- static const_ptr_value_list produce() { return const_ptr_value_list(); }
- static void consume(const const_ptr_value_list& l) { (void)l; }
-};
-
-#endif // LIST_H
diff --git a/sources/shiboken2/tests/libsample/derived.cpp b/sources/shiboken2/tests/libsample/derived.cpp
deleted file mode 100644
index 0dc026876..000000000
--- a/sources/shiboken2/tests/libsample/derived.cpp
+++ /dev/null
@@ -1,125 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "derived.h"
-
-using namespace std;
-
-Derived::Derived(int id) : Abstract(id)
-{
-}
-
-Derived::~Derived()
-{
-}
-
-Abstract*
-Derived::createObject()
-{
- static int id = 100;
- return new Derived(id++);
-}
-
-void
-Derived::pureVirtual()
-{
-}
-
-void*
-Derived::pureVirtualReturningVoidPtr()
-{
- return nullptr;
-}
-
-void
-Derived::unpureVirtual()
-{
-}
-
-bool
-Derived::singleArgument(bool b)
-{
- return !b;
-}
-
-double
-Derived::defaultValue(int n)
-{
- return ((double) n) + 0.1;
-}
-
-OverloadedFuncEnum
-Derived::overloaded(int i, int d)
-{
- return OverloadedFunc_ii;
-}
-
-OverloadedFuncEnum
-Derived::overloaded(double n)
-{
- return OverloadedFunc_d;
-}
-
-Derived::OtherOverloadedFuncEnum
-Derived::otherOverloaded(int a, int b, bool c, double d)
-{
- return OtherOverloadedFunc_iibd;
-}
-
-Derived::OtherOverloadedFuncEnum
-Derived::otherOverloaded(int a, double b)
-{
- return OtherOverloadedFunc_id;
-}
-
-struct SecretClass : public Abstract {
- virtual void pureVirtual() {}
- virtual void *pureVirtualReturningVoidPtr() { return nullptr; }
- virtual PrintFormat returnAnEnum() { return Short; }
- void hideFunction(HideType*){};
-private:
- virtual void pureVirtualPrivate() {}
-};
-
-Abstract* Derived::triggerImpossibleTypeDiscovery()
-{
- return new SecretClass;
-}
-
-struct AnotherSecretClass : public Derived {
-};
-
-Abstract* Derived::triggerAnotherImpossibleTypeDiscovery()
-{
- return new AnotherSecretClass;
-}
-
-void Derived::pureVirtualPrivate()
-{
-}
diff --git a/sources/shiboken2/tests/libsample/derived.h b/sources/shiboken2/tests/libsample/derived.h
deleted file mode 100644
index 783a6dc50..000000000
--- a/sources/shiboken2/tests/libsample/derived.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DERIVED_H
-#define DERIVED_H
-
-#include "libsamplemacros.h"
-#include "abstract.h"
-
-enum OverloadedFuncEnum {
- OverloadedFunc_ii,
- OverloadedFunc_d
-};
-
-class LIBSAMPLE_API Derived : public Abstract
-{
-public:
- enum OtherOverloadedFuncEnum {
- OtherOverloadedFunc_iibd,
- OtherOverloadedFunc_id
- };
-
- class SomeInnerClass {
- public:
- void uselessMethod() {}
- SomeInnerClass operator+(const SomeInnerClass& other) { return other; }
- bool operator==(const SomeInnerClass& other) { return true; }
- };
-
- Derived(int id = -1);
- ~Derived() override;
- void pureVirtual() override;
- void* pureVirtualReturningVoidPtr() override;
- void unpureVirtual() override;
-
- PrintFormat returnAnEnum() override { return Short; }
- Type type() const override { return TpDerived; }
-
- // factory method
- static Abstract* createObject();
-
- // single argument
- bool singleArgument(bool b);
-
- // method with default value
- double defaultValue(int n = 0);
-
- // overloads
- OverloadedFuncEnum overloaded(int i = 0, int d = 0);
- OverloadedFuncEnum overloaded(double n);
-
- // more overloads
- OtherOverloadedFuncEnum otherOverloaded(int a, int b, bool c, double d);
- OtherOverloadedFuncEnum otherOverloaded(int a, double b);
-
- inline SomeInnerClass returnMyParameter(const SomeInnerClass& s) { return s; }
-
- static Abstract* triggerImpossibleTypeDiscovery();
- static Abstract* triggerAnotherImpossibleTypeDiscovery();
-
- void hideFunction(HideType*) override {}
-protected:
- const char* getClassName() { return className(); }
- virtual const char* className() override { return "Derived"; }
-
-private:
- void pureVirtualPrivate() override;
-};
-#endif // DERIVED_H
-
diff --git a/sources/shiboken2/tests/libsample/echo.cpp b/sources/shiboken2/tests/libsample/echo.cpp
deleted file mode 100644
index 55e2a461e..000000000
--- a/sources/shiboken2/tests/libsample/echo.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "echo.h"
diff --git a/sources/shiboken2/tests/libsample/echo.h b/sources/shiboken2/tests/libsample/echo.h
deleted file mode 100644
index 3f645694a..000000000
--- a/sources/shiboken2/tests/libsample/echo.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ECHO_H
-#define ECHO_H
-
-#include "libsamplemacros.h"
-#include "str.h"
-
-class ObjectType;
-
-class Echo
-{
-public:
- Echo(){}
- ~Echo(){}
-
- void doNothingWithConstBool(const bool hi) {}
- void methodWithNamedArg(const Str& string = Str("")) {}
-
- Str operator()(const Str& s, const int i) { return s + i; }
-
- // These method are here just for compilation test purposes
- Echo& operator<<(unsigned int item) { return *this; }
- Echo& operator<<(signed int item) { return *this; }
- Echo& operator<<(const ObjectType* item) { return *this; }
- Echo& operator<<(Str str) { return *this; }
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/exceptiontest.cpp b/sources/shiboken2/tests/libsample/exceptiontest.cpp
deleted file mode 100644
index 1302a8e43..000000000
--- a/sources/shiboken2/tests/libsample/exceptiontest.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "exceptiontest.h"
-
-class TestException : public std::exception
-{
-public:
- const char *what() const noexcept override
- { return "TestException"; }
-};
-
-ExceptionTest::ExceptionTest() = default;
-
-int ExceptionTest::intThrowStdException(bool doThrow)
-{
- if (doThrow)
- throw TestException();
- return 1;
-}
-
-void ExceptionTest::voidThrowStdException(bool doThrow)
-{
- if (doThrow)
- throw TestException();
-}
-
-int ExceptionTest::intThrowInt(bool doThrow)
-{
- if (doThrow)
- throw 42;
- return 1;
-}
-
-void ExceptionTest::voidThrowInt(bool doThrow)
-{
- if (doThrow)
- throw 42;
-}
diff --git a/sources/shiboken2/tests/libsample/exceptiontest.h b/sources/shiboken2/tests/libsample/exceptiontest.h
deleted file mode 100644
index 8ab3e2b67..000000000
--- a/sources/shiboken2/tests/libsample/exceptiontest.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef EXCEPTIONTEST_H
-#define EXCEPTIONTEST_H
-
-#include "libsamplemacros.h"
-
-#include <exception>
-
-class LIBSAMPLE_API ExceptionTest
-{
- public:
- ExceptionTest();
-
- int intThrowStdException(bool doThrow);
- void voidThrowStdException(bool doThrow);
-
- int intThrowInt(bool doThrow);
- void voidThrowInt(bool doThrow);
-};
-
-#endif // EXCEPTIONTEST_H
diff --git a/sources/shiboken2/tests/libsample/expression.cpp b/sources/shiboken2/tests/libsample/expression.cpp
deleted file mode 100644
index 0c255a659..000000000
--- a/sources/shiboken2/tests/libsample/expression.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "expression.h"
-#include <sstream>
-
-Expression::Expression() : m_value(0), m_operation(None), m_operand1(nullptr), m_operand2(nullptr)
-{
-}
-
-Expression::Expression(int number) : m_value(number), m_operation(None), m_operand1(nullptr), m_operand2(nullptr)
-{
-}
-
-Expression::Expression(const Expression& other)
-{
- m_operand1 = other.m_operand1 ? new Expression(*other.m_operand1) : nullptr;
- m_operand2 = other.m_operand2 ? new Expression(*other.m_operand2) : nullptr;
- m_value = other.m_value;
- m_operation = other.m_operation;
-}
-
-Expression& Expression::operator=(const Expression& other)
-{
- delete m_operand1;
- delete m_operand2;
- m_operand1 = other.m_operand1 ? new Expression(*other.m_operand1) : nullptr;
- m_operand2 = other.m_operand2 ? new Expression(*other.m_operand2) : nullptr;
- m_operation = other.m_operation;
- m_value = other.m_value;
- return *this;
-}
-
-Expression::~Expression()
-{
- delete m_operand1;
- delete m_operand2;
-}
-
-Expression Expression::operator+(const Expression& other)
-{
- Expression expr;
- expr.m_operation = Add;
- expr.m_operand1 = new Expression(*this);
- expr.m_operand2 = new Expression(other);
- return expr;
-}
-
-Expression Expression::operator-(const Expression& other)
-{
- Expression expr;
- expr.m_operation = Add;
- expr.m_operand1 = new Expression(*this);
- expr.m_operand2 = new Expression(other);
- return expr;
-}
-
-Expression Expression::operator<(const Expression& other)
-{
- Expression expr;
- expr.m_operation = LessThan;
- expr.m_operand1 = new Expression(*this);
- expr.m_operand2 = new Expression(other);
- return expr;
-}
-
-Expression Expression::operator>(const Expression& other)
-{
- Expression expr;
- expr.m_operation = GreaterThan;
- expr.m_operand1 = new Expression(*this);
- expr.m_operand2 = new Expression(other);
- return expr;
-}
-
-std::string Expression::toString() const
-{
- if (m_operation == None) {
- std::ostringstream s;
- s << m_value;
- return s.str();
- }
-
- std::string result;
- result += '(';
- result += m_operand1->toString();
- char op;
- switch (m_operation) {
- case Add:
- op = '+';
- break;
- case Sub:
- op = '-';
- break;
- case LessThan:
- op = '<';
- break;
- case GreaterThan:
- op = '<';
- break;
- case None: // just to avoid the compiler warning
- default:
- op = '?';
- break;
- }
- result += op;
- result += m_operand2->toString();
- result += ')';
- return result;
-}
-
diff --git a/sources/shiboken2/tests/libsample/expression.h b/sources/shiboken2/tests/libsample/expression.h
deleted file mode 100644
index 3add5572e..000000000
--- a/sources/shiboken2/tests/libsample/expression.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef EXPRESSION_H
-#define EXPRESSION_H
-
-#include "libsamplemacros.h"
-#include <string>
-
-class LIBSAMPLE_API Expression
-{
-public:
- enum Operation {
- None, Add, Sub, LessThan, GreaterThan
- };
-
- Expression(int number);
- Expression(const Expression& other);
- Expression& operator=(const Expression& other);
-
- ~Expression();
-
- Expression operator>(const Expression& other);
- Expression operator<(const Expression& other);
- Expression operator+(const Expression& other);
- Expression operator-(const Expression& other);
-
- std::string toString() const;
-private:
- int m_value;
- Operation m_operation;
- Expression* m_operand1;
- Expression* m_operand2;
-
- Expression();
-};
-
-#endif // EXPRESSION_H
diff --git a/sources/shiboken2/tests/libsample/filter.cpp b/sources/shiboken2/tests/libsample/filter.cpp
deleted file mode 100644
index f862babd2..000000000
--- a/sources/shiboken2/tests/libsample/filter.cpp
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <string>
-#include "filter.h"
-Data::Data(Field field, std::string value)
- : m_field(field), m_value(value)
-{
-}
-
-Union::Union(const Data& filter)
-{
- m_filters.push_back(filter);
-}
-
-Union::Union(const Intersection& filter)
-{
- m_filters.push_back(filter);
-}
-
-Union::Union(const Union& filter)
-{
- m_filters = filter.filters();
-}
-
-Intersection::Intersection(const Data& filter)
-{
- m_filters.push_back(filter);
-}
-
-Intersection::Intersection(const Union& filter)
-{
- m_filters.push_back(filter);
-}
-
-Intersection::Intersection(const Intersection& filter)
-{
- m_filters = filter.filters();
-}
-
-Intersection operator&(const Intersection& a, const Intersection& b)
-{
- Intersection filter;
- filter.addFilter(a);
- filter.addFilter(b);
-
- return filter;
-}
diff --git a/sources/shiboken2/tests/libsample/filter.h b/sources/shiboken2/tests/libsample/filter.h
deleted file mode 100644
index e318cba20..000000000
--- a/sources/shiboken2/tests/libsample/filter.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef FILTER_H
-#define FILTER_H
-
-#include <string>
-#include <list>
-
-#include "libsamplemacros.h"
-
-class Intersection;
-
-class LIBSAMPLE_API Filter
-{
-};
-
-class LIBSAMPLE_API Data : public Filter
-{
-
-public:
- enum Field {
- Name,
- Album,
- Year
- };
-
- Data(Field field, std::string value);
-
- Field field() const { return m_field; }
- std::string value() const { return m_value; }
-
-private:
- Field m_field;
- std::string m_value;
-};
-
-class LIBSAMPLE_API Union : public Filter
-{
-public:
-
- Union(const Data&);
- Union(const Intersection&);
- Union() {};
- Union(const Union&);
-
- std::list<Filter> filters() const { return m_filters; }
- void addFilter(const Filter& data) { m_filters.push_back(data); }
-
-private:
- std::list<Filter> m_filters;
-};
-
-class LIBSAMPLE_API Intersection : public Filter
-{
-public:
-
- Intersection(const Data&);
- Intersection(const Union&);
- Intersection() {};
- Intersection(const Intersection&);
-
- std::list<Filter> filters() const { return m_filters; }
- void addFilter(const Filter& data) { m_filters.push_back(data); }
-
-private:
- std::list<Filter> m_filters;
-};
-
-LIBSAMPLE_API Intersection operator&(const Intersection& a, const Intersection& b);
-
-#endif // FILTER_H
-
-
diff --git a/sources/shiboken2/tests/libsample/functions.cpp b/sources/shiboken2/tests/libsample/functions.cpp
deleted file mode 100644
index 288fa96ee..000000000
--- a/sources/shiboken2/tests/libsample/functions.cpp
+++ /dev/null
@@ -1,255 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "functions.h"
-#include <string.h>
-#include <algorithm>
-#include <iostream>
-#include <numeric>
-
-using namespace std;
-
-void
-printSomething()
-{
- cout << __FUNCTION__ << endl;
-}
-
-int
-gimmeInt()
-{
- static int val = 2;
- val = val * 1.3;
- return val;
-}
-
-double
-gimmeDouble()
-{
- static double val = 7.77;
- val = val * 1.3;
- return val;
-}
-
-std::list<Complex>
-gimmeComplexList()
-{
- std::list<Complex> lst;
- lst.push_back(Complex());
- lst.push_back(Complex(1.1, 2.2));
- lst.push_back(Complex(1.3, 2.4));
- return lst;
-}
-
-Complex
-sumComplexPair(std::pair<Complex, Complex> cpx_pair)
-{
- return cpx_pair.first + cpx_pair.second;
-}
-
-double
-multiplyPair(std::pair<double, double> pair)
-{
- return pair.first * pair.second;
-}
-
-int
-countCharacters(const char* text)
-{
- if (!text)
- return -1;
- int count;
- for(count = 0; text[count] != '\0'; count++)
- ;
- return count;
-}
-
-char*
-makeCString()
-{
- char* string = new char[strlen(__FUNCTION__) + 1];
- strcpy(string, __FUNCTION__);
- return string;
-}
-
-const char*
-returnCString()
-{
- return __FUNCTION__;
-}
-
-GlobalOverloadFuncEnum
-overloadedFunc(int val)
-{
- return GlobalOverloadFunc_i;
-}
-
-GlobalOverloadFuncEnum
-overloadedFunc(double val)
-{
- return GlobalOverloadFunc_d;
-}
-
-char*
-returnNullPrimitivePointer()
-{
- return nullptr;
-}
-
-ObjectType*
-returnNullObjectTypePointer()
-{
- return nullptr;
-}
-
-Event*
-returnNullValueTypePointer()
-{
- return nullptr;
-}
-
-unsigned int
-doubleUnsignedInt(unsigned int value)
-{
- return value * 2;
-}
-
-long long
-doubleLongLong(long long value)
-{
- return value * 2;
-}
-
-unsigned long long
-doubleUnsignedLongLong(unsigned long long value)
-{
- return value * 2;
-}
-
-short
-doubleShort(short value)
-{
- return value * 2;
-}
-
-int
-acceptInt(int x)
-{
- return x;
-}
-
-unsigned int
-acceptUInt(unsigned int x)
-{
- return x;
-}
-
-long
-acceptLong(long x)
-{
- return x;
-}
-
-unsigned long
-acceptULong(unsigned long x)
-{
- return x;
-}
-
-double
-acceptDouble(double x)
-{
- return x;
-}
-
-int
-acceptIntReference(int& x)
-{
- return x;
-}
-
-OddBool
-acceptOddBoolReference(OddBool& x)
-{
- return x;
-}
-
-int sumIntArray(int array[4])
-{
- return std::accumulate(array, array + 4, 0);
-}
-
-double sumDoubleArray(double array[4])
-{
- return std::accumulate(array, array + 4, double(0));
-}
-
-int sumIntMatrix(int m[2][3])
-{
- int result = 0;
- for (int r = 0; r < 2; ++r) {
- for (int c = 0; c < 3; ++c)
- result += m[r][c];
- }
- return result;
-}
-
-double sumDoubleMatrix(double m[2][3])
-{
- double result = 0;
- for (int r = 0; r < 2; ++r) {
- for (int c = 0; c < 3; ++c)
- result += m[r][c];
- }
- return result;
-}
-
-ArrayModifyTest::ArrayModifyTest()
-{
-}
-
-int ArrayModifyTest::sumIntArray(int n, int *array)
-{
- return std::accumulate(array, array + n, 0);
-}
-
-ClassWithFunctionPointer::ClassWithFunctionPointer()
-{
- callFunctionPointer(0, &ClassWithFunctionPointer::doNothing);
-}
-
-void ClassWithFunctionPointer::callFunctionPointer(int dummy, void (*fp)(void *))
-{
- size_t a = dummy;
- fp(reinterpret_cast<void *>(a));
-}
-
-void ClassWithFunctionPointer::doNothing(void *operand)
-{
- (void) operand;
-}
diff --git a/sources/shiboken2/tests/libsample/functions.h b/sources/shiboken2/tests/libsample/functions.h
deleted file mode 100644
index cad8b2a33..000000000
--- a/sources/shiboken2/tests/libsample/functions.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef FUNCTIONS_H
-#define FUNCTIONS_H
-
-#include "libsamplemacros.h"
-#include <list>
-#include <utility>
-#include "oddbool.h"
-#include "complex.h"
-#include "objecttype.h"
-
-enum GlobalEnum {
- NoThing,
- FirstThing,
- SecondThing,
- ThirdThing
-};
-
-enum GlobalOverloadFuncEnum {
- GlobalOverloadFunc_i,
- GlobalOverloadFunc_d
-};
-
-LIBSAMPLE_API void printSomething();
-LIBSAMPLE_API int gimmeInt();
-LIBSAMPLE_API double gimmeDouble();
-LIBSAMPLE_API double multiplyPair(std::pair<double, double> pair);
-LIBSAMPLE_API std::list<Complex> gimmeComplexList();
-LIBSAMPLE_API Complex sumComplexPair(std::pair<Complex, Complex> cpx_pair);
-
-LIBSAMPLE_API int countCharacters(const char* text);
-LIBSAMPLE_API char* makeCString();
-LIBSAMPLE_API const char* returnCString();
-
-LIBSAMPLE_API char* returnNullPrimitivePointer();
-LIBSAMPLE_API ObjectType* returnNullObjectTypePointer();
-LIBSAMPLE_API Event* returnNullValueTypePointer();
-
-// Tests overloading on functions (!methods)
-LIBSAMPLE_API GlobalOverloadFuncEnum overloadedFunc(int val);
-LIBSAMPLE_API GlobalOverloadFuncEnum overloadedFunc(double val);
-
-LIBSAMPLE_API unsigned int doubleUnsignedInt(unsigned int value);
-LIBSAMPLE_API long long doubleLongLong(long long value);
-LIBSAMPLE_API unsigned long long doubleUnsignedLongLong(unsigned long long value);
-LIBSAMPLE_API short doubleShort(short value);
-
-LIBSAMPLE_API int acceptInt(int x);
-LIBSAMPLE_API unsigned int acceptUInt(unsigned int x);
-LIBSAMPLE_API long acceptLong(long x);
-LIBSAMPLE_API unsigned long acceptULong(unsigned long x);
-LIBSAMPLE_API double acceptDouble(double x);
-
-LIBSAMPLE_API int acceptIntReference(int& x);
-LIBSAMPLE_API OddBool acceptOddBoolReference(OddBool& x);
-
-LIBSAMPLE_API int sumIntArray(int array[4]);
-LIBSAMPLE_API double sumDoubleArray(double array[4]);
-LIBSAMPLE_API int sumIntMatrix(int m[2][3]);
-LIBSAMPLE_API double sumDoubleMatrix(double m[2][3]);
-
-class LIBSAMPLE_API ArrayModifyTest
-{
-public:
- ArrayModifyTest();
- int sumIntArray(int n, int *array);
-};
-
-class LIBSAMPLE_API ClassWithFunctionPointer
-{
-public:
- explicit ClassWithFunctionPointer();
- void callFunctionPointer(int dummy, void (*fp)(void *));
- static void doNothing(void *operand);
-};
-
-#endif // FUNCTIONS_H
diff --git a/sources/shiboken2/tests/libsample/handle.cpp b/sources/shiboken2/tests/libsample/handle.cpp
deleted file mode 100644
index 643eac458..000000000
--- a/sources/shiboken2/tests/libsample/handle.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "handle.h"
-
-HANDLE HandleHolder::createHandle()
-{
- return (HANDLE) new OBJ;
-}
-
-bool HandleHolder::compare(HandleHolder* other)
-{
- return other->m_handle == m_handle;
-}
-
-bool HandleHolder::compare2(HandleHolder* other)
-{
- return other->m_handle2 == m_handle2;
-}
diff --git a/sources/shiboken2/tests/libsample/handle.h b/sources/shiboken2/tests/libsample/handle.h
deleted file mode 100644
index 824c28b9a..000000000
--- a/sources/shiboken2/tests/libsample/handle.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef HANDLE_H
-#define HANDLE_H
-
-#include "libsamplemacros.h"
-
-/* See http://bugs.pyside.org/show_bug.cgi?id=1105. */
-namespace Foo {
- using HANDLE = unsigned long;
-}
-
-class LIBSAMPLE_API OBJ
-{
-};
-
-using HANDLE = OBJ *;
-
-class LIBSAMPLE_API HandleHolder
-{
-public:
- explicit HandleHolder(HANDLE ptr = nullptr) : m_handle(ptr) {}
- explicit HandleHolder(Foo::HANDLE val): m_handle2(val) {}
-
- inline void set(HANDLE ptr) { HANDLE tmp; tmp = m_handle; m_handle = tmp; }
- inline void set(const Foo::HANDLE& val) { m_handle2 = val; }
- inline HANDLE handle() { return m_handle; }
- inline Foo::HANDLE handle2() { return m_handle2; }
-
- static HANDLE createHandle();
- bool compare(HandleHolder* other);
- bool compare2(HandleHolder* other);
-
-private:
- HANDLE m_handle;
- Foo::HANDLE m_handle2;
-};
-
-struct LIBSAMPLE_API PrimitiveStruct {};
-using PrimitiveStructPtr = struct PrimitiveStruct *;
-struct LIBSAMPLE_API PrimitiveStructPointerHolder
-{
- PrimitiveStructPtr primitiveStructPtr;
-};
-
-#endif // HANDLE_H
diff --git a/sources/shiboken2/tests/libsample/implicitconv.cpp b/sources/shiboken2/tests/libsample/implicitconv.cpp
deleted file mode 100644
index 88af0d936..000000000
--- a/sources/shiboken2/tests/libsample/implicitconv.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "implicitconv.h"
-
-ImplicitConv
-ImplicitConv::implicitConvCommon(ImplicitConv implicit)
-{
- return implicit;
-}
-
-ImplicitConv
-ImplicitConv::implicitConvDefault(ImplicitConv implicit)
-{
- return implicit;
-}
-
-ImplicitConv::ICOverloadedFuncEnum
-ImplicitConv::implicitConvOverloading(ImplicitConv implicit, int dummyArg)
-{
- return ImplicitConv::OverFunc_Ii;
-}
-
-ImplicitConv::ICOverloadedFuncEnum
-ImplicitConv::implicitConvOverloading(ImplicitConv implicit, bool dummyArg)
-{
- return ImplicitConv::OverFunc_Ib;
-}
-
-ImplicitConv::ICOverloadedFuncEnum
-ImplicitConv::implicitConvOverloading(int dummyArg)
-{
- return ImplicitConv::OverFunc_i;
-}
-
-ImplicitConv::ICOverloadedFuncEnum
-ImplicitConv::implicitConvOverloading(CtorEnum dummyArg)
-{
- return ImplicitConv::OverFunc_C;
-}
-
diff --git a/sources/shiboken2/tests/libsample/implicitconv.h b/sources/shiboken2/tests/libsample/implicitconv.h
deleted file mode 100644
index ea859a1a6..000000000
--- a/sources/shiboken2/tests/libsample/implicitconv.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef IMPLICITCONV_H
-#define IMPLICITCONV_H
-
-#include "libsamplemacros.h"
-#include "null.h"
-
-class ObjectType;
-
-class LIBSAMPLE_API ImplicitConv
-{
-public:
- enum CtorEnum {
- CtorNone,
- CtorOne,
- CtorTwo,
- CtorThree,
- CtorObjectTypeReference,
- CtorPrimitiveType
- };
-
- enum ICOverloadedFuncEnum {
- OverFunc_Ii,
- OverFunc_Ib,
- OverFunc_i,
- OverFunc_C
- };
-
- ImplicitConv() : m_ctorEnum(CtorNone), m_objId(-1), m_value(-1.0) {}
- ImplicitConv(int objId) : m_ctorEnum(CtorOne), m_objId(objId), m_value(-1.0) {}
- ImplicitConv(CtorEnum ctorEnum) : m_ctorEnum(ctorEnum), m_objId(-1), m_value(-1.0) {}
- ImplicitConv(ObjectType&) : m_ctorEnum(CtorObjectTypeReference), m_objId(-1), m_value(-1.0) {}
- ImplicitConv(double value, bool=true) : m_ctorEnum(CtorNone), m_value(value) {}
- ImplicitConv(const Null& null) : m_ctorEnum(CtorPrimitiveType) {}
- ~ImplicitConv() {}
-
- inline CtorEnum ctorEnum() { return m_ctorEnum; }
- inline int objId() { return m_objId; }
- inline double value() { return m_value; }
-
- static ImplicitConv implicitConvCommon(ImplicitConv implicit);
-
- static ImplicitConv implicitConvDefault(ImplicitConv implicit = CtorTwo);
-
- static ICOverloadedFuncEnum implicitConvOverloading(ImplicitConv implicit, int dummyArg);
- static ICOverloadedFuncEnum implicitConvOverloading(ImplicitConv implicit, bool dummyArg);
- static ICOverloadedFuncEnum implicitConvOverloading(int dummyArg);
- static ICOverloadedFuncEnum implicitConvOverloading(CtorEnum dummyArg);
-
-private:
- CtorEnum m_ctorEnum;
- int m_objId;
- double m_value;
-};
-
-#endif // IMPLICITCONV_H
diff --git a/sources/shiboken2/tests/libsample/injectcode.cpp b/sources/shiboken2/tests/libsample/injectcode.cpp
deleted file mode 100644
index b1cf2d26b..000000000
--- a/sources/shiboken2/tests/libsample/injectcode.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "injectcode.h"
-#include <sstream>
-
-using namespace std;
-
-InjectCode::InjectCode()
-{
-}
-
-InjectCode::~InjectCode()
-{
-}
-
-template<typename T>
-const char* InjectCode::toStr(const T& value)
-{
- std::ostringstream s;
- s << value;
- m_valueHolder = s.str();
- return m_valueHolder.c_str();
-}
-
-const char* InjectCode::simpleMethod1(int arg0, int arg1)
-{
- return toStr(arg0 + arg1);
-}
-
-const char* InjectCode::simpleMethod2()
-{
- return "_";
-}
-
-const char* InjectCode::simpleMethod3(int argc, char** argv)
-{
- for (int i = 0; i < argc; ++i)
- m_valueHolder += argv[i];
- return m_valueHolder.c_str();
-}
-
-const char* InjectCode::overloadedMethod(int arg0, bool arg1)
-{
- toStr(arg0);
- m_valueHolder += arg1 ? "true" : "false";
- return m_valueHolder.c_str();
-}
-
-const char* InjectCode::overloadedMethod(int arg0, double arg1)
-{
- return toStr(arg0 + arg1);
-}
-
-const char* InjectCode::overloadedMethod(int argc, char** argv)
-{
- return simpleMethod3(argc, argv);
-}
-
-const char* InjectCode::virtualMethod(int arg)
-{
- return toStr(arg);
-}
-
-int InjectCode::arrayMethod(int count, int *values) const
-{
- int ret = 0;
- for (int i=0; i < count; i++)
- ret += values[i];
- return ret;
-}
-
-int InjectCode::sumArrayAndLength(int* values) const
-{
- int sum = 0;
-
- while(*values) {
- sum = sum + *values + 1;
- values++;
- }
-
- return sum;
-}
diff --git a/sources/shiboken2/tests/libsample/injectcode.h b/sources/shiboken2/tests/libsample/injectcode.h
deleted file mode 100644
index 927721f8f..000000000
--- a/sources/shiboken2/tests/libsample/injectcode.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef INJECTCODE_H
-#define INJECTCODE_H
-
-#include "libsamplemacros.h"
-#include <utility>
-#include <string>
-
-class LIBSAMPLE_API InjectCode
-{
-public:
- InjectCode();
- virtual ~InjectCode();
-
- const char* simpleMethod1(int arg0, int arg1);
- const char* simpleMethod2();
- const char* simpleMethod3(int argc, char** argv);
-
- const char* overloadedMethod(int argc, char** argv);
- const char* overloadedMethod(int arg0, double arg1);
- const char* overloadedMethod(int arg0, bool arg1);
-
- virtual int arrayMethod(int count, int* values) const;
- inline int callArrayMethod(int count, int *values) const { return arrayMethod(count, values); }
- virtual const char* virtualMethod(int arg);
- int sumArrayAndLength(int* values) const;
-private:
- // This attr is just to retain the memory pointed by all return values,
- // So, the memory returned by all methods will be valid until someone call
- // another method of this class.
- std::string m_valueHolder;
-
- template<typename T>
- const char* toStr(const T& value);
-};
-
-#endif // INJECTCODE_H
-
diff --git a/sources/shiboken2/tests/libsample/libsamplemacros.h b/sources/shiboken2/tests/libsample/libsamplemacros.h
deleted file mode 100644
index cda029ab7..000000000
--- a/sources/shiboken2/tests/libsample/libsamplemacros.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef LIBSAMPLEMACROS_H
-#define LIBSAMPLEMACROS_H
-
-#if defined _WIN32 || defined __CYGWIN__
- #if LIBSAMPLE_BUILD
- #define LIBSAMPLE_API __declspec(dllexport)
- #else
- #define LIBSAMPLE_API __declspec(dllimport)
- #endif
-#else
-#if __GNUC__ >= 4
- #define LIBSAMPLE_API __attribute__ ((visibility("default")))
-#else
- #define LIBSAMPLE_API
-#endif
-#endif
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/list.h b/sources/shiboken2/tests/libsample/list.h
deleted file mode 100644
index f4970d947..000000000
--- a/sources/shiboken2/tests/libsample/list.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef LIST_H
-#define LIST_H
-
-#include <list>
-#include "libsamplemacros.h"
-#include "point.h"
-
-class ObjectType;
-
-template<class T>
-class List : public std::list<T>
-{
-};
-
-class IntList : public List<int>
-{
-public:
- enum CtorEnum {
- NoParamsCtor,
- IntCtor,
- CopyCtor,
- ListOfIntCtor
- };
-
- inline IntList() : m_ctorUsed(NoParamsCtor) {}
- inline explicit IntList(int val) : m_ctorUsed(IntCtor) { push_back(val); }
- inline IntList(const IntList& lst) : List<int>(lst), m_ctorUsed(CopyCtor) {}
- inline IntList(const List<int>& lst) : List<int>(lst), m_ctorUsed(ListOfIntCtor) {}
-
- inline void append(int v) { insert(end(), v); }
- CtorEnum constructorUsed() { return m_ctorUsed; }
-private:
- CtorEnum m_ctorUsed;
-};
-
-class PointValueList : public List<Point>
-{
-public:
- enum CtorEnum {
- NoParamsCtor,
- PointCtor,
- CopyCtor,
- ListOfPointValuesCtor
- };
-
- inline PointValueList() : m_ctorUsed(NoParamsCtor) {}
- inline explicit PointValueList(Point val) : m_ctorUsed(PointCtor) { push_back(val); }
- inline PointValueList(const PointValueList& lst) : List<Point>(lst), m_ctorUsed(CopyCtor) {}
- inline PointValueList(const List<Point>& lst) : List<Point>(lst), m_ctorUsed(ListOfPointValuesCtor) {}
-
- inline void append(Point v) { insert(end(), v); }
- CtorEnum constructorUsed() { return m_ctorUsed; }
-private:
- CtorEnum m_ctorUsed;
-};
-
-class ObjectTypePtrList : public List<ObjectType*>
-{
-public:
- enum CtorEnum {
- NoParamsCtor,
- ObjectTypeCtor,
- CopyCtor,
- ListOfObjectTypePtrCtor
- };
-
- inline ObjectTypePtrList() : m_ctorUsed(NoParamsCtor) {}
- inline explicit ObjectTypePtrList(ObjectType* val) : m_ctorUsed(ObjectTypeCtor) { push_back(val); }
- inline ObjectTypePtrList(const ObjectTypePtrList& lst) : List<ObjectType*>(lst), m_ctorUsed(CopyCtor) {}
- inline ObjectTypePtrList(const List<ObjectType*>& lst) : List<ObjectType*>(lst), m_ctorUsed(ListOfObjectTypePtrCtor) {}
-
- inline void append(ObjectType* v) { insert(end(), v); }
- CtorEnum constructorUsed() { return m_ctorUsed; }
-private:
- CtorEnum m_ctorUsed;
-};
-
-#endif // LIST_H
diff --git a/sources/shiboken2/tests/libsample/listuser.cpp b/sources/shiboken2/tests/libsample/listuser.cpp
deleted file mode 100644
index b50ce1e4c..000000000
--- a/sources/shiboken2/tests/libsample/listuser.cpp
+++ /dev/null
@@ -1,91 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <numeric>
-#include <cstdlib>
-#include "listuser.h"
-
-using namespace std;
-
-std::list<int>
-ListUser::callCreateList()
-{
- return createList();
-}
-
-std::list<int>
-ListUser::createList()
-{
- std::list<int> retval;
- for (int i = 0; i < 4; i++)
- retval.push_front(rand());
- return retval;
-}
-
-std::list<Complex>
-ListUser::createComplexList(Complex cpx0, Complex cpx1)
-{
- std::list<Complex> retval;
- retval.push_back(cpx0);
- retval.push_back(cpx1);
- return retval;
-}
-
-double
-ListUser::sumList(std::list<int> vallist)
-{
- return std::accumulate(vallist.begin(), vallist.end(), 0.0);
-}
-
-double
-ListUser::sumList(std::list<double> vallist)
-{
- return std::accumulate(vallist.begin(), vallist.end(), 0.0);
-}
-
-ListUser::ListOfSomething
-ListUser::listOfPoints(const std::list<Point>& pointlist)
-{
- return ListOfPoint;
-}
-
-ListUser::ListOfSomething
-ListUser::listOfPoints(const std::list<PointF>& pointlist)
-{
- return ListOfPointF;
-}
-
-void
-ListUser::multiplyPointList(PointList& points, double multiplier)
-{
- for(PointList::iterator piter = points.begin(); piter != points.end(); piter++) {
- (*piter)->setX((*piter)->x() * multiplier);
- (*piter)->setY((*piter)->y() * multiplier);
- }
-}
-
diff --git a/sources/shiboken2/tests/libsample/listuser.h b/sources/shiboken2/tests/libsample/listuser.h
deleted file mode 100644
index 7e67039d9..000000000
--- a/sources/shiboken2/tests/libsample/listuser.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef LISTUSER_H
-#define LISTUSER_H
-
-#include <list>
-#include "complex.h"
-#include "point.h"
-#include "pointf.h"
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API ListUser
-{
-public:
- using PointList = std::list<Point *>;
-
- enum ListOfSomething {
- ListOfPoint,
- ListOfPointF
- };
-
- ListUser() {}
- ListUser(const ListUser& other) : m_lst(other.m_lst) {}
- virtual ~ListUser() {}
-
- virtual std::list<int> createList();
- std::list<int> callCreateList();
-
- static std::list<Complex> createComplexList(Complex cpx0, Complex cpx1);
-
- double sumList(std::list<int> vallist);
- double sumList(std::list<double> vallist);
-
- static ListOfSomething listOfPoints(const std::list<Point>& pointlist);
- static ListOfSomething listOfPoints(const std::list<PointF>& pointlist);
-
- static void multiplyPointList(PointList& points, double multiplier);
-
- inline void setList(std::list<int> lst) { m_lst = lst; }
- inline std::list<int> getList() { return m_lst; }
-
-private:
- std::list<int> m_lst;
-};
-
-#endif // LISTUSER_H
-
diff --git a/sources/shiboken2/tests/libsample/main.cpp b/sources/shiboken2/tests/libsample/main.cpp
deleted file mode 100644
index 336551ea2..000000000
--- a/sources/shiboken2/tests/libsample/main.cpp
+++ /dev/null
@@ -1,244 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include <list>
-#include "abstract.h"
-#include "derived.h"
-#include "kindergarten.h"
-#include "complex.h"
-#include "point.h"
-#include "size.h"
-#include "listuser.h"
-#include "samplenamespace.h"
-
-using namespace std;
-
-int
-main(int argv, char **argc)
-{
- cout << endl;
-
- Derived derived;
-
- cout << endl;
-
- derived.unpureVirtual();
- derived.pureVirtual();
- derived.callPureVirtual();
-
- cout << endl;
- Abstract* abs;
- abs = Abstract::createObject();
- cout << "Abstract::createObject(): " << abs << endl << endl;
- delete abs;
-
- abs = Derived::createObject();
- cout << "Derived::createObject() : ";
- abs->show();
- cout << endl;
- delete abs;
- cout << endl;
-
- abs = Derived::createObject();
- cout << "Derived::createObject() : ";
- abs->show();
- cout << endl;
- delete abs;
- cout << endl;
-
- cout << endl << "-----------------------------------------" << endl;
-
- KinderGarten kg;
- Derived* d[] = { 0, 0, 0 };
-
- for (int i = 0; i < 3; i++) {
- d[i] = new Derived(i);
- d[i]->show();
- cout << endl;
- kg.addChild(d[i]);
- }
-
- kg.show();
- cout << endl;
-
- cout << endl << "* kill child ";
- d[2]->show();
- cout << " ----------------" << endl;
- kg.killChild(d[2]);
- kg.show();
- cout << endl;
-
- cout << endl << "* release child ";
- d[1]->show();
- cout << " -------------" << endl;
- Abstract* released = kg.releaseChild(d[1]);
- cout << "released: ";
- released->show();
- cout << endl;
- kg.show();
- cout << endl;
-
- cout << endl << "* kill children ------------------------------------" << endl;
- kg.killChildren();
- kg.show();
- cout << endl << endl;
-
- cout << "-----------------------------------------" << endl;
- ListUser lu;
- cout << "ListUser::createList()" << endl;
- std::list<int> intlist = lu.createList();
- for (std::list<int>::iterator it = intlist.begin(); it != intlist.end(); it++) {
- cout << "* " << *it << endl;
- }
-
- cout << "ListUser::createComplexList" << endl;
- std::list<Complex> cpxlist = ListUser::createComplexList(Complex(1.1, 2.2), Complex(3.3, 4.4));
- for (std::list<Complex>::iterator it = cpxlist.begin(); it != cpxlist.end(); it++) {
- cout << "* ";
- (*it).show();
- cout << endl;
- }
- cout << endl;
-
- cout << "-----------------------------------------" << endl;
- cout << "SampleNamespace" << endl;
-
- cout << "SampleNamespace::RandomNumber: ";
- cout << SampleNamespace::getNumber(SampleNamespace::RandomNumber);
- cout << endl;
- cout << "SampleNamespace::UnixTime: ";
- cout << SampleNamespace::getNumber(SampleNamespace::UnixTime);
- cout << endl;
- double val_d = 1.3;
- cout << "SampleNamespace::powerOfTwo(" << val_d << "): ";
- cout << SampleNamespace::powerOfTwo(val_d) << endl;
- int val_i = 7;
- cout << "SampleNamespace::powerOfTwo(" << val_i << "): ";
- cout << SampleNamespace::powerOfTwo(val_i) << endl;
- cout << endl;
-
- cout << "-----------------------------------------" << endl;
- cout << "Point" << endl;
-
- Point p1(1.1, 2.2);
- cout << "p1: ";
- p1.show();
- cout << endl;
-
- Point p2(3.4, 5.6);
- cout << "p2: ";
- p2.show();
- cout << endl;
-
- cout << "p1 + p2 == ";
- (p1 + p2).show();
- cout << endl;
-
- cout << "p1 * 2.0 == ";
- (p1 * 2.0).show();
- cout << endl;
-
- cout << "1.5 * p2 == ";
- (1.5 * p2).show();
- cout << endl;
-
- cout << "p1: ";
- p1.show();
- cout << endl << "p2: ";
- p2.show();
- cout << endl << "p1 += p2" << endl;
- p1 += p2;
- cout << "p1: ";
- p1.show();
- cout << endl;
-
- cout << "p1 == p2 ? " << ((p1 == p2) ? "true" : "false") << endl;
- cout << "p1 == p1 ? " << ((p1 == p1) ? "true" : "false") << endl;
- cout << "p2 == p2 ? " << ((p2 == p2) ? "true" : "false") << endl;
-
- cout << "-----------------------------------------" << endl;
- cout << "Size" << endl;
-
- Size s1(2, 2);
- cout << "s1: ";
- s1.show();
- cout << ", area: " << s1.calculateArea();
- cout << endl;
-
- Size s2(3, 5);
- cout << "s2: ";
- s2.show();
- cout << ", area: " << s2.calculateArea();
- cout << endl;
-
- cout << endl;
-
- cout << "s1 == s2 ? " << ((s1 == s2) ? "true" : "false") << endl;
- cout << "s1 != s2 ? " << ((s1 != s2) ? "true" : "false") << endl;
-
- cout << "s1 < s2 ? " << ((s1 < s2) ? "true" : "false") << endl;
- cout << "s1 <= s2 ? " << ((s1 <= s2) ? "true" : "false") << endl;
- cout << "s1 > s2 ? " << ((s1 > s2) ? "true" : "false") << endl;
- cout << "s1 >= s2 ? " << ((s1 >= s2) ? "true" : "false") << endl;
-
- cout << "s1 < 10 ? " << ((s1 < 10) ? "true" : "false") << endl;
- cout << "s1 <= 10 ? " << ((s1 <= 10) ? "true" : "false") << endl;
- cout << "s1 > 10 ? " << ((s1 > 10) ? "true" : "false") << endl;
- cout << "s1 >= 10 ? " << ((s1 >= 10) ? "true" : "false") << endl;
- cout << "s2 < 10 ? " << ((s2 < 10) ? "true" : "false") << endl;
- cout << "s2 <= 10 ? " << ((s2 <= 10) ? "true" : "false") << endl;
- cout << "s2 > 10 ? " << ((s2 > 10) ? "true" : "false") << endl;
- cout << "s2 >= 10 ? " << ((s2 >= 10) ? "true" : "false") << endl;
- cout << endl;
-
- cout << "s1: ";
- s1.show();
- cout << endl << "s2: ";
- s2.show();
- cout << endl << "s1 += s2" << endl;
- s1 += s2;
- cout << "s1: ";
- s1.show();
- cout << endl;
-
- cout << endl;
-
- cout << "s1: ";
- s1.show();
- cout << endl << "s1 *= 2.0" << endl;
- s1 *= 2.0;
- cout << "s1: ";
- s1.show();
- cout << endl;
-
- cout << endl;
-
- return 0;
-}
-
diff --git a/sources/shiboken2/tests/libsample/mapuser.cpp b/sources/shiboken2/tests/libsample/mapuser.cpp
deleted file mode 100644
index 89a835af8..000000000
--- a/sources/shiboken2/tests/libsample/mapuser.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "mapuser.h"
-
-using namespace std;
-
-std::map<std::string, std::pair<Complex, int> >
-MapUser::callCreateMap()
-{
- return createMap();
-}
-
-
-std::map<std::string, std::pair<Complex, int> >
-MapUser::createMap()
-{
- std::map<std::string, std::pair<Complex, int> > retval;
-
- std::pair<std::string, std::pair<Complex, int> >
- item0("zero", std::pair<Complex, int>(Complex(1.2, 3.4), 2));
- retval.insert(item0);
-
- std::pair<std::string, std::pair<Complex, int> >
- item1("one", std::pair<Complex, int>(Complex(5.6, 7.8), 3));
- retval.insert(item1);
-
- std::pair<std::string, std::pair<Complex, int> >
- item2("two", std::pair<Complex, int>(Complex(9.1, 2.3), 5));
- retval.insert(item2);
-
- return retval;
-}
-
-void
-MapUser::showMap(std::map<std::string, int> mapping)
-{
- std::map<std::string, int>::iterator it;
- cout << __FUNCTION__ << endl;
- for (it = mapping.begin() ; it != mapping.end(); it++)
- cout << (*it).first << " => " << (*it).second << endl;
-}
-
-std::map<int, std::list<std::list<double> > > MapUser::foo() const
-{
- std::map<int, std::list<std::list<double> > > result;
- return result;
-}
diff --git a/sources/shiboken2/tests/libsample/mapuser.h b/sources/shiboken2/tests/libsample/mapuser.h
deleted file mode 100644
index ad434b957..000000000
--- a/sources/shiboken2/tests/libsample/mapuser.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MAPUSER_H
-#define MAPUSER_H
-
-#include <map>
-#include <list>
-#include <utility>
-#include <string>
-#include "complex.h"
-#include "bytearray.h"
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API MapUser
-{
-public:
- MapUser() {}
- virtual ~MapUser() {}
-
- virtual std::map<std::string, std::pair<Complex, int> > createMap();
- std::map<std::string, std::pair<Complex, int> > callCreateMap();
-
- void showMap(std::map<std::string, int> mapping);
-
- inline void setMap(std::map<std::string, std::list<int> > map) { m_map = map; }
- inline std::map<std::string, std::list<int> > getMap() { return m_map; }
-
- // Compile test
- static void pointerToMap(std::map<std::string, std::string>* arg) {}
- static void referenceToMap(std::map<std::string, std::string>& arg) {}
-
- inline const std::map<int, ByteArray>& passMapIntValueType(const std::map<int, ByteArray>& arg) { return arg; }
-
- std::map<int, std::list<std::list<double> > > foo() const;
-
-private:
- std::map<std::string, std::list<int> > m_map;
-};
-
-#endif // MAPUSER_H
diff --git a/sources/shiboken2/tests/libsample/modelindex.h b/sources/shiboken2/tests/libsample/modelindex.h
deleted file mode 100644
index dd3ddc089..000000000
--- a/sources/shiboken2/tests/libsample/modelindex.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MODELINDEX_H
-#define MODELINDEX_H
-
-#include "libsamplemacros.h"
-
-class ModelIndex
-{
-public:
- ModelIndex() : m_value(0) {}
- ModelIndex(const ModelIndex& other) { m_value = other.m_value; }
- inline void setValue(int value) { m_value = value; }
- inline int value() const { return m_value; }
- static int getValue(const ModelIndex& index) { return index.value(); }
-private:
- int m_value;
-};
-
-class ReferentModelIndex
-{
-public:
- ReferentModelIndex() {}
- ReferentModelIndex(const ModelIndex& index) : m_index(index) {}
- ReferentModelIndex(const ReferentModelIndex& other) { m_index = other.m_index; }
- inline void setValue(int value) { m_index.setValue(value); }
- inline int value() const { return m_index.value(); }
- operator const ModelIndex&() const { return m_index; }
-private:
- ModelIndex m_index;
-};
-
-class PersistentModelIndex
-{
-public:
- PersistentModelIndex() {}
- PersistentModelIndex(const ModelIndex& index) : m_index(index) {}
- PersistentModelIndex(const PersistentModelIndex& other) { m_index = other.m_index; }
- inline void setValue(int value) { m_index.setValue(value); }
- inline int value() const { return m_index.value(); }
- operator ModelIndex() const { return m_index; }
-private:
- ModelIndex m_index;
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/modifications.cpp b/sources/shiboken2/tests/libsample/modifications.cpp
deleted file mode 100644
index 627d17b45..000000000
--- a/sources/shiboken2/tests/libsample/modifications.cpp
+++ /dev/null
@@ -1,186 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "modifications.h"
-#include "objecttype.h"
-
-using namespace std;
-
-Modifications::Modifications()
-{
- m_object = new ObjectType();
- m_object->setObjectName("MyObject");
-}
-
-Modifications::~Modifications()
-{
- delete m_object;
-}
-
-std::pair<double, double>
-Modifications::pointToPair(Point pt, bool* ok)
-{
- std::pair<double, double> retval(pt.x(), pt.y());
- *ok = true;
- return retval;
-}
-
-double
-Modifications::multiplyPointCoordsPlusValue(bool* ok, Point pt, double value)
-{
- double retval = (pt.x() * pt.y()) + value;
- *ok = true;
- return retval;
-}
-
-int
-Modifications::doublePlus(int value, int plus)
-{
- return (2 * value) + plus;
-}
-
-int
-Modifications::power(int base, int exponent)
-{
- if (exponent == 0)
- return 1;
- int retval = base;
- for (int i = 1; i < exponent; i++)
- retval = retval * base;
- return retval;
-}
-
-int
-Modifications::timesTen(int number)
-{
- return number * 10;
-}
-
-int
-Modifications::increment(int number)
-{
- return ++number;
-}
-
-void
-Modifications::exclusiveCppStuff()
-{
- cout << __FUNCTION__ << endl;
-}
-
-int
-Modifications::cppMultiply(int a, int b)
-{
- return a * b;
-}
-
-const char*
-Modifications::className()
-{
- return "Modifications";
-}
-
-Point
-Modifications::sumPointArray(int arraySize, const Point pointArray[])
-{
- Point point;
- for (int i = 0; i < arraySize; ++i)
- point = point + pointArray[i];
- return point;
-}
-
-int
-Modifications::getSize(const void* data, int size)
-{
- (void)data;
- return size;
-}
-
-int
-Modifications::sumPointCoordinates(const Point* point)
-{
- return point->x() + point->y();
-}
-
-double
-Modifications::differenceOfPointCoordinates(const Point* pt, bool* ok)
-{
- if (!pt) {
- *ok = false;
- return 0.0;
- }
- *ok = true;
- double result = pt->x() - pt->y();
- if (result < 0)
- result = result * -1.0;
- return result;
-}
-
-bool
-Modifications::nonConversionRuleForArgumentWithDefaultValue(ObjectType** object)
-{
- if (object)
- *object = m_object;
- return true;
-}
-
-void Modifications::setEnumValue(TestEnum e)
-{
- m_enumValue = e;
-}
-
-Modifications::TestEnum Modifications::enumValue() const
-{
- return m_enumValue;
-}
-
-Modifications::TestEnum Modifications::defaultEnumValue() const
-{
- return TestEnumValue2;
-}
-
-bool Modifications::wasGetAttroCalled() const
-{
- return m_getAttroCalled;
-}
-
-void Modifications::notifyGetAttroCalled()
-{
- m_getAttroCalled = true;
-}
-
-bool Modifications::wasSetAttroCalled() const
-{
- return m_setAttroCalled;
-}
-
-void Modifications::notifySetAttroCalled()
-{
- m_setAttroCalled = true;
-}
diff --git a/sources/shiboken2/tests/libsample/modifications.h b/sources/shiboken2/tests/libsample/modifications.h
deleted file mode 100644
index 888c66d18..000000000
--- a/sources/shiboken2/tests/libsample/modifications.h
+++ /dev/null
@@ -1,160 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MODIFICATIONS_H
-#define MODIFICATIONS_H
-
-#include "libsamplemacros.h"
-#include <utility>
-#include "point.h"
-#include "oddbool.h"
-
-class ObjectType;
-
-class LIBSAMPLE_API Modifications
-{
-public:
- Modifications();
- virtual ~Modifications();
-
- enum OverloadedModFunc {
- OverloadedNone,
- Overloaded_ibid,
- Overloaded_ibib,
- Overloaded_ibiP,
- Overloaded_ibii,
- Overloaded_ibPP
- };
-
- enum TestEnum {
- TestEnumValue1,
- TestEnumValue2
- };
-
- // those overloaded methods should be heavily modified
- // to push the overload decisor to its limits
- inline OverloadedModFunc overloaded(int a0, bool b0, int c0, double d0) { return Overloaded_ibid; }
- inline OverloadedModFunc overloaded(int a1, bool b1, int c1, bool d1) { return Overloaded_ibib; }
- inline OverloadedModFunc overloaded(int a2, bool b2, int c2, Point d2) { return Overloaded_ibiP; }
- inline OverloadedModFunc overloaded(int a3, bool b3, int c3 = 123, int d3 = 456) { return Overloaded_ibii; }
- inline OverloadedModFunc overloaded(int a4, bool b4, Point c4, Point d4) { return Overloaded_ibPP; }
-
- inline void argRemoval0(int a0, bool a1, int a2 = 123, int a3 = 456) {}
- inline void argRemoval0(int a0, bool a1, int a2, bool a3) {}
-
- inline void argRemoval1(int a0, bool a1, Point a2 = Point(1, 2), Point a3 = Point(3, 4), int a4 = 333) {}
- inline void argRemoval1(int a0, bool a1, int a2, bool a3) {}
-
- inline void argRemoval2(int a0, bool a1, Point a2 = Point(1, 2), Point a3 = Point(3, 4), int a4 = 333) {}
-
- inline void argRemoval3(int a0, Point a1 = Point(1, 2), bool a2 = true, Point a3 = Point(3, 4), int a4 = 333) {}
-
- inline void argRemoval4(int a0, Point a1, bool a2, Point a3 = Point(3, 4), int a4 = 333) {}
-
- inline void argRemoval5(int a0, bool a1, Point a2 = Point(1, 2), Point a3 = Point(3, 4), int a4 = 333) {}
- inline void argRemoval5(int a0, bool a1, int a2, bool a3) {}
-
- // 'ok' must be removed and the return value will be changed
- // to a tuple (PyObject*) containing the expected result plus
- // the 'ok' value as a Python boolean
- std::pair<double, double> pointToPair(Point pt, bool* ok);
-
- // same as 'pointToPair' except that this time 'ok' is the first argument
- double multiplyPointCoordsPlusValue(bool* ok, Point pt, double value);
-
- // completely remove 'plus' from the Python side
- int doublePlus(int value, int plus = 0);
-
- // the default value for both arguments must be changed in Python
- int power(int base = 1, int exponent = 0);
-
- // in Python set argument default value to 10
- int timesTen(int number);
-
- // in Python remove the argument default value
- int increment(int number = 0);
-
- // don't export this method to Python
- void exclusiveCppStuff();
-
- // change the name of this regular method
- int cppMultiply(int a, int b);
-
- // change the name of this virtual method
- virtual const char* className();
-
- Point sumPointArray(int arraySize, const Point pointArray[]);
-
- // Replace 'const void*' by 'ByteArray&'.
- int getSize(const void* data, int size);
-
- // Mark the argument with a <no-null-pointer/> tag;
- // the test implementation must expect point never to be null.
- int sumPointCoordinates(const Point* point);
-
- // Modify the return value of a virtual method.
- virtual double differenceOfPointCoordinates(const Point* pt, bool* ok);
- double callDifferenceOfPointCoordinates(const Point* pt, bool* ok) { return differenceOfPointCoordinates(pt, ok); }
-
- // Sets an ObjectType in the argument and returns true.
- bool nonConversionRuleForArgumentWithDefaultValue(ObjectType **object = nullptr);
- ObjectType* getObject() const { return m_object; }
-
- // Inject code with a %CONVERTTOPYTHON that receives an user's primitive type.
- static inline OddBool passOddBool(OddBool ob) { return ob; }
-
- void setEnumValue(TestEnum e = TestEnumValue1);
- TestEnum enumValue() const;
- TestEnum defaultEnumValue() const;
-
- bool wasGetAttroCalled() const;
- void notifyGetAttroCalled();
-
- bool wasSetAttroCalled() const;
- void notifySetAttroCalled();
-
-private:
- ObjectType* m_object;
- TestEnum m_enumValue = TestEnumValue1;
- bool m_getAttroCalled = false;
- bool m_setAttroCalled = false;
-};
-
-class LIBSAMPLE_API AbstractModifications : public Modifications
-{
-public:
- AbstractModifications() {}
- virtual ~AbstractModifications() {}
-
- inline bool invert(bool value) { return !value; }
-
- // completely remove this method in Python
- virtual void pointlessPureVirtualMethod() = 0;
-};
-
-#endif // MODIFICATIONS_H
diff --git a/sources/shiboken2/tests/libsample/modified_constructor.cpp b/sources/shiboken2/tests/libsample/modified_constructor.cpp
deleted file mode 100644
index 015cf4e80..000000000
--- a/sources/shiboken2/tests/libsample/modified_constructor.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "modified_constructor.h"
-
-ModifiedConstructor::ModifiedConstructor(int first_arg)
-{
- m_stored_value = first_arg;
-}
-
-int
-ModifiedConstructor::retrieveValue()
-{
- return m_stored_value;
-}
-
-
diff --git a/sources/shiboken2/tests/libsample/modified_constructor.h b/sources/shiboken2/tests/libsample/modified_constructor.h
deleted file mode 100644
index ccf23a1a3..000000000
--- a/sources/shiboken2/tests/libsample/modified_constructor.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MODIFIEDCONSTRUCTOR_H
-#define MODIFIEDCONSTRUCTOR_H
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API ModifiedConstructor
-{
-public:
-
- ModifiedConstructor(int first_arg);
- int retrieveValue();
-
-private:
- int m_stored_value;
-};
-
-#endif // MODIFIEDCONSTRUCTOR_H
-
diff --git a/sources/shiboken2/tests/libsample/multiple_derived.cpp b/sources/shiboken2/tests/libsample/multiple_derived.cpp
deleted file mode 100644
index 2c6a0b8bb..000000000
--- a/sources/shiboken2/tests/libsample/multiple_derived.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "multiple_derived.h"
-
-MDerived1::MDerived1() : m_value(100)
-{
-}
-
-MDerived2::MDerived2() : m_value(200)
-{
-}
-
-MDerived3::MDerived3() : m_value(3000)
-{
-}
-
-MDerived4::MDerived4()
-{
-}
-
-MDerived5::MDerived5()
-{
-}
-
-MDerived1*
-MDerived1::transformFromBase1(Base1* self)
-{
- MDerived1* ptr = dynamic_cast<MDerived1*>(self);
- return ptr;
-}
-
-MDerived1*
-MDerived1::transformFromBase2(Base2* self)
-{
- MDerived1* ptr = dynamic_cast<MDerived1*>(self);
- return ptr;
-}
-
diff --git a/sources/shiboken2/tests/libsample/multiple_derived.h b/sources/shiboken2/tests/libsample/multiple_derived.h
deleted file mode 100644
index b551eda74..000000000
--- a/sources/shiboken2/tests/libsample/multiple_derived.h
+++ /dev/null
@@ -1,195 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MDERIVED_H
-#define MDERIVED_H
-
-#include "libsamplemacros.h"
-#include <string>
-
-class Base1
-{
-public:
- Base1() : m_value(1) {}
- virtual ~Base1() {}
- virtual int base1Method() { return m_value; }
-
- virtual void publicMethod() {};
-private:
- int m_value;
-};
-
-class Base2
-{
-public:
- Base2() : m_value(2) {}
- virtual ~Base2() {}
- virtual int base2Method() { return m_value; }
-private:
- int m_value;
-};
-
-class LIBSAMPLE_API MDerived1 : public Base1, public Base2
-{
-public:
- MDerived1();
- ~MDerived1() override {}
-
- int mderived1Method() { return m_value; }
- int base1Method () override { return Base1::base1Method() * 10; }
- int base2Method() override { return Base2::base2Method() * 10; }
-
- inline Base1* castToBase1() { return (Base1*) this; }
- inline Base2* castToBase2() { return (Base2*) this; }
-
- static MDerived1* transformFromBase1(Base1 *self);
- static MDerived1* transformFromBase2(Base2 *self);
-
-private:
- void publicMethod() override {}
- int m_value;
-};
-
-class SonOfMDerived1 : public MDerived1
-{
-public:
- SonOfMDerived1() : m_value(0) {}
- ~SonOfMDerived1() {}
-
- inline MDerived1* castToMDerived1() { return (MDerived1*) this; }
-
- int sonOfMDerived1Method() { return m_value; }
-private:
- int m_value;
-};
-
-class Base3
-{
-public:
- explicit Base3(int val = 3) : m_value(val) {}
- virtual ~Base3() {}
- int base3Method() { return m_value; }
-private:
- int m_value;
-};
-
-class Base4
-{
-public:
- Base4() : m_value(4) {}
- virtual ~Base4() {}
- int base4Method() { return m_value; }
-private:
- int m_value;
-};
-
-class Base5
-{
-public:
- Base5() : m_value(5) {}
- virtual ~Base5() {}
- virtual int base5Method() { return m_value; }
-private:
- int m_value;
-};
-
-class Base6
-{
-public:
- Base6() : m_value(6) {}
- virtual ~Base6() {}
- virtual int base6Method() { return m_value; }
-private:
- int m_value;
-};
-
-
-class LIBSAMPLE_API MDerived2 : public Base3, public Base4, public Base5, public Base6
-{
-public:
- MDerived2();
- virtual ~MDerived2() {}
-
- inline int base4Method() { return Base3::base3Method() * 10; }
- inline int mderived2Method() { return m_value; }
-
- inline Base3* castToBase3() { return (Base3*) this; }
- inline Base4* castToBase4() { return (Base4*) this; }
- inline Base5* castToBase5() { return (Base5*) this; }
- inline Base6* castToBase6() { return (Base6*) this; }
-
-private:
- int m_value;
-};
-
-class LIBSAMPLE_API MDerived3 : public MDerived1, public MDerived2
-{
-public:
- MDerived3();
- virtual ~MDerived3() {}
-
- inline virtual int mderived3Method() { return m_value; }
-
- inline MDerived1* castToMDerived1() { return (MDerived1*) this; }
- inline MDerived2* castToMDerived2() { return (MDerived2*) this; }
-
- inline Base3* castToBase3() { return (Base3*) this; }
-
-private:
- int m_value;
-};
-
-class LIBSAMPLE_API MDerived4 : public Base3, public Base4
-{
-public:
- MDerived4();
- ~MDerived4() {}
-
- inline int mderived4Method() { return 0; }
- inline int justDummyMethod() { return m_value; }
-
- inline Base3* castToBase3() { return (Base3*) this; }
- inline Base4* castToBase4() { return (Base4*) this; }
-private:
- int m_value;
-};
-
-class LIBSAMPLE_API MDerived5 : public Base3, public Base4
-{
-public:
- MDerived5();
- virtual ~MDerived5() {}
-
- virtual int mderived5Method() { return 0; }
-
- inline Base3* castToBase3() { return (Base3*) this; }
- inline Base4* castToBase4() { return (Base4*) this; }
-};
-
-#endif // MDERIVED_H
-
diff --git a/sources/shiboken2/tests/libsample/noimplicitconversion.h b/sources/shiboken2/tests/libsample/noimplicitconversion.h
deleted file mode 100644
index 3173f4609..000000000
--- a/sources/shiboken2/tests/libsample/noimplicitconversion.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef NOIMPLICITCONVERSION_H
-#define NOIMPLICITCONVERSION_H
-
-#include "libsamplemacros.h"
-
-// This class must not have implicit conversions AND
-// no conversion operators should be defined in its own module.
-class NoImplicitConversion
-{
-public:
- explicit NoImplicitConversion(int objId) : m_objId(objId) {}
- inline int objId() const { return m_objId; }
- inline static int receivesNoImplicitConversionByValue(NoImplicitConversion arg) { return arg.m_objId; }
- inline static int receivesNoImplicitConversionByPointer(NoImplicitConversion* arg) { return arg->m_objId; }
- inline static int receivesNoImplicitConversionByReference(NoImplicitConversion& arg) { return arg.m_objId; }
-private:
- int m_objId;
-};
-
-#endif // NOIMPLICITCONVERSION_H
-
diff --git a/sources/shiboken2/tests/libsample/nondefaultctor.h b/sources/shiboken2/tests/libsample/nondefaultctor.h
deleted file mode 100644
index bfdcbcf5b..000000000
--- a/sources/shiboken2/tests/libsample/nondefaultctor.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef NONDEFAULTCTOR_H
-#define NONDEFAULTCTOR_H
-
-#include "libsamplemacros.h"
-
-class NonDefaultCtor
-{
- int m_value;
-public:
- NonDefaultCtor(int value) : m_value(value)
- {
- }
-
- inline int value()
- {
- return m_value;
- }
-
- inline NonDefaultCtor returnMyself()
- {
- return *this;
- }
-
- inline NonDefaultCtor returnMyself(int)
- {
- return *this;
- }
-
- inline NonDefaultCtor returnMyself(int, NonDefaultCtor)
- {
- return *this;
- }
-
- virtual NonDefaultCtor returnMyselfVirtual()
- {
- return *this;
- }
-
- inline NonDefaultCtor callReturnMyselfVirtual()
- {
- return returnMyselfVirtual();
- }
-
- virtual ~NonDefaultCtor() {}
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/nontypetemplate.h b/sources/shiboken2/tests/libsample/nontypetemplate.h
deleted file mode 100644
index 5a9e670c6..000000000
--- a/sources/shiboken2/tests/libsample/nontypetemplate.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef NONTYPETEMPLATE_H
-#define NONTYPETEMPLATE_H
-
-#include "libsamplemacros.h"
-
-#include <algorithm>
-#include <numeric>
-
-template <int Size> class IntArray
-{
-public:
- explicit IntArray(const int *data) { std::copy(data, data + Size, m_array); }
- explicit IntArray(int v) { std::fill(m_array, m_array + Size, v); }
-
- int sum() const { return std::accumulate(m_array, m_array + Size, int(0)); }
-
-private:
- int m_array[Size];
-};
-
-typedef IntArray<2> IntArray2;
-typedef IntArray<3> IntArray3;
-
-#endif // NONTYPETEMPLATE_H
diff --git a/sources/shiboken2/tests/libsample/null.h b/sources/shiboken2/tests/libsample/null.h
deleted file mode 100644
index ea34ff5a0..000000000
--- a/sources/shiboken2/tests/libsample/null.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef NULL_H
-#define NULL_H
-
-class Null
-{
-public:
- Null(bool value) : m_isNull(value) {}
- Null() : m_isNull(false) {}
- void setIsNull(bool flag) { m_isNull = flag; }
-
-private:
- bool m_isNull;
-};
-
-#endif // STR_H
-
diff --git a/sources/shiboken2/tests/libsample/objectmodel.cpp b/sources/shiboken2/tests/libsample/objectmodel.cpp
deleted file mode 100644
index c92fb2ec2..000000000
--- a/sources/shiboken2/tests/libsample/objectmodel.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "objectmodel.h"
-
-void
-ObjectModel::setData(ObjectType* data)
-{
- m_data = data;
-}
-
-ObjectType*
-ObjectModel::data() const
-{
- return m_data;
-}
-
diff --git a/sources/shiboken2/tests/libsample/objectmodel.h b/sources/shiboken2/tests/libsample/objectmodel.h
deleted file mode 100644
index 1890ac47f..000000000
--- a/sources/shiboken2/tests/libsample/objectmodel.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OBJECTMODEL_H
-#define OBJECTMODEL_H
-
-#include "objecttype.h"
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API ObjectModel : public ObjectType
-{
-public:
- explicit ObjectModel(ObjectType *parent = nullptr)
- : ObjectType(parent), m_data(nullptr)
- {}
-
- void setData(ObjectType* data);
- virtual ObjectType* data() const;
-
- // The MethodCalled enum and related static methods were created to
- // test bug #630 [http://bugs.openbossa.org/show_bug.cgi?id=630]
- enum MethodCalled { ObjectTypeCalled, ObjectModelCalled };
- static MethodCalled receivesObjectTypeFamily(const ObjectType& object) { return ObjectModel::ObjectTypeCalled; }
- static MethodCalled receivesObjectTypeFamily(const ObjectModel& object) { return ObjectModel::ObjectModelCalled; }
-
-private:
- // The model holds only one piece of data.
- // (This is just a test after all.)
- ObjectType* m_data;
-};
-
-#endif // OBJECTMODEL_H
-
diff --git a/sources/shiboken2/tests/libsample/objecttype.cpp b/sources/shiboken2/tests/libsample/objecttype.cpp
deleted file mode 100644
index 855c08611..000000000
--- a/sources/shiboken2/tests/libsample/objecttype.cpp
+++ /dev/null
@@ -1,312 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "objecttype.h"
-#include "objecttypelayout.h"
-#include <algorithm>
-#include <iostream>
-#include <string>
-#include <assert.h>
-
-using namespace std;
-
-ObjectType::ObjectType(ObjectType* parent) : m_parent(nullptr), m_layout(nullptr), m_call_id(-1)
-{
- setParent(parent);
-}
-
-ObjectType::~ObjectType()
-{
- for (ObjectTypeList::iterator child_iter = m_children.begin();
- child_iter != m_children.end(); ++child_iter)
- delete *child_iter;
-}
-
-ObjectType*
-ObjectType::createWithChild()
-{
- ObjectType* parent = create();
- ObjectType* child = create();
- child->setObjectName("child");
- child->setParent(parent);
- return parent;
-}
-
-void
-ObjectType::removeChild(ObjectType* child)
-{
- if (!child)
- return;
-
- ObjectTypeList::iterator child_iter = std::find(m_children.begin(), m_children.end(), child);
- if (child_iter != m_children.end()) {
- m_children.erase(child_iter);
- child->m_parent = nullptr;
- }
-}
-
-ObjectType*
-ObjectType::takeChild(ObjectType* child)
-{
- if (!child)
- return nullptr;
-
- ObjectTypeList::iterator child_iter = std::find(m_children.begin(), m_children.end(), child);
- if (child_iter != m_children.end()) {
- m_children.erase(child_iter);
- child->m_parent = nullptr;
- return child;
- }
- return nullptr;
-}
-
-ObjectType*
-ObjectType::takeChild(const Str& name)
-{
- return takeChild(findChild(name));
-
-}
-
-ObjectType*
-ObjectType::findChild(const Str& name)
-{
- for (ObjectTypeList::iterator child_iter = m_children.begin();
- child_iter != m_children.end(); ++child_iter) {
-
- if ((*child_iter)->objectName() == name)
- return *child_iter;
- }
- return nullptr;
-}
-
-void
-ObjectType::killChild(const Str& name)
-{
- for (ObjectTypeList::iterator child_iter = m_children.begin();
- child_iter != m_children.end(); ++child_iter) {
-
- if ((*child_iter)->objectName() == name) {
- ObjectType* child = *child_iter;
- removeChild(child);
- delete child;
- break;
- }
- }
-}
-
-void
-ObjectType::setParent(ObjectType* parent)
-{
- if (m_parent == parent)
- return;
-
- if (m_parent)
- m_parent->removeChild(this);
-
- m_parent = parent;
- if (m_parent)
- m_parent->m_children.push_back(this);
-}
-
-void
-ObjectType::setObjectName(const Str& name)
-{
- m_objectName = name;
-}
-
-Str
-ObjectType::objectName() const
-{
- return m_objectName;
-}
-
-bool
-ObjectType::causeEvent(Event::EventType eventType)
-{
- Event e(eventType);
- return event(&e);
-}
-
-bool
-ObjectType::event(Event* event)
-{
- return true;
-}
-
-int
-ObjectType::processEvent(ObjectTypeList objects, Event *event)
-{
- int evaluated = 0;
-
- for (ObjectTypeList::iterator obj_iter = objects.begin();
- obj_iter != objects.end(); ++obj_iter) {
- if((*obj_iter)->event(event))
- evaluated++;
- }
-
- return evaluated;
-
-}
-
-void
-ObjectType::callInvalidateEvent(Event* event)
-{
- invalidateEvent(event);
-}
-
-void
-ObjectType::setLayout(ObjectTypeLayout* l)
-{
- if (!l) {
- cerr << "[WARNING] ObjectType::setLayout: Cannot set layout to 0." << endl;
- return;
- }
-
- if (layout()) {
- if (layout() != l) {
- cerr << "[WARNING] ObjectType::setLayout: Attempting to set ObjectTypeLayout '" << l->objectName().cstring();
- cerr << "' on ObjectType '" << objectName().cstring() << "', which already has a layout." << endl;
- }
- return;
- }
-
- ObjectType* oldParent = l->parent();
- if (oldParent && oldParent != this) {
- if (oldParent->isLayoutType()) {
- cerr << "[WARNING] ObjectType::setLayout: Attempting to set ObjectTypeLayout '" << l->objectName().cstring();
- cerr << "' on ObjectType '" << objectName().cstring() << "', when the ObjectTypeLayout already has a parent layout." << endl;
- return;
- } else {
- // Steal the layout from an ObjectType parent.
- oldParent->takeLayout();
- }
- }
-
- m_layout = l;
- if (oldParent != this) {
- l->setParent(this);
- l->reparentChildren(this);
- }
-}
-
-ObjectTypeLayout* ObjectType::takeLayout()
-{
- ObjectTypeLayout* l = layout();
- if (!l)
- return nullptr;
- m_layout = nullptr;
- l->setParent(0);
- return l;
-}
-
-unsigned int
-objectTypeHash(const ObjectType* objectType)
-{
- return reinterpret_cast<std::size_t>(objectType);
-}
-
-unsigned char
-ObjectType::callWithEnum(const Str& prefix, Event::EventType type, unsigned char value){
- return value*value;
-}
-
-unsigned char
-ObjectType::callWithEnum(const Str& prefix, unsigned char value) {
- return value;
-}
-
-void
-ObjectType::setObjectSplittedName(const char*, const Str& prefix, const Str& suffix)
-{
- std::string result(prefix.cstring());
- result += suffix.cstring();
- m_objectName = result.c_str();
-}
-
-void
-ObjectType::setObjectNameWithSize(const char*, int size, const Str& name)
-{
- std::string result(name.cstring(), size);
- m_objectName = result.c_str();
-}
-
-void
-ObjectType::setObjectNameWithSize(const Str& name, int size)
-{
- setObjectNameWithSize("", size, name);
-}
-
-void ObjectType::setObject(ObjectType *)
-{
- m_call_id = 0;
-}
-
-void ObjectType::setObject(const Null&)
-{
- m_call_id = 1;
-}
-
-int ObjectType::callId() const
-{
- return m_call_id;
-}
-
-
-void ObjectType::callVirtualCreateChild()
-{
- ObjectType* fake_parent = new ObjectType();
- ObjectType* fake_child = createChild(fake_parent);
- assert(fake_child->isPython());
- (void)fake_child;
- delete fake_parent;
-}
-
-ObjectType* ObjectType::createChild(ObjectType* parent)
-{
- return new ObjectType(parent);
-}
-
-std::size_t ObjectType::createObjectType()
-{
- void* addr = new ObjectType();
- return (std::size_t) addr;
-}
-
-OtherBase::~OtherBase()
-{
-}
-
-ObjectTypeDerived::~ObjectTypeDerived()
-{
-}
-
-bool
-ObjectTypeDerived::event(Event* event)
-{
- return true;
-}
diff --git a/sources/shiboken2/tests/libsample/objecttype.h b/sources/shiboken2/tests/libsample/objecttype.h
deleted file mode 100644
index 1f2a9c7e8..000000000
--- a/sources/shiboken2/tests/libsample/objecttype.h
+++ /dev/null
@@ -1,185 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OBJECTTYPE_H
-#define OBJECTTYPE_H
-
-#include <list>
-#include "str.h"
-#include "null.h"
-
-#include "libsamplemacros.h"
-
-#include <stddef.h>
-
-struct Event
-{
- enum EventType {
- NO_EVENT,
- BASIC_EVENT,
- SOME_EVENT,
- ANY_EVENT
- };
-
- enum class EventTypeClass {
- Value1,
- Value2
- };
-
- 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;
-};
-
-class ObjectTypeLayout;
-class ObjectType;
-using ObjectTypeList = std::list<ObjectType*>;
-
-class LIBSAMPLE_API ObjectType
-{
-public:
- // ### Fixme: Use uintptr_t in C++ 11
- using Identifier = size_t;
-
- explicit ObjectType(ObjectType *parent = nullptr);
- virtual ~ObjectType();
-
- // factory method
- inline static ObjectType* create() { return new ObjectType(); }
- static ObjectType* createWithChild();
-
- void setParent(ObjectType* parent);
- inline ObjectType* parent() const { return m_parent; }
- inline const ObjectTypeList& children() const { return m_children; }
- void killChild(const Str& name);
- void removeChild(ObjectType* child);
- ObjectType* takeChild(ObjectType* child);
- virtual ObjectType* takeChild(const Str& name);
- ObjectType* findChild(const Str& name);
-
- Str objectName() const;
- void setObjectName(const Str& name);
-
- inline Identifier identifier() const { return reinterpret_cast<Identifier>(this); }
-
- bool causeEvent(Event::EventType eventType);
-
- // Returns true if the event is processed.
- virtual bool event(Event* event);
- static int processEvent(ObjectTypeList objects, Event *event);
-
- void callInvalidateEvent(Event* event);
- virtual void invalidateEvent(Event* event) {}
-
- // This nonsense method emulate QWidget.setLayout method
- // All layout objects will became children of this object.
- void setLayout(ObjectTypeLayout* layout);
- inline ObjectTypeLayout* layout() const { return m_layout; }
-
- // This method should be reimplemented by ObjectTypeLayout.
- virtual bool isLayoutType() { return false; }
-
- unsigned char callWithEnum(const Str& prefix, Event::EventType type, unsigned char value=80);
- unsigned char callWithEnum(const Str& prefix, unsigned char value=0);
-
- //Functions used in test with named arguments
- void setObjectSplittedName(const char*, const Str& prefix = Str("<unk"), const Str& suffix = Str("nown>"));
- void setObjectNameWithSize(const char*, int size=9, const Str& name = Str("<unknown>"));
- void setObjectNameWithSize(const Str& name = Str("<unknown>"), int size=9);
-
- //Function used to confuse the generator when two values accept Null as arg
- void setObject(ObjectType *);
- void setObject(const Null&);
- int callId() const;
-
- //Function used to create a parent from C++
- virtual bool isPython() { return false; }
- void callVirtualCreateChild();
- virtual ObjectType* createChild(ObjectType* parent);
- static std::size_t createObjectType();
-
- //return a parent from C++
- ObjectType* getCppParent() {
- if (!m_parent) {
- ObjectType* parent = new ObjectType();
- setParent(parent);
- }
- return m_parent;
- }
-
- void destroyCppParent() {
- delete m_parent;
- }
-
- //Deprecated test
- bool deprecatedFunction() { return true; }
-
- // nextInFocusChain simply returns the parent to test object cycles; the parent
- // may be returned by the QWidget's implementation but isn't always returned
- ObjectType* nextInFocusChain() { return m_parent; }
-
-private:
- ObjectType(const ObjectType&);
- ObjectType& operator=(const ObjectType&);
-
- ObjectTypeLayout* takeLayout();
-
- Str m_objectName;
- ObjectType* m_parent;
- ObjectTypeList m_children;
-
- ObjectTypeLayout* m_layout;
-
-
- //used on overload null test
- int m_call_id;
-};
-
-LIBSAMPLE_API unsigned int objectTypeHash(const ObjectType* objectType);
-
-class LIBSAMPLE_API OtherBase {
-public:
- OtherBase() {};
- virtual ~OtherBase();
-};
-
-class LIBSAMPLE_API ObjectTypeDerived: public ObjectType, public OtherBase {
-public:
- ObjectTypeDerived(): ObjectType(), OtherBase() {};
-
- bool event(Event* event) override;
- ~ObjectTypeDerived() override;
-};
-
-#endif // OBJECTTYPE_H
-
diff --git a/sources/shiboken2/tests/libsample/objecttypebyvalue.h b/sources/shiboken2/tests/libsample/objecttypebyvalue.h
deleted file mode 100644
index 64fa78c83..000000000
--- a/sources/shiboken2/tests/libsample/objecttypebyvalue.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OBJECTTYPEBYVALUE_H
-#define OBJECTTYPEBYVALUE_H
-#include <list>
-#include "protected.h"
-
-class ObjectTypeByValue
-{
-public:
- ObjectTypeByValue returnSomeKindOfMe() { return ObjectTypeByValue(); }
- void acceptKindOfMeAsValue(ObjectTypeByValue kindOfMe) {}
-
- void acceptListOfObjectTypeByValue(std::list<ObjectTypeByValue> listOfMe) {}
-
- // prop used to check for segfaults
- ProtectedProperty prop;
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/objecttypeholder.cpp b/sources/shiboken2/tests/libsample/objecttypeholder.cpp
deleted file mode 100644
index ff2f14f12..000000000
--- a/sources/shiboken2/tests/libsample/objecttypeholder.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "objecttypeholder.h"
-
-ObjectTypeHolder::ObjectTypeHolder(const char* objectName)
-{
- m_objectType = new ObjectType();
- m_objectType->setObjectName(objectName);
-}
-
-ObjectTypeHolder::~ObjectTypeHolder()
-{
- delete m_objectType;
-}
-
-Str
-ObjectTypeHolder::passObjectTypeAsReference(const ObjectType& objectType)
-{
- return objectType.objectName();
-}
-
-Str
-ObjectTypeHolder::callPassObjectTypeAsReference()
-{
- return passObjectTypeAsReference(*m_objectType);
-}
diff --git a/sources/shiboken2/tests/libsample/objecttypeholder.h b/sources/shiboken2/tests/libsample/objecttypeholder.h
deleted file mode 100644
index ce13de74f..000000000
--- a/sources/shiboken2/tests/libsample/objecttypeholder.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OBJECTTYPEHOLDER_H
-#define OBJECTTYPEHOLDER_H
-
-#include "libsamplemacros.h"
-#include "objecttype.h"
-#include "str.h"
-
-class LIBSAMPLE_API ObjectTypeHolder
-{
-public:
- explicit ObjectTypeHolder(const char* objectName);
- virtual ~ObjectTypeHolder();
-
- ObjectType* getObjecType() { return m_objectType; }
-
- virtual Str passObjectTypeAsReference(const ObjectType& objectType);
- Str callPassObjectTypeAsReference();
-
-private:
- ObjectType* m_objectType;
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/objecttypelayout.cpp b/sources/shiboken2/tests/libsample/objecttypelayout.cpp
deleted file mode 100644
index 6f3d0eba9..000000000
--- a/sources/shiboken2/tests/libsample/objecttypelayout.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "objecttypelayout.h"
-#include <iostream>
-
-using namespace std;
-
-void ObjectTypeLayout::addObject(ObjectType* obj)
-{
- if (obj->isLayoutType()) {
- ObjectTypeLayout* l = reinterpret_cast<ObjectTypeLayout*>(obj);
- if (l->parent()) {
- cerr << "[WARNING] ObjectTypeLayout::addObject: layout '" << l->objectName().cstring();
- cerr << "' already has a parent." << endl;
- return;
- }
-
- l->setParent(this);
-
- if (parent() && !parent()->isLayoutType())
- l->reparentChildren(parent());
- }
-
- m_objects.push_back(obj);
-}
-
-std::list< ObjectType* > ObjectTypeLayout::objects() const
-{
- return m_objects;
-}
-
-void ObjectTypeLayout::reparentChildren(ObjectType* parent)
-{
- std::list<ObjectType*>::const_iterator it = m_objects.begin();
- for (; it != m_objects.end(); ++it) {
- if ((*it)->isLayoutType())
- reinterpret_cast<ObjectTypeLayout*>(*it)->reparentChildren(parent);
- else
- (*it)->setParent(parent);
- }
-}
-
diff --git a/sources/shiboken2/tests/libsample/objecttypelayout.h b/sources/shiboken2/tests/libsample/objecttypelayout.h
deleted file mode 100644
index eb099313c..000000000
--- a/sources/shiboken2/tests/libsample/objecttypelayout.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OBJECTTYPELAYOUT_H
-#define OBJECTTYPELAYOUT_H
-
-#include "libsamplemacros.h"
-#include "objecttype.h"
-#include <list>
-
-class ObjectType;
-
-class LIBSAMPLE_API ObjectTypeLayout : public ObjectType
-{
-public:
- void addObject(ObjectType* obj);
- std::list<ObjectType*> objects() const;
-
- bool isLayoutType() override { return true; }
- inline static ObjectTypeLayout* create() { return new ObjectTypeLayout(); }
-
- ObjectType* takeChild(const Str& name) override { return ObjectType::takeChild(name); }
-private:
- std::list<ObjectType*> m_objects;
-
- void reparentChildren(ObjectType* parent);
- friend LIBSAMPLE_API void ObjectType::setLayout(ObjectTypeLayout* l);
-};
-
-#endif // OBJECTTYPELAYOUT_H
-
diff --git a/sources/shiboken2/tests/libsample/objecttypeoperators.cpp b/sources/shiboken2/tests/libsample/objecttypeoperators.cpp
deleted file mode 100644
index dc5243f2e..000000000
--- a/sources/shiboken2/tests/libsample/objecttypeoperators.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "objecttypeoperators.h"
-
-ObjectTypeOperators::ObjectTypeOperators(const std::string key) : m_key(key)
-{
-}
-
-bool ObjectTypeOperators::operator==(const ObjectTypeOperators& other) const
-{
- return m_key == other.m_key;
-}
-
-const ObjectTypeOperators& ObjectTypeOperators::operator<(const ObjectTypeOperators& other) const
-{
- return m_key < other.m_key ? *this : other;
-}
-
-bool operator==(const ObjectTypeOperators* obj, const std::string& str)
-{
- return obj->key() == str;
-}
-
-bool operator==(const std::string& str, const ObjectTypeOperators* obj)
-{
- return str == obj->key();
-}
-
-std::string operator+(const ObjectTypeOperators* obj, const std::string& str)
-{
- return obj->key() + str;
-}
-
-std::string operator+(const std::string& str, const ObjectTypeOperators* obj)
-{
- return str + obj->key();
-}
diff --git a/sources/shiboken2/tests/libsample/objecttypeoperators.h b/sources/shiboken2/tests/libsample/objecttypeoperators.h
deleted file mode 100644
index 6bb54d600..000000000
--- a/sources/shiboken2/tests/libsample/objecttypeoperators.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OBJECTTYPEOPERATORS_H
-#define OBJECTTYPEOPERATORS_H
-
-#include "libsamplemacros.h"
-#include <string>
-
-class LIBSAMPLE_API ObjectTypeOperators
-{
-public:
- explicit ObjectTypeOperators(const std::string key);
- virtual ~ObjectTypeOperators() {}
-
- bool operator==(const ObjectTypeOperators& other) const;
- const ObjectTypeOperators& operator<(const ObjectTypeOperators& other) const;
-
- // chaos!
- virtual void operator>(const ObjectTypeOperators&) { m_key.append("operator>"); }
-
- std::string key() const { return m_key; }
-
-private:
- std::string m_key;
-
- ObjectTypeOperators(ObjectTypeOperators&);
- ObjectTypeOperators& operator=(ObjectTypeOperators&);
-};
-
-LIBSAMPLE_API bool operator==(const ObjectTypeOperators* obj, const std::string& str);
-LIBSAMPLE_API bool operator==(const std::string& str, const ObjectTypeOperators* obj);
-LIBSAMPLE_API std::string operator+(const ObjectTypeOperators* obj, const std::string& str);
-LIBSAMPLE_API std::string operator+(const std::string& str, const ObjectTypeOperators* obj);
-
-#endif // OBJECTTYPEOPERATORS_H
diff --git a/sources/shiboken2/tests/libsample/objectview.cpp b/sources/shiboken2/tests/libsample/objectview.cpp
deleted file mode 100644
index d640c406e..000000000
--- a/sources/shiboken2/tests/libsample/objectview.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "objectview.h"
-#include "objectmodel.h"
-#include "str.h"
-
-Str
-ObjectView::displayModelData()
-{
- if (!m_model)
- return Str("(NULL)");
- return Str("Name: %VAR").arg(m_model->objectName());
-}
-
-void
-ObjectView::modifyModelData(Str& data)
-{
- if (m_model)
- m_model->setObjectName(data);
-}
-
-
-ObjectType*
-ObjectView::getRawModelData()
-{
- return m_model->data();
-}
-
diff --git a/sources/shiboken2/tests/libsample/objectview.h b/sources/shiboken2/tests/libsample/objectview.h
deleted file mode 100644
index b68d031e9..000000000
--- a/sources/shiboken2/tests/libsample/objectview.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OBJECTVIEW_H
-#define OBJECTVIEW_H
-
-#include "objecttype.h"
-#include "libsamplemacros.h"
-
-class Str;
-class ObjectModel;
-
-class LIBSAMPLE_API ObjectView : public ObjectType
-{
-public:
- ObjectView(ObjectModel *model = nullptr, ObjectType *parent = nullptr)
- : ObjectType(parent), m_model(model)
- {}
-
- inline void setModel(ObjectModel* model) { m_model = model; }
- inline ObjectModel* model() const { return m_model; }
-
- Str displayModelData();
- void modifyModelData(Str& data);
-
- ObjectType* getRawModelData();
-
-private:
- ObjectModel* m_model;
-};
-
-#endif // OBJECTVIEW_H
-
diff --git a/sources/shiboken2/tests/libsample/oddbool.h b/sources/shiboken2/tests/libsample/oddbool.h
deleted file mode 100644
index 454c84157..000000000
--- a/sources/shiboken2/tests/libsample/oddbool.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ODDBOOL_H
-#define ODDBOOL_H
-
-#include "libsamplemacros.h"
-
-class OddBool
-{
-
-public:
- inline explicit OddBool(bool b) : m_value(b) {}
- bool value() const { return m_value; }
-
- inline OddBool operator!() const { return OddBool(!m_value); }
-
-private:
- bool m_value;
-};
-
-inline bool operator==(OddBool b1, bool b2) { return (!b1).value() == !b2; }
-inline bool operator==(bool b1, OddBool b2) { return (!b1) == (!b2).value(); }
-inline bool operator==(OddBool b1, OddBool b2) { return (!b1).value() == (!b2).value(); }
-inline bool operator!=(OddBool b1, bool b2) { return (!b1).value() != !b2; }
-inline bool operator!=(bool b1, OddBool b2) { return (!b1) != (!b2).value(); }
-inline bool operator!=(OddBool b1, OddBool b2) { return (!b1).value() != (!b2).value(); }
-
-class OddBoolUser
-{
-public:
- OddBoolUser() : m_oddbool(OddBool(false)) {}
- OddBoolUser(const OddBool& oddBool) : m_oddbool(oddBool) {}
- virtual ~OddBoolUser() {}
-
- inline OddBool oddBool() { return m_oddbool; }
- inline void setOddBool(OddBool oddBool) { m_oddbool = oddBool; }
-
- virtual OddBool invertedOddBool()
- {
- return !m_oddbool;
- }
-
- inline OddBool callInvertedOddBool()
- {
- return invertedOddBool();
- }
-
- static inline OddBool getOddBool(const OddBoolUser& oddBoolUser)
- {
- return oddBoolUser.m_oddbool;
- }
-
-private:
- OddBool m_oddbool;
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/onlycopy.cpp b/sources/shiboken2/tests/libsample/onlycopy.cpp
deleted file mode 100644
index cfc7c9d99..000000000
--- a/sources/shiboken2/tests/libsample/onlycopy.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "onlycopy.h"
-
-class OnlyCopyPrivate
-{
-public:
- explicit OnlyCopyPrivate(int v = 0) : value(v) {}
-
- int value;
-};
-
-OnlyCopy::OnlyCopy(int value) : d(new OnlyCopyPrivate(value))
-{
-
-}
-
-OnlyCopy::OnlyCopy(OnlyCopyPrivate *dIn) : d(dIn)
-{
-}
-
-OnlyCopy::~OnlyCopy()
-{
- delete d;
-}
-
-OnlyCopy::OnlyCopy(const OnlyCopy& other) : d(new OnlyCopyPrivate(other.value()))
-{
-}
-
-OnlyCopy&
-OnlyCopy::operator=(const OnlyCopy& other)
-{
- d->value = other.d->value;
- return *this;
-}
-
-int OnlyCopy::value() const
-{
- return d->value;
-}
-
-OnlyCopy
-FriendOfOnlyCopy::createOnlyCopy(int value)
-{
-
- return OnlyCopy(value);
-}
-
-std::list<OnlyCopy>
-FriendOfOnlyCopy::createListOfOnlyCopy(int quantity)
-{
- std::list<OnlyCopy> list;
- for (int i = 0; i < quantity; ++i)
- list.push_back(createOnlyCopy(i));
- return list;
-}
diff --git a/sources/shiboken2/tests/libsample/onlycopy.h b/sources/shiboken2/tests/libsample/onlycopy.h
deleted file mode 100644
index 84a32a951..000000000
--- a/sources/shiboken2/tests/libsample/onlycopy.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef ONLYCOPYCLASS_H
-#define ONLYCOPYCLASS_H
-
-#include "libsamplemacros.h"
-#include <list>
-
-// These classes simulate a situation found in QWebEngineHistoryItem.
-
-class OnlyCopyPrivate;
-
-class LIBSAMPLE_API OnlyCopy
-{
-public:
- OnlyCopy(const OnlyCopy& other);
- OnlyCopy& operator=(const OnlyCopy& other);
- ~OnlyCopy();
-
- int value() const;
- static int getValue(OnlyCopy onlyCopy) { return onlyCopy.value(); }
- static int getValueFromReference(const OnlyCopy& onlyCopy) { return onlyCopy.value(); }
-private:
- OnlyCopyPrivate *d;
- explicit OnlyCopy(int value);
- explicit OnlyCopy(OnlyCopyPrivate *d); // rejected due to unknown OnlyCopyPrivate
- friend class FriendOfOnlyCopy;
-};
-
-class LIBSAMPLE_API FriendOfOnlyCopy
-{
-public:
- static OnlyCopy createOnlyCopy(int value);
- static std::list<OnlyCopy> createListOfOnlyCopy(int quantity);
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/overload.cpp b/sources/shiboken2/tests/libsample/overload.cpp
deleted file mode 100644
index ebf19586e..000000000
--- a/sources/shiboken2/tests/libsample/overload.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "overload.h"
-
-Overload::FunctionEnum Overload::overloaded()
-{
- return Function0;
-}
-
-Overload::FunctionEnum Overload::overloaded(Size* size)
-{
- return Function1;
-}
-
-Overload::FunctionEnum Overload::overloaded(Point* point, ParamEnum param)
-{
- return Function2;
-}
-
-Overload::FunctionEnum Overload::overloaded(const Point& point)
-{
- return Function3;
-}
-
diff --git a/sources/shiboken2/tests/libsample/overload.h b/sources/shiboken2/tests/libsample/overload.h
deleted file mode 100644
index aa2572d50..000000000
--- a/sources/shiboken2/tests/libsample/overload.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OVERLOAD_H
-#define OVERLOAD_H
-
-#include "echo.h"
-#include "str.h"
-#include "size.h"
-#include "point.h"
-#include "pointf.h"
-#include "polygon.h"
-#include "rect.h"
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API Overload
-{
-public:
- enum FunctionEnum {
- Function0,
- Function1,
- Function2,
- Function3,
- Function4,
- Function5,
- Function6
- };
-
- enum ParamEnum {
- Param0,
- Param1
- };
-
- Overload() {}
- virtual ~Overload() {}
-
- FunctionEnum overloaded();
- FunctionEnum overloaded(Size* size);
- FunctionEnum overloaded(Point* point, ParamEnum param);
- FunctionEnum overloaded(const Point& point);
-
- inline void differentReturnTypes(ParamEnum param = Param0) {}
- inline int differentReturnTypes(ParamEnum param, int val) { return val; }
-
- inline int intOverloads(const Point& p, double d) { return 1; }
- inline int intOverloads(int i, int i2) { return 2; }
- inline int intOverloads(int i, int removedArg, double d) { return 3; }
-
- inline FunctionEnum intDoubleOverloads(int a0, int a1) const { return Function0; }
- inline FunctionEnum intDoubleOverloads(double a0, double a1) const { return Function1; }
-
- void singleOverload(Point* x) {}
- Point* singleOverload() {return new Point();}
-
- // Similar to QImage::trueMatrix(QMatrix,int,int) and QImage::trueMatrix(QTransform,int,int)
- FunctionEnum wrapperIntIntOverloads(const Point& arg0, int arg1, int arg2) { return Function0; }
- FunctionEnum wrapperIntIntOverloads(const Polygon& arg0, int arg1, int arg2) { return Function1; }
-
- // Similar to QImage constructor
- FunctionEnum strBufferOverloads(const Str &arg0, const char *arg1 = nullptr, bool arg2 = true) { return Function0; }
- FunctionEnum strBufferOverloads(unsigned char* arg0, int arg1) { return Function1; }
- FunctionEnum strBufferOverloads() { return Function2; }
-
- // Similar to QPainter::drawText(...)
- FunctionEnum drawText(const Point& a0, const Str& a1) { return Function0; }
- FunctionEnum drawText(const PointF& a0, const Str& a1) { return Function1; }
- FunctionEnum drawText(const Rect& a0, int a1, const Str& a2) { return Function2; }
- FunctionEnum drawText(const RectF& a0, int a1, const Str& a2) { return Function3; }
- FunctionEnum drawText(const RectF& a0, const Str& a1, const Echo& a2 = Echo()) { return Function4; }
- FunctionEnum drawText(int a0, int a1, const Str& a2) { return Function5; }
- FunctionEnum drawText(int a0, int a1, int a2, int a3, int a4, const Str& a5) { return Function6; }
-
- // A variant of the one similar to QPainter::drawText(...)
- FunctionEnum drawText2(const Point& a0, const Str& a1) { return Function0; }
- FunctionEnum drawText2(const PointF& a0, const Str& a1) { return Function1; }
- FunctionEnum drawText2(const Rect& a0, int a1, const Str& a2) { return Function2; }
- FunctionEnum drawText2(const RectF& a0, int a1, const Str& a2) { return Function3; }
- FunctionEnum drawText2(const RectF& a0, const Str& a1, const Echo& a2 = Echo()) { return Function4; }
- FunctionEnum drawText2(int a0, int a1, const Str& a2) { return Function5; }
- FunctionEnum drawText2(int a0, int a1, int a2, int a3 = 0, int a4 = 0, const Str& a5 = Str()) { return Function6; }
-
- // A simpler variant of the one similar to QPainter::drawText(...)
- FunctionEnum drawText3(const Str& a0, const Str& a1, const Str& a2) { return Function0; }
- FunctionEnum drawText3(int a0, int a1, int a2, int a3, int a4) { return Function1; }
-
- // Another simpler variant of the one similar to QPainter::drawText(...)
- FunctionEnum drawText4(int a0, int a1, int a2) { return Function0; }
- FunctionEnum drawText4(int a0, int a1, int a2, int a3, int a4) { return Function1; }
-
- FunctionEnum acceptSequence() { return Function0; }
- FunctionEnum acceptSequence(int a0, int a1) { return Function1; }
- FunctionEnum acceptSequence(const Str& a0, ParamEnum a1 = Param0) { return Function2; }
- FunctionEnum acceptSequence(const Size& a0) { return Function3; }
- // The type must be changed to PySequence.
- FunctionEnum acceptSequence(const char* const a0[]) { return Function4; }
- FunctionEnum acceptSequence(void* a0) { return Function5; }
-};
-
-class LIBSAMPLE_API Overload2 : public Overload
-{
-public:
- // test bug#616, public and private method differ only by const
- void doNothingInPublic() const {}
- void doNothingInPublic(int) {}
- virtual void doNothingInPublic3() const {}
- void doNothingInPublic3(int) const {}
-protected:
- void doNothingInPublic2() const {}
- void doNothingInPublic2(int) {}
-private:
- void doNothingInPublic() {}
- void doNothingInPublic2() {}
- void doNothingInPublic3() {}
-};
-
-#endif // OVERLOAD_H
-
diff --git a/sources/shiboken2/tests/libsample/overloadsort.cpp b/sources/shiboken2/tests/libsample/overloadsort.cpp
deleted file mode 100644
index bad0cdf52..000000000
--- a/sources/shiboken2/tests/libsample/overloadsort.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "overloadsort.h"
-
diff --git a/sources/shiboken2/tests/libsample/overloadsort.h b/sources/shiboken2/tests/libsample/overloadsort.h
deleted file mode 100644
index 024f229a5..000000000
--- a/sources/shiboken2/tests/libsample/overloadsort.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef OVERLOADSORT_H
-#define OVERLOADSORT_H
-
-#include "libsamplemacros.h"
-
-#include <list>
-
-class ImplicitTarget
-{
-public:
- ImplicitTarget(){}
-};
-
-class ImplicitBase
-{
-public:
- ImplicitBase(){}
- ImplicitBase(const ImplicitTarget &b){}
-};
-
-class SortedOverload
-{
-public:
-
- inline const char *overload(int x) {
- return "int";
- }
-
- inline const char *overload(double x) {
- return "double";
- }
-
- inline const char *overload(ImplicitBase x) {
- return "ImplicitBase";
- }
-
- inline const char *overload(ImplicitTarget x) {
- return "ImplicitTarget";
- }
-
- inline const char *overload(const std::list<ImplicitBase> &x) {
- return "list(ImplicitBase)";
- }
-
- inline int implicit_overload(const ImplicitBase &x) {
- return 1;
- }
-
- inline const char *overloadDeep(int x, ImplicitBase &y) {
- return "ImplicitBase";
- }
-
-
- inline const char* pyObjOverload(int, int) { return "int,int"; }
- inline const char* pyObjOverload(unsigned char*, int) { return "PyObject,int"; }
-
-};
-
-#endif // OVERLOADSORT_H
-
diff --git a/sources/shiboken2/tests/libsample/pairuser.cpp b/sources/shiboken2/tests/libsample/pairuser.cpp
deleted file mode 100644
index 661988445..000000000
--- a/sources/shiboken2/tests/libsample/pairuser.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "pairuser.h"
-
-using namespace std;
-
-std::pair<int, int>
-PairUser::callCreatePair()
-{
- return createPair();
-}
-
-std::pair<int, int>
-PairUser::createPair()
-{
- return std::pair<int, int>(10, 20);
-}
-
-std::pair<Complex, Complex>
-PairUser::createComplexPair(Complex cpx0, Complex cpx1)
-{
- return std::pair<Complex, Complex>(cpx0, cpx1);
-}
-
-double
-PairUser::sumPair(std::pair<int, double> pair)
-{
- return ((double) pair.first) + pair.second;
-}
-
diff --git a/sources/shiboken2/tests/libsample/pairuser.h b/sources/shiboken2/tests/libsample/pairuser.h
deleted file mode 100644
index 37219f724..000000000
--- a/sources/shiboken2/tests/libsample/pairuser.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PAIRUSER_H
-#define PAIRUSER_H
-
-#include <utility>
-#include "complex.h"
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API PairUser
-{
-public:
- PairUser() {}
- virtual ~PairUser() {}
-
- virtual std::pair<int, int> createPair();
- std::pair<int, int> callCreatePair();
- static std::pair<Complex, Complex> createComplexPair(Complex cpx0, Complex cpx1);
- double sumPair(std::pair<int, double> pair);
-
- inline void setPair(std::pair<int, int> pair) { m_pair = pair; }
- inline std::pair<int, int> getPair() { return m_pair; }
-
-private:
- std::pair<int, int> m_pair;
-};
-#endif // PAIRUSER_H
-
diff --git a/sources/shiboken2/tests/libsample/pen.cpp b/sources/shiboken2/tests/libsample/pen.cpp
deleted file mode 100644
index d30071f49..000000000
--- a/sources/shiboken2/tests/libsample/pen.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "pen.h"
-
-Color::Color() : m_null(true)
-{
-}
-
-Color::Color(SampleNamespace::InValue arg) : m_null(false)
-{
-}
-
-Color::Color(unsigned int arg) : m_null(false)
-{
-}
-
-bool Color::isNull() const
-{
- return m_null;
-}
-
-Pen::Pen() : m_ctor(EmptyCtor)
-{
-}
-
-Pen::Pen(SampleNamespace::Option option) : m_ctor(EnumCtor)
-{
-}
-
-Pen::Pen(const Color& color) : m_ctor(ColorCtor)
-{
-}
-
-Pen::Pen(const Pen& pen) : m_ctor(CopyCtor)
-{
-}
-
-int Pen::ctorType()
-{
- return m_ctor;
-}
diff --git a/sources/shiboken2/tests/libsample/pen.h b/sources/shiboken2/tests/libsample/pen.h
deleted file mode 100644
index ca079198b..000000000
--- a/sources/shiboken2/tests/libsample/pen.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PEN_H
-#define PEN_H
-
-#include "libsamplemacros.h"
-#include "samplenamespace.h"
-
-class LIBSAMPLE_API Color
-{
-public:
- Color();
- Color(SampleNamespace::InValue arg);
- Color(unsigned int arg);
-
- bool isNull() const;
-private:
- bool m_null;
-};
-
-class LIBSAMPLE_API Pen
-{
-public:
- enum { EmptyCtor, EnumCtor, ColorCtor, CopyCtor };
-
- Pen();
- Pen(SampleNamespace::Option option);
- Pen(const Color& color);
- Pen(const Pen& pen);
-
- int ctorType();
-private:
- int m_ctor;
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/photon.cpp b/sources/shiboken2/tests/libsample/photon.cpp
deleted file mode 100644
index e61fd5969..000000000
--- a/sources/shiboken2/tests/libsample/photon.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "photon.h"
-
-namespace Photon
-{
-const ClassType Base::staticType;
-int callCalculateForValueDuplicatorPointer(ValueDuplicator* value)
-{
- return value->calculate();
-}
-int callCalculateForValueDuplicatorReference(ValueDuplicator& value)
-{
- return value.calculate();
-}
-int countValueIdentities(const std::list<ValueIdentity>& values)
-{
- return values.size();
-}
-int countValueDuplicators(const std::list<TemplateBase<DuplicatorType> >& values)
-{
- return values.size();
-}
-} // namespace Photon
diff --git a/sources/shiboken2/tests/libsample/photon.h b/sources/shiboken2/tests/libsample/photon.h
deleted file mode 100644
index 1dcb4f83e..000000000
--- a/sources/shiboken2/tests/libsample/photon.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PHOTON_H
-#define PHOTON_H
-
-#include <list>
-#include "libsamplemacros.h"
-
-// This namespace and classes simulate
-// situations found in Qt's phonon module.
-
-namespace Photon
-{
-
-enum ClassType {
- BaseType = 0,
- IdentityType = 1,
- DuplicatorType = 2
-};
-
-class LIBSAMPLE_API Base
-{
-public:
- explicit Base(int value) : m_value(value) {}
- virtual ~Base() {}
- inline void setValue(int value) { m_value = value; }
- inline int value() const { return m_value; }
-
- template <class T> bool isType() { return type() == T::staticType; }
- bool isType(ClassType t) { return type() == t; }
-
- virtual ClassType type() const { return BaseType; };
- static const ClassType staticType = BaseType;
-
-protected:
- int m_value;
-};
-
-template<ClassType CLASS_TYPE>
-class LIBSAMPLE_API TemplateBase : public Base
-{
-public:
- explicit TemplateBase(int value) : Base(value) {}
- inline int multiplicator() const { return (int)CLASS_TYPE; }
- inline int calculate() const { return m_value * ((int)CLASS_TYPE); }
- static inline ClassType classType() { return CLASS_TYPE; }
-
- inline int sumValueUsingPointer(TemplateBase<CLASS_TYPE>* other) const { return m_value + other->m_value; }
- inline int sumValueUsingReference(TemplateBase<CLASS_TYPE>& other) const { return m_value + other.m_value; }
-
- inline std::list<TemplateBase<CLASS_TYPE> > getListOfThisTemplateBase()
- {
- std::list<TemplateBase<CLASS_TYPE> > objs;
- objs.push_back(*this);
- objs.push_back(*this);
- return objs;
- }
-
- static inline TemplateBase<CLASS_TYPE>* passPointerThrough(TemplateBase<CLASS_TYPE>* obj) { return obj; }
-
- ClassType type() const override { return CLASS_TYPE; }
- static const ClassType staticType = CLASS_TYPE;
-};
-
-#if defined _WIN32 || defined __CYGWIN__
-template class LIBSAMPLE_API TemplateBase<IdentityType>;
-template class LIBSAMPLE_API TemplateBase<DuplicatorType>;
-#endif
-
-using ValueIdentity = TemplateBase<IdentityType>;
-using ValueDuplicator = TemplateBase<DuplicatorType>;
-
-LIBSAMPLE_API int callCalculateForValueDuplicatorPointer(ValueDuplicator* value);
-LIBSAMPLE_API int callCalculateForValueDuplicatorReference(ValueDuplicator& value);
-LIBSAMPLE_API int countValueIdentities(const std::list<ValueIdentity>& values);
-LIBSAMPLE_API int countValueDuplicators(const std::list<TemplateBase<DuplicatorType> >& values);
-
-// This simulates an internal error (SEGV) caused by 'noexcept' in
-// boost::intrusive_ptr before support for 'noexcept' was added. The ENTIRE
-// code below is needed to trigger the exception; it isn't seen with just a
-// 'noexcept' following a declaration.
-//
-// NOTE: For reasons that should be fairly obvious, this test unfortunately can
-// only be "run" when building in C++11 mode.
-#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)
-# define PHOTON_NOEXCEPT noexcept
-#else
-# define PHOTON_NOEXCEPT
-#endif
-class Pointer
-{
-public:
- Pointer() PHOTON_NOEXCEPT : px(nullptr) {}
- Pointer(int* p) : px(p) {}
-
- void reset() PHOTON_NOEXCEPT { Pointer().swap(*this); }
-
- int* get() const PHOTON_NOEXCEPT { return px; }
- int& operator*() const { return *px; }
-
- void swap(Pointer& rhs) PHOTON_NOEXCEPT
- {
- int* tmp = px;
- px = rhs.px;
- rhs.px = tmp;
- }
-
-private:
- int* px;
-};
-
-} // namespace Photon
-
-#endif // PHOTON_H
diff --git a/sources/shiboken2/tests/libsample/point.cpp b/sources/shiboken2/tests/libsample/point.cpp
deleted file mode 100644
index 75e015e07..000000000
--- a/sources/shiboken2/tests/libsample/point.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "point.h"
-
-using namespace std;
-
-Point::Point(int x, int y) : m_x(x), m_y(y)
-{
-}
-
-Point::Point(double x, double y) : m_x(x), m_y(y)
-{
-}
-
-void
-Point::midpoint(const Point& other, Point* midpoint) const
-{
- if (!midpoint)
- return;
- midpoint->setX((m_x + other.m_x) / 2.0);
- midpoint->setY((m_y + other.m_y) / 2.0);
-}
-
-Point*
-Point::copy() const
-{
- Point* pt = new Point();
- pt->m_x = m_x;
- pt->m_y = m_y;
- return pt;
-}
-
-void
-Point::show()
-{
- cout << "(x: " << m_x << ", y: " << m_y << ")";
-}
-
-bool
-Point::operator==(const Point& other)
-{
- return m_x == other.m_x && m_y == other.m_y;
-}
-
-Point
-Point::operator+(const Point& other)
-{
- return Point(m_x + other.m_x, m_y + other.m_y);
-}
-
-Point
-Point::operator-(const Point& other)
-{
- return Point(m_x - other.m_x, m_y - other.m_y);
-}
-
-Point&
-Point::operator+=(Point &other)
-{
- m_x += other.m_x;
- m_y += other.m_y;
- return *this;
-}
-
-Point&
-Point::operator-=(Point &other)
-{
- m_x -= other.m_x;
- m_y -= other.m_y;
- return *this;
-}
-
-Point
-operator*(const Point& pt, double mult)
-{
- return Point(pt.m_x * mult, pt.m_y * mult);
-}
-
-Point
-operator*(const Point& pt, int mult)
-{
- return Point(((int) pt.m_x) * mult, ((int) pt.m_y) * mult);
-}
-
-Point
-operator*(double mult, const Point& pt)
-{
- return Point(pt.m_x * mult, pt.m_y * mult);
-}
-
-Point
-operator*(int mult, const Point& pt)
-{
- return Point(((int) pt.m_x) * mult, ((int) pt.m_y) * mult);
-}
-
-Point
-operator-(const Point& pt)
-{
- return Point(-pt.m_x, -pt.m_y);
-}
-
-bool
-operator!(const Point& pt)
-{
- return (pt.m_x == 0.0 && pt.m_y == 0.0);
-}
-
-Point
-Point::operator/(int operand)
-{
- return Point(m_x/operand, m_y/operand);
-}
-
-Complex
-transmutePointIntoComplex(const Point& point)
-{
- Complex cpx(point.x(), point.y());
- return cpx;
-}
-
-Point
-transmuteComplexIntoPoint(const Complex& cpx)
-{
- Point pt(cpx.real(), cpx.imag());
- return pt;
-}
-
diff --git a/sources/shiboken2/tests/libsample/point.h b/sources/shiboken2/tests/libsample/point.h
deleted file mode 100644
index 579bcd515..000000000
--- a/sources/shiboken2/tests/libsample/point.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef POINT_H
-#define POINT_H
-
-#include "complex.h"
-#include <utility>
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API Point
-{
-public:
- Point(int x = 0, int y = 0);
- Point(double x, double y);
- ~Point() {}
-
- inline double x() const { return m_x; }
- inline double y() const { return m_y; }
-
- inline void setX(double x) { m_x = x; }
- inline void setY(double y) { m_y = y; }
- inline void setXAsUint(unsigned int x) { m_x = x; }
- inline void setYAsUint(unsigned int y) { m_y = y; }
-
- // This method could simply return the midpoint,
- // but the interesting part of the test is to set the
- // result in the pointer argument.
- void midpoint(const Point& other, Point* midpoint) const;
-
- Point* copy() const;
-
- inline const Point& getConstReferenceToSelf() const { return *this; }
- inline const Point* getSelf() const { return this; }
-
- // The != operator is not implemented for the purpose of testing
- // for the absense of the __ne__ method in the Python binding.
- bool operator==(const Point& other);
-
- Point operator+(const Point& other);
- Point operator-(const Point& other);
- Point operator/(int operand);
-
- friend LIBSAMPLE_API Point operator*(const Point& pt, double mult);
- friend LIBSAMPLE_API Point operator*(const Point& pt, int mult);
- friend LIBSAMPLE_API Point operator*(double mult, const Point& pt);
- friend LIBSAMPLE_API Point operator*(int mult, const Point& pt);
- friend LIBSAMPLE_API Point operator-(const Point& pt);
- friend LIBSAMPLE_API bool operator!(const Point& pt);
-
- Point& operator+=(Point &other);
- Point& operator-=(Point &other);
-
- void show();
-
-private:
- double m_x;
- double m_y;
-};
-
-LIBSAMPLE_API Point operator*(const Point& pt, double mult);
-LIBSAMPLE_API Point operator*(const Point& pt, int mult);
-LIBSAMPLE_API Point operator*(double mult, const Point& pt);
-LIBSAMPLE_API Point operator*(int mult, const Point& pt);
-LIBSAMPLE_API Point operator-(const Point& pt);
-LIBSAMPLE_API bool operator!(const Point& pt);
-
-LIBSAMPLE_API Complex transmutePointIntoComplex(const Point& point);
-LIBSAMPLE_API Point transmuteComplexIntoPoint(const Complex& cpx);
-
-LIBSAMPLE_API Point operator*(const Point& pt, double multiplier);
-
-#endif // POINT_H
diff --git a/sources/shiboken2/tests/libsample/pointerholder.h b/sources/shiboken2/tests/libsample/pointerholder.h
deleted file mode 100644
index b872ceb5c..000000000
--- a/sources/shiboken2/tests/libsample/pointerholder.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef POINTERHOLDER_H
-#define POINTERHOLDER_H
-
-#include "libsamplemacros.h"
-
-class PointerHolder
-{
-public:
- explicit PointerHolder(void* ptr) : m_pointer(ptr) {}
- ~PointerHolder() {}
- inline void* pointer() const { return m_pointer; }
-private:
- void* m_pointer;
-};
-
-#endif // POINTERHOLDER_H
-
diff --git a/sources/shiboken2/tests/libsample/pointf.cpp b/sources/shiboken2/tests/libsample/pointf.cpp
deleted file mode 100644
index fadf3e591..000000000
--- a/sources/shiboken2/tests/libsample/pointf.cpp
+++ /dev/null
@@ -1,126 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "pointf.h"
-
-using namespace std;
-
-PointF::PointF(const Point& point) : m_x(point.x()), m_y(point.y())
-{
-}
-
-PointF::PointF(double x, double y) : m_x(x), m_y(y)
-{
-}
-
-void
-PointF::midpoint(const PointF& other, PointF* midpoint) const
-{
- if (!midpoint)
- return;
- midpoint->setX((m_x + other.m_x) / 2.0);
- midpoint->setY((m_y + other.m_y) / 2.0);
-}
-
-void
-PointF::show()
-{
- cout << "(x: " << m_x << ", y: " << m_y << ")";
-}
-
-bool
-PointF::operator==(const PointF& other)
-{
- return m_x == other.m_x && m_y == other.m_y;
-}
-
-PointF
-PointF::operator+(const PointF& other)
-{
- return PointF(m_x + other.m_x, m_y + other.m_y);
-}
-
-PointF
-PointF::operator-(const PointF& other)
-{
- return PointF(m_x - other.m_x, m_y - other.m_y);
-}
-
-PointF&
-PointF::operator+=(PointF &other)
-{
- m_x += other.m_x;
- m_y += other.m_y;
- return *this;
-}
-
-PointF&
-PointF::operator-=(PointF &other)
-{
- m_x -= other.m_x;
- m_y -= other.m_y;
- return *this;
-}
-
-PointF
-operator*(const PointF& pt, double mult)
-{
- return PointF(pt.m_x * mult, pt.m_y * mult);
-}
-
-PointF
-operator*(const PointF& pt, int mult)
-{
- return PointF(((int) pt.m_x) * mult, ((int) pt.m_y) * mult);
-}
-
-PointF
-operator*(double mult, const PointF& pt)
-{
- return PointF(pt.m_x * mult, pt.m_y * mult);
-}
-
-PointF
-operator*(int mult, const PointF& pt)
-{
- return PointF(((int) pt.m_x) * mult, ((int) pt.m_y) * mult);
-}
-
-PointF
-operator-(const PointF& pt)
-{
- return PointF(-pt.m_x, -pt.m_y);
-}
-
-bool
-operator!(const PointF& pt)
-{
- return (pt.m_x == 0.0 && pt.m_y == 0.0);
-}
-
diff --git a/sources/shiboken2/tests/libsample/pointf.h b/sources/shiboken2/tests/libsample/pointf.h
deleted file mode 100644
index f90125c8a..000000000
--- a/sources/shiboken2/tests/libsample/pointf.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef POINTF_H
-#define POINTF_H
-
-#include "point.h"
-#include <utility>
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API PointF
-{
-public:
- PointF(const Point& point);
- PointF(double x = 0.0, double y = 0.0);
- ~PointF() {}
-
- inline double x() const { return m_x; }
- inline double y() const { return m_y; }
-
- inline void setX(double x) { m_x = x; }
- inline void setY(double y) { m_y = y; }
-
- // This method could simply return the midpoint,
- // but the interesting part of the test is to set the
- // result in the pointer argument.
- void midpoint(const PointF& other, PointF* midpoint) const;
-
- // The != operator is not implemented for the purpose of testing
- // for the absence of the __ne__ method in the Python binding.
- bool operator==(const PointF& other);
-
- PointF operator+(const PointF& other);
- PointF operator-(const PointF& other);
-
- friend LIBSAMPLE_API PointF operator*(const PointF& pt, double mult);
- friend LIBSAMPLE_API PointF operator*(const PointF& pt, int mult);
- friend LIBSAMPLE_API PointF operator*(double mult, const PointF& pt);
- friend LIBSAMPLE_API PointF operator*(int mult, const PointF& pt);
- friend LIBSAMPLE_API PointF operator-(const PointF& pt);
- friend LIBSAMPLE_API bool operator!(const PointF& pt);
-
- PointF& operator+=(PointF &other);
- PointF& operator-=(PointF &other);
-
- void show();
-
-private:
- double m_x;
- double m_y;
-};
-
-LIBSAMPLE_API PointF operator*(const PointF& pt, double mult);
-LIBSAMPLE_API PointF operator*(const PointF& pt, int mult);
-LIBSAMPLE_API PointF operator*(double mult, const PointF& pt);
-LIBSAMPLE_API PointF operator*(int mult, const PointF& pt);
-LIBSAMPLE_API PointF operator-(const PointF& pt);
-LIBSAMPLE_API bool operator!(const PointF& pt);
-
-LIBSAMPLE_API PointF operator*(const PointF& pt, double multiplier);
-
-#endif // POINTF_H
diff --git a/sources/shiboken2/tests/libsample/polygon.cpp b/sources/shiboken2/tests/libsample/polygon.cpp
deleted file mode 100644
index fc0526db2..000000000
--- a/sources/shiboken2/tests/libsample/polygon.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "polygon.h"
-
-using namespace std;
-
-Polygon::Polygon(double x, double y)
-{
- m_points.push_back(Point(x, y));
-}
-
-Polygon::Polygon(Point point)
-{
- m_points.push_back(point);
-}
-
-Polygon::Polygon(PointList points)
-{
- m_points = points;
-}
-
-void
-Polygon::addPoint(Point point)
-{
- m_points.push_back(point);
-}
-
-Polygon
-Polygon::doublePolygonScale(Polygon polygon)
-{
- Polygon result;
- for(PointList::const_iterator piter = result.points().begin(); piter != result.points().end(); piter++)
- result.addPoint((*piter) * 2.0);
- return result;
-}
-
-void
-Polygon::stealOwnershipFromPython(Point* point)
-{
- delete point;
-}
-
-void
-Polygon::stealOwnershipFromPython(Polygon* polygon)
-{
- delete polygon;
-}
-
diff --git a/sources/shiboken2/tests/libsample/polygon.h b/sources/shiboken2/tests/libsample/polygon.h
deleted file mode 100644
index 728332d1a..000000000
--- a/sources/shiboken2/tests/libsample/polygon.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef POLYGON_H
-#define POLYGON_H
-
-#include <list>
-#include "point.h"
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API Polygon
-{
-public:
- using PointList = std::list<Point>;
-
- Polygon() {}
- Polygon(double x, double y);
- Polygon(Point point);
- Polygon(PointList points);
- ~Polygon() {}
-
- void addPoint(Point point);
-
- inline const PointList& points() const { return m_points; }
-
- // This method intentionally receives and returns copies of a Polygon object.
- static Polygon doublePolygonScale(Polygon polygon);
-
- // This method invalidates the argument to be used for Polygon(Point) implicit conversion.
- static void stealOwnershipFromPython(Point* point);
-
- // This method invalidates the argument to be used in a call to doublePolygonScale(Polygon).
- static void stealOwnershipFromPython(Polygon* polygon);
-
-private:
- PointList m_points;
-};
-
-#endif // POLYGON_H
-
diff --git a/sources/shiboken2/tests/libsample/privatector.h b/sources/shiboken2/tests/libsample/privatector.h
deleted file mode 100644
index f168fdacd..000000000
--- a/sources/shiboken2/tests/libsample/privatector.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PRIVATECTOR_H
-#define PRIVATECTOR_H
-
-#include "libsamplemacros.h"
-
-class PrivateCtor
-{
-public:
- inline static PrivateCtor* instance()
- {
- static PrivateCtor self;
- self.m_instanciations++;
- return &self;
- }
-
- inline int instanceCalls()
- {
- return m_instanciations;
- }
-
-private:
- int m_instanciations;
-
- PrivateCtor() : m_instanciations(0) {}
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/privatedtor.h b/sources/shiboken2/tests/libsample/privatedtor.h
deleted file mode 100644
index 64b8652f6..000000000
--- a/sources/shiboken2/tests/libsample/privatedtor.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PRIVATEDTOR_H
-#define PRIVATEDTOR_H
-
-#include "libsamplemacros.h"
-
-class PrivateDtor
-{
-public:
- inline static PrivateDtor* instance()
- {
- static PrivateDtor self;
- self.m_instanciations++;
- return &self;
- }
-
- inline int instanceCalls()
- {
- return m_instanciations;
- }
-
-protected:
- inline int protectedInstanceCalls() { return m_instanciations; }
-
-private:
- int m_instanciations;
-
- PrivateDtor() : m_instanciations(0) {}
- PrivateDtor(const PrivateDtor&) {}
- ~PrivateDtor() {}
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/protected.cpp b/sources/shiboken2/tests/libsample/protected.cpp
deleted file mode 100644
index b0f3f1cdc..000000000
--- a/sources/shiboken2/tests/libsample/protected.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "protected.h"
-
-int ProtectedVirtualDestructor::dtor_called = 0;
-
diff --git a/sources/shiboken2/tests/libsample/protected.h b/sources/shiboken2/tests/libsample/protected.h
deleted file mode 100644
index 0f4fbf299..000000000
--- a/sources/shiboken2/tests/libsample/protected.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PROTECTED_H
-#define PROTECTED_H
-
-#include "libsamplemacros.h"
-#include "objecttype.h"
-#include "point.h"
-#include <string>
-#include <list>
-
-class LIBSAMPLE_API ProtectedNonPolymorphic
-{
-public:
- explicit ProtectedNonPolymorphic(const char *name) : m_name(name) {}
- ~ProtectedNonPolymorphic() {}
-
- inline const char* publicName() { return m_name.c_str(); }
-
- inline static ProtectedNonPolymorphic* create() { return new ProtectedNonPolymorphic("created"); }
-
-protected:
- inline const char* protectedName() { return m_name.c_str(); }
- inline int protectedSum(int a0, int a1) { return a0 + a1; }
- inline int modifiedProtectedSum(int a0, int a1) { return a0 + a1; }
- inline static const char* protectedStatic() { return "protectedStatic"; }
- inline const char* dataTypeName(void *data = nullptr) const { return "pointer"; }
- inline const char* dataTypeName(int data) const { return "integer"; }
-
-private:
- std::string m_name;
-};
-
-class LIBSAMPLE_API ProtectedPolymorphic
-{
-public:
- explicit ProtectedPolymorphic(const char *name) : m_name(name) {}
- virtual ~ProtectedPolymorphic() {}
-
- inline static ProtectedPolymorphic* create() { return new ProtectedPolymorphic("created"); }
- inline const char* publicName() { return m_name.c_str(); }
- inline const char* callProtectedName() { return protectedName(); }
-
-protected:
- virtual const char* protectedName() { return m_name.c_str(); }
-
-private:
- std::string m_name;
-};
-
-class LIBSAMPLE_API ProtectedPolymorphicDaughter : public ProtectedPolymorphic
-{
-public:
- explicit ProtectedPolymorphicDaughter(const char *name) : ProtectedPolymorphic(name) {}
- inline static ProtectedPolymorphicDaughter* create() { return new ProtectedPolymorphicDaughter("created"); }
-};
-
-class LIBSAMPLE_API ProtectedPolymorphicGrandDaughter: public ProtectedPolymorphicDaughter
-{
-public:
- explicit ProtectedPolymorphicGrandDaughter(const char *name) : ProtectedPolymorphicDaughter(name) {}
- inline static ProtectedPolymorphicGrandDaughter* create() { return new ProtectedPolymorphicGrandDaughter("created"); }
-};
-
-class LIBSAMPLE_API ProtectedVirtualDestructor
-{
-public:
- ProtectedVirtualDestructor() {}
- inline static ProtectedVirtualDestructor* create() { return new ProtectedVirtualDestructor(); }
- inline static int dtorCalled() { return dtor_called; }
- inline static void resetDtorCounter() { dtor_called = 0; }
-protected:
- virtual ~ProtectedVirtualDestructor() { dtor_called++; }
-private:
- static int dtor_called;
-};
-
-class LIBSAMPLE_API ProtectedEnumClass
-{
-public:
- ProtectedEnumClass() {}
- virtual ~ProtectedEnumClass() {}
- enum PublicEnum {
- PublicItem0,
- PublicItem1
- };
-protected:
- enum ProtectedEnum {
- ProtectedItem0,
- ProtectedItem1
- };
- ProtectedEnum callProtectedEnumMethod(ProtectedEnum in) { return protectedEnumMethod(in); }
- inline PublicEnum callPublicEnumMethod(PublicEnum in) { return publicEnumMethod(in); }
-
- virtual ProtectedEnum protectedEnumMethod(ProtectedEnum in) { return in; }
- virtual PublicEnum publicEnumMethod(PublicEnum in) { return in; }
-};
-
-
-class LIBSAMPLE_API ProtectedProperty
-{
-public:
- ProtectedProperty()
- : protectedValueTypeProperty(Point(0, 0)),
- protectedProperty(0),
- protectedEnumProperty(Event::NO_EVENT),
- protectedValueTypePointerProperty(nullptr),
- protectedObjectTypeProperty(nullptr)
- {}
-protected:
- // This is deliberately the first member to test wrapper registration
- // for value type members sharing the same memory address.
- Point protectedValueTypeProperty;
- int protectedProperty;
- std::list<int> protectedContainerProperty;
- Event::EventType protectedEnumProperty;
- Point* protectedValueTypePointerProperty;
- ObjectType* protectedObjectTypeProperty;
-};
-
-LIBSAMPLE_API inline ProtectedProperty* createProtectedProperty() {
- return new ProtectedProperty;
-}
-
-#endif // PROTECTED_H
diff --git a/sources/shiboken2/tests/libsample/rect.h b/sources/shiboken2/tests/libsample/rect.h
deleted file mode 100644
index 1897a8dce..000000000
--- a/sources/shiboken2/tests/libsample/rect.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef RECT_H
-#define RECT_H
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API Rect
-{
-public:
- Rect()
- {
- m_left = m_top = 0;
- m_right = m_bottom = -1;
- }
- Rect(int left, int top, int right, int bottom)
- : m_left(left), m_top(top), m_right(right), m_bottom(bottom) { }
- ~Rect() {}
- inline int left() const { return m_left; }
- inline int top() const { return m_top; }
- inline int right() const { return m_right; }
- inline int bottom() const { return m_bottom; }
-private:
- int m_left;
- int m_top;
- int m_right;
- int m_bottom;
-};
-
-class LIBSAMPLE_API RectF
-{
-public:
- RectF()
- {
- m_left = m_top = 0;
- m_right = m_bottom = -1;
- }
- RectF(int left, int top, int right, int bottom)
- : m_left(left), m_top(top), m_right(right), m_bottom(bottom) { }
- RectF(const Rect& other)
- {
- m_left = other.left();
- m_top = other.top();
- m_right = other.right();
- m_bottom = other.bottom();
- }
- ~RectF() {}
- inline double left() const { return m_left; }
- inline double top() const { return m_top; }
- inline double right() const { return m_right; }
- inline double bottom() const { return m_bottom; }
-private:
- double m_left;
- double m_top;
- double m_right;
- double m_bottom;
-};
-
-#endif // RECT_H
-
diff --git a/sources/shiboken2/tests/libsample/reference.cpp b/sources/shiboken2/tests/libsample/reference.cpp
deleted file mode 100644
index 37ce1a590..000000000
--- a/sources/shiboken2/tests/libsample/reference.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "reference.h"
-
-using namespace std;
-
-void
-Reference::show() const
-{
- cout << "Reference.objId: " << m_objId << ", address: " << this;
-}
-
-int
-Reference::usesReferenceVirtual(Reference& r, int inc)
-{
- return r.m_objId + inc;
-}
-
-int
-Reference::usesConstReferenceVirtual(const Reference& r, int inc)
-{
- return r.m_objId + inc;
-}
-
-int
-Reference::callUsesReferenceVirtual(Reference& r, int inc)
-{
- return usesReferenceVirtual(r, inc);
-}
-
-int
-Reference::callUsesConstReferenceVirtual(const Reference& r, int inc)
-{
- return usesConstReferenceVirtual(r, inc);
-}
-
-void
-Reference::alterReferenceIdVirtual(Reference& r)
-{
- r.setObjId(r.objId() * Reference::multiplier());
-}
-
-void
-Reference::callAlterReferenceIdVirtual(Reference& r)
-{
- alterReferenceIdVirtual(r);
-}
-
-ObjTypeReference::~ObjTypeReference()
-{
-}
diff --git a/sources/shiboken2/tests/libsample/reference.h b/sources/shiboken2/tests/libsample/reference.h
deleted file mode 100644
index 2c0498c6f..000000000
--- a/sources/shiboken2/tests/libsample/reference.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef REFERENCE_H
-#define REFERENCE_H
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API Reference
-{
-public:
- explicit Reference(int objId = -1)
- : m_objId(objId) {}
- virtual ~Reference() {}
-
- inline int objId() { return m_objId; }
- inline void setObjId(int objId) { m_objId = objId; }
-
- inline static int usesReference(Reference& r) { return r.m_objId; }
- inline static int usesConstReference(const Reference& r) { return r.m_objId; }
-
- virtual int usesReferenceVirtual(Reference& r, int inc);
- virtual int usesConstReferenceVirtual(const Reference& r, int inc);
-
- int callUsesReferenceVirtual(Reference& r, int inc);
- int callUsesConstReferenceVirtual(const Reference& r, int inc);
-
- virtual void alterReferenceIdVirtual(Reference& r);
- void callAlterReferenceIdVirtual(Reference& r);
-
- void show() const;
-
- inline static int multiplier() { return 10; }
-
- virtual Reference& returnMyFirstArg(Reference& ref) { return ref; }
- virtual Reference& returnMySecondArg(int a, Reference& ref) { return ref; }
-
- // nonsense operator to test if Shiboken is ignoring dereference operators.
- int operator*() { return m_objId; }
-private:
- int m_objId;
-};
-
-class LIBSAMPLE_API ObjTypeReference
-{
-public:
- ObjTypeReference() {}
- ObjTypeReference(const ObjTypeReference&) {}
- virtual ~ObjTypeReference();
- virtual ObjTypeReference& returnMyFirstArg(ObjTypeReference& ref) { return ref; }
- virtual ObjTypeReference& returnMySecondArg(int a, ObjTypeReference& ref) { return ref; }
- virtual ObjTypeReference& justAPureVirtualFunc(ObjTypeReference& ref) = 0;
-};
-
-#endif // REFERENCE_H
-
diff --git a/sources/shiboken2/tests/libsample/removednamespaces.h b/sources/shiboken2/tests/libsample/removednamespaces.h
deleted file mode 100644
index 1de028d38..000000000
--- a/sources/shiboken2/tests/libsample/removednamespaces.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef REMOVEDNAMESPACE_H
-#define REMOVEDNAMESPACE_H
-
-#include "libsamplemacros.h"
-
-namespace RemovedNamespace1
-{
-
-enum RemovedNamespace1_Enum {
- RemovedNamespace1_Enum_Value0
-};
-
-enum {
- RemovedNamespace1_AnonymousEnum_Value0
-};
-
-namespace RemovedNamespace2 {
- enum RemovedNamespace2_Enum {
- RemovedNamespace2_Enum_Value0
- };
-}
-
-}
-
-namespace UnremovedNamespace
-{
-namespace RemovedNamespace3
-{
- enum RemovedNamespace3_Enum {
- RemovedNamespace3_Enum_Value0
- };
-
- enum {
- RemovedNamespace3_AnonymousEnum_Value0
- };
-}
-}
-
-#endif // REMOVEDNAMESPACE_H
-
diff --git a/sources/shiboken2/tests/libsample/renaming.cpp b/sources/shiboken2/tests/libsample/renaming.cpp
deleted file mode 100644
index 30586e1db..000000000
--- a/sources/shiboken2/tests/libsample/renaming.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "renaming.h"
-
-#include <iostream>
-
-int ToBeRenamedValue::value() const
-{
- return m_value;
-}
-
-void ToBeRenamedValue::setValue(int v)
-{
- m_value = v;
-}
-
-void RenamedUser::useRenamedValue(const ToBeRenamedValue &v)
-{
- std::cout << __FUNCTION__ << ' ' << v.value() << '\n';
-}
diff --git a/sources/shiboken2/tests/libsample/renaming.h b/sources/shiboken2/tests/libsample/renaming.h
deleted file mode 100644
index cd88b36bf..000000000
--- a/sources/shiboken2/tests/libsample/renaming.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef RENAMING_H
-#define RENAMING_H
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API ToBeRenamedValue
-{
-public:
- int value() const;
- void setValue(int v);
-
-private:
- int m_value = 42;
-};
-
-class LIBSAMPLE_API RenamedUser
-{
-public:
- void useRenamedValue(const ToBeRenamedValue &v);
-};
-
-#endif // POINT_H
diff --git a/sources/shiboken2/tests/libsample/sample.cpp b/sources/shiboken2/tests/libsample/sample.cpp
deleted file mode 100644
index 638413fd2..000000000
--- a/sources/shiboken2/tests/libsample/sample.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sample.h"
-
-namespace sample
-{
-
-sample::sample(int value) : m_value(value)
-{
-}
-
-int sample::value() const
-{
- return m_value;
-}
-
-bool operator==(const sample&s1, const sample&s2)
-{
- return s1.value() == s2.value();
-}
-} // namespace sample
diff --git a/sources/shiboken2/tests/libsample/sample.h b/sources/shiboken2/tests/libsample/sample.h
deleted file mode 100644
index fe76a53b2..000000000
--- a/sources/shiboken2/tests/libsample/sample.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SAMPLE_H
-#define SAMPLE_H
-
-#include "libsamplemacros.h"
-
-// namespace with the same name of the current package to try to mess up with the generator
-namespace sample
-{
- // to increase the mess we add a class with the same name of the package/namespace
- class LIBSAMPLE_API sample
- {
- public:
- sample(int value = 0);
- int value() const;
- private:
- int m_value;
- };
-
- // shiboken must not generate richcompare for namespace sample
- LIBSAMPLE_API bool operator==(const sample&s1, const sample&s2);
-}
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/samplenamespace.cpp b/sources/shiboken2/tests/libsample/samplenamespace.cpp
deleted file mode 100644
index fc9f6d395..000000000
--- a/sources/shiboken2/tests/libsample/samplenamespace.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include <cstdlib>
-#include <time.h>
-#include "samplenamespace.h"
-
-using namespace std;
-
-namespace SampleNamespace
-{
-
-// PYSIDE-817, scoped enums must not be converted to int in the wrappers generated
-// for the protected hacks
-SomeClass::PublicScopedEnum SomeClass::protectedMethodReturningPublicScopedEnum() const
-{
- return PublicScopedEnum::v1;
-}
-
-OutValue
-enumInEnumOut(InValue in)
-{
- OutValue retval;
- switch(in) {
- case ZeroIn:
- retval = ZeroOut;
- break;
- case OneIn:
- retval = OneOut;
- break;
- case TwoIn:
- retval = TwoOut;
- break;
- default:
- retval = (OutValue) -1;
- }
- return retval;
-}
-
-Option
-enumArgumentWithDefaultValue(Option opt)
-{
- return opt;
-}
-
-int
-getNumber(Option opt)
-{
- int retval;
- switch(opt) {
- case RandomNumber:
- retval = rand() % 100;
- break;
- case UnixTime:
- retval = (int) time(nullptr);
- break;
- default:
- retval = 0;
- }
- return retval;
-}
-
-void
-doSomethingWithArray(const unsigned char* data, unsigned int size, const char* format)
-{
- // This function does nothing in fact.
- // It is here as a dummy copy of QPixmap.loadFromData method
- // to check compilation issues, i.e. if it compiles, it's ok.
-}
-
-int
-enumItemAsDefaultValueToIntArgument(int value)
-{
- return value;
-}
-
-void
-forceDecisorSideA(ObjectType* object)
-{
-}
-
-void
-forceDecisorSideA(const Point& pt, const Str& text, ObjectType* object)
-{
-}
-
-void
-forceDecisorSideB(int a, ObjectType* object)
-{
-}
-
-void
-forceDecisorSideB(int a, const Point& pt, const Str& text, ObjectType* object)
-{
-}
-
-double
-passReferenceToValueType(const Point& point, double multiplier)
-{
- return (point.x() + point.y()) * multiplier;
-}
-
-int
-passReferenceToObjectType(const ObjectType& obj, int multiplier)
-{
- return obj.objectName().size() * multiplier;
-}
-
-} // namespace SampleNamespace
diff --git a/sources/shiboken2/tests/libsample/samplenamespace.h b/sources/shiboken2/tests/libsample/samplenamespace.h
deleted file mode 100644
index 9e46b2ad6..000000000
--- a/sources/shiboken2/tests/libsample/samplenamespace.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SAMPLENAMESPACE_H
-#define SAMPLENAMESPACE_H
-
-#include <list>
-#include "libsamplemacros.h"
-#include "str.h"
-#include "point.h"
-#include "objecttype.h"
-
-// Anonymous global enum
-enum {
- AnonymousGlobalEnum_Value0,
- AnonymousGlobalEnum_Value1
-};
-
-// Invisible namespace
-namespace Invisible
-{
-
-enum EnumOnNamespace {
- Option1 = 1,
- Option2 = 2,
- Option3 = 3
-};
-
-struct ObjectOnInvisibleNamespace
-{
- bool exists() const { return true; }
- static int toInt(EnumOnNamespace e) { return static_cast<int>(e); }
- static ObjectOnInvisibleNamespace consume(const ObjectOnInvisibleNamespace &other) { return other; }
-};
-
-};
-
-namespace SampleNamespace
-{
-
-enum Option {
- None_,
- RandomNumber,
- UnixTime
-};
-
-enum InValue {
- ZeroIn,
- OneIn,
- TwoIn
-};
-
-enum OutValue {
- ZeroOut,
- OneOut,
- TwoOut
-};
-
-// Anonymous non-global enum.
-// This counts as a class enum, since C++ namespaces
-// are represented as classes in Python.
-enum {
- AnonymousClassEnum_Value0,
- AnonymousClassEnum_Value1
-};
-
-LIBSAMPLE_API OutValue enumInEnumOut(InValue in);
-
-LIBSAMPLE_API Option enumArgumentWithDefaultValue(Option opt = UnixTime);
-
-LIBSAMPLE_API int getNumber(Option opt);
-
-inline double powerOfTwo(double num) {
- return num * num;
-}
-
-LIBSAMPLE_API void doSomethingWithArray(const unsigned char *data, unsigned int size, const char *format = nullptr);
-
-LIBSAMPLE_API int enumItemAsDefaultValueToIntArgument(int value = ZeroIn);
-
-class LIBSAMPLE_API SomeClass
-{
-public:
- enum class PublicScopedEnum { v1, v2 };
-
- class SomeInnerClass
- {
- public:
- class OkThisIsRecursiveEnough
- {
- public:
- virtual ~OkThisIsRecursiveEnough() {}
- enum NiceEnum {
- NiceValue1, NiceValue2
- };
-
- enum class NiceEnumClass {
- NiceClassValue1, NiceClassValue2
- };
-
- inline int someMethod(SomeInnerClass*) { return 0; }
- virtual OkThisIsRecursiveEnough* someVirtualMethod(OkThisIsRecursiveEnough* arg) { return arg; }
- };
- protected:
- enum ProtectedEnum {
- ProtectedItem0,
- ProtectedItem1
- };
- };
- struct SomeOtherInnerClass {
- std::list<SomeInnerClass> someInnerClasses;
- };
-protected:
- enum ProtectedEnum {
- ProtectedItem0,
- ProtectedItem1
- };
-
- PublicScopedEnum protectedMethodReturningPublicScopedEnum() const;
-};
-
-LIBSAMPLE_API inline int enumAsInt(SomeClass::PublicScopedEnum value) { return static_cast<int>(value); }
-
-class DerivedFromNamespace : public SomeClass::SomeInnerClass::OkThisIsRecursiveEnough
-{
-public:
- // FIXME Uncomment this when the fix for MSVC is available
- // only to cause namespace confusion
-// enum SampleNamespace {
-// };
- virtual OkThisIsRecursiveEnough* someVirtualMethod(OkThisIsRecursiveEnough* arg) { return arg; }
- inline OkThisIsRecursiveEnough *methodReturningTypeFromParentScope() { return nullptr; }
-};
-
-// The combination of the following two overloaded methods could trigger a
-// problematic behaviour on the overload decisor, if it isn't working properly.
-LIBSAMPLE_API void forceDecisorSideA(ObjectType *object = nullptr);
-LIBSAMPLE_API void forceDecisorSideA(const Point& pt, const Str& text, ObjectType* object = 0);
-
-// The combination of the following two overloaded methods could trigger a
-// problematic behaviour on the overload decisor, if it isn't working properly.
-// This is a variation of forceDecisorSideB.
-LIBSAMPLE_API void forceDecisorSideB(int a, ObjectType *object = nullptr);
-LIBSAMPLE_API void forceDecisorSideB(int a, const Point &pt, const Str &text, ObjectType *object = nullptr);
-
-// Add a new signature on type system with only a Point value as parameter.
-LIBSAMPLE_API double passReferenceToValueType(const Point& point, double multiplier);
-// Add a new signature on type system with only a ObjectType pointer as parameter.
-LIBSAMPLE_API int passReferenceToObjectType(const ObjectType& obj, int multiplier);
-
-} // namespace SampleNamespace
-
-#endif // SAMPLENAMESPACE_H
-
diff --git a/sources/shiboken2/tests/libsample/sbkdate.cpp b/sources/shiboken2/tests/libsample/sbkdate.cpp
deleted file mode 100644
index 8ba18af43..000000000
--- a/sources/shiboken2/tests/libsample/sbkdate.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sbkdate.h"
-
-SbkDate::SbkDate(int d, int m, int y) : m_d(d), m_m(m), m_y(y)
-{
-}
-
-int SbkDate::day() const
-{
- return m_d;
-}
-
-int SbkDate::month() const
-{
- return m_m;
-}
-
-int SbkDate::year() const
-{
- return m_y;
-}
diff --git a/sources/shiboken2/tests/libsample/sbkdate.h b/sources/shiboken2/tests/libsample/sbkdate.h
deleted file mode 100644
index bbe3d3ca8..000000000
--- a/sources/shiboken2/tests/libsample/sbkdate.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SBKDATE_H
-#define SBKDATE_H
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API SbkDate
-{
-public:
- SbkDate(int d, int m, int y);
-
- int day() const;
- int month() const;
- int year() const;
-
-private:
- int m_d;
- int m_m;
- int m_y;
-};
-
-#endif // SBKDATE_H
-
diff --git a/sources/shiboken2/tests/libsample/simplefile.cpp b/sources/shiboken2/tests/libsample/simplefile.cpp
deleted file mode 100644
index 3b68e02c3..000000000
--- a/sources/shiboken2/tests/libsample/simplefile.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <stdlib.h>
-#include <string.h>
-#include <fstream>
-#include "simplefile.h"
-
-class SimpleFile_p
-{
-public:
- SimpleFile_p(const char* filename) : m_descriptor(nullptr), m_size(0)
- {
- m_filename = strdup(filename);
- }
-
- ~SimpleFile_p()
- {
- free(m_filename);
- }
-
- char* m_filename;
- FILE* m_descriptor;
- long m_size;
-};
-
-SimpleFile::SimpleFile(const char* filename)
-{
- p = new SimpleFile_p(filename);
-}
-
-SimpleFile::~SimpleFile()
-{
- close();
- delete p;
-}
-
-const char* SimpleFile::filename()
-{
- return p->m_filename;
-}
-
-long SimpleFile::size()
-{
- return p->m_size;
-}
-
-bool
-SimpleFile::open()
-{
- if ((p->m_descriptor = fopen(p->m_filename, "rb")) == nullptr)
- return false;
-
- fseek(p->m_descriptor, 0, SEEK_END);
- p->m_size = ftell(p->m_descriptor);
- rewind(p->m_descriptor);
-
- return true;
-}
-
-void
-SimpleFile::close()
-{
- if (p->m_descriptor) {
- fclose(p->m_descriptor);
- p->m_descriptor = nullptr;
- }
-}
-
-bool
-SimpleFile::exists() const
-{
- std::ifstream ifile(p->m_filename);
- return !ifile.fail();
-}
-
-bool
-SimpleFile::exists(const char* filename)
-{
- std::ifstream ifile(filename);
- return !ifile.fail();
-}
-
diff --git a/sources/shiboken2/tests/libsample/simplefile.h b/sources/shiboken2/tests/libsample/simplefile.h
deleted file mode 100644
index 7a437a99d..000000000
--- a/sources/shiboken2/tests/libsample/simplefile.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SIMPLEFILE_H
-#define SIMPLEFILE_H
-
-#include "libsamplemacros.h"
-#include <stdio.h>
-
-class SimpleFile_p;
-
-class LIBSAMPLE_API SimpleFile
-{
-public:
- explicit SimpleFile(const char* filename);
- ~SimpleFile();
-
- const char* filename();
- long size();
- bool open();
- void close();
-
- bool exists() const;
- static bool exists(const char* filename);
-
-private:
- SimpleFile_p *p;
-};
-
-#endif // SIMPLEFILE_H
-
diff --git a/sources/shiboken2/tests/libsample/size.cpp b/sources/shiboken2/tests/libsample/size.cpp
deleted file mode 100644
index 4c195161e..000000000
--- a/sources/shiboken2/tests/libsample/size.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "size.h"
-
-using namespace std;
-
-void
-Size::show() const
-{
- cout << "(width: " << m_width << ", height: " << m_height << ")";
-}
-
diff --git a/sources/shiboken2/tests/libsample/size.h b/sources/shiboken2/tests/libsample/size.h
deleted file mode 100644
index 76502b416..000000000
--- a/sources/shiboken2/tests/libsample/size.h
+++ /dev/null
@@ -1,206 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SIZE_H
-#define SIZE_H
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API Size
-{
-public:
- Size(double width = 0.0, double height = 0.0) : m_width(width), m_height(height) {}
- ~Size() {}
-
- inline double width() { return m_width; }
- inline void setWidth(double width) { m_width = width; }
- inline double height() { return m_height; }
- inline void setHeight(double height) { m_height = height; }
-
- inline double calculateArea() const { return m_width * m_height; }
-
- // Comparison Operators
- inline bool operator==(const Size& other)
- {
- return m_width == other.m_width && m_height == other.m_height;
- }
-
- inline bool operator<(const Size& other)
- {
- return calculateArea() < other.calculateArea();
- }
-
- inline bool operator>(const Size& other)
- {
- // On some x86 hardware and compiler combinations, floating point
- // comparisons may fail due to a hardware bug. One workaround is to
- // simplify comparison expressions by putting partial results in
- // variables. See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=323#c109
- // for details.
- double a = calculateArea();
- double b = other.calculateArea();
- return a > b;
- }
-
- inline bool operator<=(const Size& other)
- {
- // See comments for operator>()
- double a = calculateArea();
- double b = other.calculateArea();
- return a <= b;
- }
-
- inline bool operator>=(const Size& other)
- {
- return calculateArea() >= other.calculateArea();
- }
-
- inline bool operator<(double area) { return calculateArea() < area; }
- inline bool operator>(double area) { return calculateArea() > area; }
- inline bool operator<=(double area) { return calculateArea() <= area; }
- inline bool operator>=(double area) { return calculateArea() >= area; }
-
- // Arithmetic Operators
- inline Size& operator+=(const Size& s)
- {
- m_width += s.m_width;
- m_height += s.m_height;
- return *this;
- }
-
- inline Size& operator-=(const Size& s)
- {
- m_width -= s.m_width;
- m_height -= s.m_height;
- return *this;
- }
-
- inline Size& operator*=(double mult)
- {
- m_width *= mult;
- m_height *= mult;
- return *this;
- }
-
- inline Size& operator/=(double div)
- {
- m_width /= div;
- m_height /= div;
- return *this;
- }
-
- // TODO: add ++size, size++, --size, size--
-
- // External operators
- friend inline bool operator!=(const Size&, const Size&);
- friend inline const Size operator+(const Size&, const Size&);
- friend inline const Size operator-(const Size&, const Size&);
- friend inline const Size operator*(const Size&, double);
- friend inline const Size operator*(double, const Size&);
- friend inline const Size operator/(const Size&, double);
-
- friend inline bool operator<(double, const Size&);
- friend inline bool operator>(double, const Size&);
- friend inline bool operator<=(double, const Size&);
- friend inline bool operator>=(double, const Size&);
-
- void show() const;
-
-private:
- double m_width;
- double m_height;
-};
-
-// Comparison Operators
-inline bool operator!=(const Size& s1, const Size& s2)
-{
- return s1.m_width != s2.m_width || s1.m_height != s2.m_height;
-}
-
-inline bool operator<(double area, const Size& s)
-{
- return area < s.calculateArea();
-}
-
-inline bool operator>(double area, const Size& s)
-{
- return area > s.calculateArea();
-}
-
-inline bool operator<=(double area, const Size& s)
-{
- return area <= s.calculateArea();
-}
-
-inline bool operator>=(double area, const Size& s)
-{
- return area >= s.calculateArea();
-}
-
-// Arithmetic Operators
-inline const Size operator+(const Size& s1, const Size& s2)
-{
- return Size(s1.m_width + s2.m_width, s1.m_height + s2.m_height);
-}
-
-inline const Size operator-(const Size& s1, const Size& s2)
-{
- return Size(s1.m_width - s2.m_width, s1.m_height - s2.m_height);
-}
-
-inline const Size operator*(const Size& s, double mult)
-{
- return Size(s.m_width * mult, s.m_height * mult);
-}
-
-inline const Size operator*(double mult, const Size& s)
-{
- return Size(s.m_width * mult, s.m_height * mult);
-}
-
-inline const Size operator/(const Size& s, double div)
-{
- return Size(s.m_width / div, s.m_height / div);
-}
-
-using real = double;
-using ushort = unsigned short;
-class LIBSAMPLE_API SizeF
-{
-public:
- SizeF(real width, real height) : m_width(width), m_height(height) {}
- real width() { return m_width; }
- real height() { return m_height; }
- static inline ushort passTypedefOfUnsignedShort(ushort value) { return value; }
-private:
- real m_width;
- real m_height;
-};
-
-#endif // SIZE_H
-
diff --git a/sources/shiboken2/tests/libsample/sometime.cpp b/sources/shiboken2/tests/libsample/sometime.cpp
deleted file mode 100644
index 851b3b913..000000000
--- a/sources/shiboken2/tests/libsample/sometime.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sometime.h"
-#include <stdio.h>
-
-void
-Time::setTime()
-{
- m_hour = 0;
- m_minute = 0;
- m_second = 0;
- m_msec = 0;
- m_is_null = true;
-}
-
-void
-Time::setTime(int h, int m, int s, int ms)
-{
- m_hour = h;
- m_minute = m;
- m_second = s;
- m_msec = ms;
- m_is_null = false;
-}
-
-
-Time::NumArgs
-Time::somethingCompletelyDifferent()
-{
- return ZeroArgs;
-}
-
-Time::NumArgs
-Time::somethingCompletelyDifferent(int h, int m, ImplicitConv ic, ObjectType* type)
-{
- if (type)
- return FourArgs;
- if (ic.ctorEnum() == ImplicitConv::CtorThree && ic.objId() == -1)
- return TwoArgs;
- return ThreeArgs;
-}
-
-Str
-Time::toString() const
-{
- if (m_is_null)
- return Str();
- char buffer[13];
- sprintf(buffer, "%02d:%02d:%02d.%03d", m_hour, m_minute, m_second, m_msec);
- return Str(buffer);
-}
-
-bool
-Time::operator==(const Time& other) const
-{
- return m_hour == other.m_hour
- && m_minute == other.m_minute
- && m_second == other.m_second
- && m_msec == other.m_msec
- && m_is_null == other.m_is_null;
-}
-
-bool
-Time::operator!=(const Time& other) const
-{
- return !operator==(other);
-}
-
-Time::operator Str() const
-{
- return Time::toString();
-}
-
diff --git a/sources/shiboken2/tests/libsample/sometime.h b/sources/shiboken2/tests/libsample/sometime.h
deleted file mode 100644
index ef16efa29..000000000
--- a/sources/shiboken2/tests/libsample/sometime.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SOMETIME_H
-#define SOMETIME_H
-
-#include "libsamplemacros.h"
-#include "str.h"
-#include "implicitconv.h"
-#include "objecttype.h"
-
-class LIBSAMPLE_API Time
-{
-public:
- enum NumArgs {
- ZeroArgs,
- TwoArgs,
- ThreeArgs,
- FourArgs
- };
-
- Time()
- : m_hour(0), m_minute(0), m_second(0), m_msec(0), m_is_null(true)
- {}
- Time(int h, int m, int s = 0, int ms = 0)
- : m_hour(h), m_minute(m), m_second(s), m_msec(ms), m_is_null(false)
- {}
-
- ~Time() {}
-
- inline bool isNull() const { return m_is_null; }
-
- inline int hour() const { return m_hour; }
- inline int minute() const { return m_minute; }
- inline int second() const { return m_second; }
- inline int msec() const { return m_msec; }
-
- void setTime();
- void setTime(int h, int m, int s = 0, int ms = 0);
-
- // This one is completely different from the other methods in this class,
- // it was added to give the overload decisor a really hard time with
- // an value-type with implicit conversion and a default argument, and also
- // an object-type, just because I feel like it.
- NumArgs somethingCompletelyDifferent();
- NumArgs somethingCompletelyDifferent(int h, int m,
- ImplicitConv ic = ImplicitConv::CtorThree,
- ObjectType *type = nullptr);
-
- Str toString() const;
- bool operator==(const Time& other) const;
- bool operator!=(const Time& other) const;
-
- // This cast operator must become an implicit conversion of Str.
- operator Str() const;
-
-private:
- int m_hour;
- int m_minute;
- int m_second;
- int m_msec;
-
- bool m_is_null;
-};
-
-#endif // SOMETIME_H
-
diff --git a/sources/shiboken2/tests/libsample/str.cpp b/sources/shiboken2/tests/libsample/str.cpp
deleted file mode 100644
index 634bd4a86..000000000
--- a/sources/shiboken2/tests/libsample/str.cpp
+++ /dev/null
@@ -1,185 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "str.h"
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-#include <sstream>
-
-using namespace std;
-
-Str::Str(const Str& s)
-{
- init(s.cstring());
-}
-
-Str::Str(char c)
-{
- char str[2] = { c, 0 };
- init(str);
-}
-
-Str::Str(const char* cstr)
-{
- init(cstr);
-}
-
-void
-Str::init(const char* cstr)
-{
- if (cstr)
- m_str = cstr;
-}
-
-Str::~Str()
-{
-}
-
-Str
-Str::arg(const Str& s) const
-{
- size_t idx = m_str.find_first_of("%VAR");
- if (idx == std::string::npos) {
- return *this;
- } else {
- std::string result = m_str;
- result.replace(idx, 4, s.m_str);
- return result.c_str();
- }
-}
-
-Str&
-Str::append(const Str& s)
-{
- m_str += s.m_str;
- return *this;
-}
-
-Str&
-Str::prepend(const Str& s)
-{
- m_str = s.m_str + m_str;
- return *this;
-}
-
-const char*
-Str::cstring() const
-{
- return m_str.c_str();
-}
-
-int
-Str::toInt(bool* ok, int base) const
-{
- bool my_ok;
- int result = 0;
- istringstream conv(m_str);
- switch (base) {
- case 8:
- conv >> std::oct >> result;
- break;
- case 10:
- conv >> std::dec >> result;
- break;
- case 16:
- conv >> std::hex >> result;
- break;
- }
- my_ok = istringstream::eofbit & conv.rdstate();
- if (!my_ok)
- result = 0;
- if (ok)
- *ok = my_ok;
- return result;
-}
-
-void
-Str::show() const
-{
- printf("%s", cstring());
-}
-
-char
-Str::get_char(int pos) const
-{
- return m_str[pos];
-}
-
-bool
-Str::set_char(int pos, char ch)
-{
- m_str[pos] = ch;
- return true;
-}
-
-Str Str::operator+(int number) const
-{
- ostringstream in;
- in << m_str << number;
- return in.str().c_str();
-}
-
-bool Str::operator==(const Str& other) const
-{
- return m_str == other.m_str;
-}
-
-Str operator+(int number, const Str& str)
-{
- ostringstream in;
- in << number << str.m_str;
- return in.str().c_str();
-}
-
-bool Str::operator<(const Str& other) const
-{
- return m_str < other.m_str;
-}
-
-unsigned int strHash(const Str& str)
-{
- unsigned int result = 0;
- const std::string& cppStr = str.m_str;
- std::string::const_iterator it = cppStr.begin();
- for (; it != cppStr.end(); ++it)
- result = 5 * result + *it;
- return result;
-}
-
-void changePStr(PStr* pstr, const char* suffix)
-{
- pstr->append(suffix);
-}
-
-void duplicatePStr(PStr* pstr)
-{
- if (!pstr)
- return;
- pstr->append(*pstr);
-}
diff --git a/sources/shiboken2/tests/libsample/str.h b/sources/shiboken2/tests/libsample/str.h
deleted file mode 100644
index 2f7cee8c3..000000000
--- a/sources/shiboken2/tests/libsample/str.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef STR_H
-#define STR_H
-#include <string>
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API Str
-{
-public:
- Str(const Str& s);
- Str(char c);
- Str(const char* cstr = "");
- ~Str();
-
- Str arg(const Str& s) const;
-
- Str& append(const Str& s);
- Str& prepend(const Str& s);
-
- const char* cstring() const;
- char get_char(int pos) const;
- bool set_char(int pos, char ch);
-
- int toInt(bool *ok = nullptr, int base = 10) const;
-
- void show() const;
-
- inline int size() const { return m_str.size(); }
-
- // nonsense operator just to test reverse operators
- Str operator+(int number) const;
- bool operator==(const Str& other) const;
- bool operator<(const Str& other) const;
-
-private:
- void init(const char* cstr);
- std::string m_str;
-
- friend LIBSAMPLE_API Str operator+(int number, const Str& str);
- friend LIBSAMPLE_API unsigned int strHash(const Str& str);
-};
-
-LIBSAMPLE_API Str operator+(int number, const Str& str);
-LIBSAMPLE_API unsigned int strHash(const Str& str);
-
-using PStr = Str;
-LIBSAMPLE_API void changePStr(PStr* pstr, const char* suffix);
-LIBSAMPLE_API void duplicatePStr(PStr *pstr = nullptr);
-
-#endif // STR_H
diff --git a/sources/shiboken2/tests/libsample/strlist.cpp b/sources/shiboken2/tests/libsample/strlist.cpp
deleted file mode 100644
index e523522f3..000000000
--- a/sources/shiboken2/tests/libsample/strlist.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "strlist.h"
-
-bool
-StrList::operator==(const std::list<Str>& other) const
-{
- if (size() != other.size())
- return false;
- StrList::const_iterator this_it = begin();
- StrList::const_iterator other_it = begin();
- while (this_it != end()) {
- if (!((*this_it) == (*other_it)))
- return false;
- ++this_it;
- ++other_it;
- }
- return true;
-}
-
-Str
-StrList::join(const Str& sep) const
-{
- Str result;
- for (StrList::const_iterator it = begin(); it != end(); ++it) {
- if (it != begin())
- result.append(sep);
- result.append(*it);
- }
- return result;
-}
diff --git a/sources/shiboken2/tests/libsample/strlist.h b/sources/shiboken2/tests/libsample/strlist.h
deleted file mode 100644
index 43aa15390..000000000
--- a/sources/shiboken2/tests/libsample/strlist.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef STRLIST_H
-#define STRLIST_H
-
-#include <list>
-#include "str.h"
-
-#include "libsamplemacros.h"
-
-class LIBSAMPLE_API StrList : public std::list<Str>
-{
-public:
- enum CtorEnum {
- NoParamsCtor,
- StrCtor,
- CopyCtor,
- ListOfStrCtor
- };
-
- inline StrList() : m_ctorUsed(NoParamsCtor) {}
- inline explicit StrList(const Str& str) : m_ctorUsed(StrCtor) { push_back(str); }
- inline StrList(const StrList& lst) : std::list<Str>(lst), m_ctorUsed(CopyCtor) {}
- inline StrList(const std::list<Str>& lst) : std::list<Str>(lst), m_ctorUsed(ListOfStrCtor) {}
-
- inline void append(Str str) { push_back(str); }
- Str join(const Str& sep) const;
-
- bool operator==(const std::list<Str>& other) const;
- inline bool operator!=(const std::list<Str>& other) const { return !(*this == other); }
-
- CtorEnum constructorUsed() { return m_ctorUsed; }
-private:
- CtorEnum m_ctorUsed;
-};
-
-using PStrList = StrList;
-
-#endif // STRLIST_H
diff --git a/sources/shiboken2/tests/libsample/templateptr.cpp b/sources/shiboken2/tests/libsample/templateptr.cpp
deleted file mode 100644
index fa5bb8206..000000000
--- a/sources/shiboken2/tests/libsample/templateptr.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "templateptr.h"
-
-void TemplatePtr::dummy(std::list<std::pair<BlackBox *, BlackBox *> > & items)
-{
-} \ No newline at end of file
diff --git a/sources/shiboken2/tests/libsample/templateptr.h b/sources/shiboken2/tests/libsample/templateptr.h
deleted file mode 100644
index 584b64185..000000000
--- a/sources/shiboken2/tests/libsample/templateptr.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TEMPLATEPTR_H
-#define TEMPLATEPTR_H
-
-#include <utility>
-#include <list>
-#include "libsamplemacros.h"
-#include "blackbox.h"
-
-class LIBSAMPLE_API TemplatePtr
-{
-public:
- void dummy(std::list<std::pair<BlackBox *, BlackBox *> > & items);
-};
-
-#endif
diff --git a/sources/shiboken2/tests/libsample/transform.cpp b/sources/shiboken2/tests/libsample/transform.cpp
deleted file mode 100644
index 840f1feac..000000000
--- a/sources/shiboken2/tests/libsample/transform.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2013 Kitware, Inc.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "transform.h"
-
-#ifdef _WIN32
-#include <math.h>
-#include <float.h>
-static inline bool isfinite(double a) { return _finite(a); }
-#else
-#include <cmath>
-#endif
-
-using namespace std;
-
-Point applyHomogeneousTransform(
- const Point& in,
- double m11, double m12, double m13,
- double m21, double m22, double m23,
- double m31, double m32, double m33,
- bool* okay)
-{
- double x = m11 * in.x() + m12 * in.y() + m13;
- double y = m21 * in.x() + m22 * in.y() + m23;
- double w = m31 * in.x() + m32 * in.y() + m33;
-
- if (isfinite(w) && fabs(w) > 1e-10)
- {
- if (okay)
- *okay = true;
- return Point(x / w, y / w);
- }
- else
- {
- if (okay)
- *okay = false;
- return Point();
- }
-}
diff --git a/sources/shiboken2/tests/libsample/transform.h b/sources/shiboken2/tests/libsample/transform.h
deleted file mode 100644
index d9ec98dd4..000000000
--- a/sources/shiboken2/tests/libsample/transform.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2013 Kitware, Inc.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef TRANSFORM_H
-#define TRANSFORM_H
-
-#include "point.h"
-
-#include "libsamplemacros.h"
-
-LIBSAMPLE_API Point
-applyHomogeneousTransform(
- const Point& in,
- double m11, double m12, double m13,
- double m21, double m22, double m23,
- double m31, double m32, double m33,
- bool* okay);
-
-#endif // TRANSFORM_H
diff --git a/sources/shiboken2/tests/libsample/valueandvirtual.h b/sources/shiboken2/tests/libsample/valueandvirtual.h
deleted file mode 100644
index 34a6788e2..000000000
--- a/sources/shiboken2/tests/libsample/valueandvirtual.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef VALUEANDVIRTUAL_H
-#define VALUEANDVIRTUAL_H
-
-class ValueAndVirtual
-{
-public:
- ValueAndVirtual(int id) : m_id(id) {}
- ValueAndVirtual(const ValueAndVirtual &other) { m_id = other.m_id; }
-
- bool operator()(int id, int id2) { return id == id2; }
-
- inline int id() { return m_id; }
- virtual ~ValueAndVirtual() {};
-private:
- int m_id;
-};
-
-#endif // VALUEANDVIRTUAL_H
-
diff --git a/sources/shiboken2/tests/libsample/virtualmethods.cpp b/sources/shiboken2/tests/libsample/virtualmethods.cpp
deleted file mode 100644
index 294feca60..000000000
--- a/sources/shiboken2/tests/libsample/virtualmethods.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "virtualmethods.h"
-
-int VirtualDtor::dtor_called = 0;
-
-double
-VirtualMethods::virtualMethod0(Point pt, int val, Complex cpx, bool b)
-{
- return (pt.x() * pt.y() * val) + cpx.imag() + ((int) b);
-}
-
-bool
-VirtualMethods::createStr(const char* text, Str*& ret)
-{
- if (!text) {
- ret = nullptr;
- return false;
- }
-
- ret = new Str(text);
- return true;
-}
-
-void
-VirtualMethods::getMargins(int* left, int* top, int* right, int* bottom) const
-{
- *left = m_left;
- *top = m_top;
- *right = m_right;
- *bottom = m_bottom;
-}
-
-double VirtualDaughter2::virtualMethod0(Point pt, int val, Complex cpx, bool b)
-{
- return 42 + VirtualMethods::virtualMethod0(pt, val, cpx, b);
-}
-
-int VirtualDaughter2::sum0(int a0, int a1, int a2)
-{
- return 42 + VirtualMethods::sum0(a0, a1, a2);
-}
-
-double VirtualFinalDaughter::virtualMethod0(Point pt, int val, Complex cpx, bool b)
-{
- return 42 + VirtualMethods::virtualMethod0(pt, val, cpx, b);
-}
-
-int VirtualFinalDaughter::sum0(int a0, int a1, int a2)
-{
- return 42 + VirtualMethods::sum0(a0, a1, a2);
-}
diff --git a/sources/shiboken2/tests/libsample/virtualmethods.h b/sources/shiboken2/tests/libsample/virtualmethods.h
deleted file mode 100644
index 3e4c8c504..000000000
--- a/sources/shiboken2/tests/libsample/virtualmethods.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef VIRTUALMETHODS_H
-#define VIRTUALMETHODS_H
-
-#include "point.h"
-#include "complex.h"
-#include "str.h"
-
-#include "libsamplemacros.h"
-#include "strlist.h"
-
-class LIBSAMPLE_API VirtualMethods
-{
-public:
- VirtualMethods(Str name = "VirtualMethods") : m_name(name)
- {
- m_left = m_top = m_right = m_bottom = 0;
- }
- virtual ~VirtualMethods() {}
-
- virtual double virtualMethod0(Point pt, int val, Complex cpx, bool b);
- double callVirtualMethod0(Point pt, int val, Complex cpx, bool b)
- {
- return virtualMethod0(pt, val, cpx, b);
- }
-
- // Binding modification: rename.
- virtual int sum0(int a0, int a1, int a2) { return a0 + a1 + a2; }
- int callSum0(int a0, int a1, int a2) { return sum0(a0, a1, a2); }
-
- // Binding modification: set default value for the last argument.
- virtual int sum1(int a0, int a1, int a2) { return a0 + a1 + a2; }
- int callSum1(int a0, int a1, int a2) { return sum1(a0, a1, a2); }
-
- // Binding modification: remove the last argument and set a default value for it.
- virtual int sum2(int a0, int a1, int a2) { return a0 + a1 + a2; }
- int callSum2(int a0, int a1, int a2) { return sum2(a0, a1, a2); }
-
- // Binding modification: remove the second argument.
- virtual int sum3(int a0, int a1, int a2) { return a0 + a1 + a2; }
- int callSum3(int a0, int a1, int a2) { return sum3(a0, a1, a2); }
-
- // Binding modification: remove the second argument and set its default
- // value, then inject code on the binding reimplementation of the virtual
- // (with a native inject-code) to sum the value of the removed
- // argument to the first argument before the method is called.
- virtual int sum4(int a0, int a1, int a2) { return a0 + a1 + a2; }
- int callSum4(int a0, int a1, int a2) { return sum4(a0, a1, a2); }
-
- // Binding modification: prepend a string to the results of a Python override.
- virtual Str name() { return m_name; }
- Str callName() { return name(); }
-
- // Binding modification: code injection that calls the Python override by itself.
- virtual void callMe() {}
- void callCallMe() { callMe(); }
-
- // Passing reference to pointers.
- virtual bool createStr(const char* text, Str*& ret);
- bool callCreateStr(const char* text, Str*& ret) { return createStr(text, ret); }
-
- // Return a non-binded method
- std::list<Str> callStrListToStdList(const StrList& strList) { return strListToStdList(strList); }
- virtual std::list<Str> strListToStdList(const StrList& strList ) { return strList; }
-
- void setMargins(int left, int top, int right, int bottom)
- {
- m_left = left;
- m_top = top;
- m_right = right;
- m_bottom = bottom;
- }
- virtual void getMargins(int* left, int* top, int* right, int* bottom) const;
- void callGetMargins(int* left, int* top, int* right, int* bottom) const
- {
- getMargins(left, top, right, bottom);
- }
-
- virtual int recursionOnModifiedVirtual(Str arg) const { return 0; }
- int callRecursionOnModifiedVirtual(Str arg) const { return recursionOnModifiedVirtual(arg); }
-
-private:
- Str m_name;
- int m_left;
- int m_top;
- int m_right;
- int m_bottom;
-};
-
-class LIBSAMPLE_API VirtualDaughter : public VirtualMethods
-{
-public:
- VirtualDaughter() : VirtualMethods() {}
- VirtualDaughter(Str name) : VirtualMethods(name) {}
-};
-
-class LIBSAMPLE_API VirtualDaughter2 : public VirtualMethods
-{
-public:
- VirtualDaughter2() : VirtualMethods("VirtualDaughter2") {}
-
- double virtualMethod0(Point pt, int val, Complex cpx, bool b) override;
- int sum0(int a0, int a1, int a2) final;
-};
-
-class LIBSAMPLE_API VirtualFinalDaughter final : public VirtualMethods
-{
-public:
- VirtualFinalDaughter() : VirtualMethods("VirtualFinalDaughter") {}
-
- double virtualMethod0(Point pt, int val, Complex cpx, bool b) override;
- int sum0(int a0, int a1, int a2) override;
-};
-
-class LIBSAMPLE_API VirtualDtor
-{
-public:
- VirtualDtor() {}
- virtual ~VirtualDtor() { dtor_called++; }
-
- static VirtualDtor* create() { return new VirtualDtor(); }
- static int dtorCalled() { return dtor_called; }
- static void resetDtorCounter() { dtor_called = 0; }
-
-private:
- static int dtor_called;
-};
-
-#endif // VIRTUALMETHODS_H
-
diff --git a/sources/shiboken2/tests/libsample/voidholder.h b/sources/shiboken2/tests/libsample/voidholder.h
deleted file mode 100644
index 367e99ddf..000000000
--- a/sources/shiboken2/tests/libsample/voidholder.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef VOIDHOLDER_H
-#define VOIDHOLDER_H
-
-#include "libsamplemacros.h"
-
-class VoidHolder
-{
-public:
- explicit VoidHolder(void *ptr = nullptr) : m_ptr(ptr) {}
- ~VoidHolder() {}
- inline void* voidPointer() { return m_ptr; }
- inline static void* gimmeMeSomeVoidPointer()
- {
- static void* pointerToSomething = new VoidHolder();
- return pointerToSomething;
- }
- void *takeVoidPointer(void *item)
- {
- return item;
- }
-private:
- void* m_ptr;
-};
-
-#endif // VOIDHOLDER_H
-
diff --git a/sources/shiboken2/tests/libsmart/CMakeLists.txt b/sources/shiboken2/tests/libsmart/CMakeLists.txt
deleted file mode 100644
index 152c57f25..000000000
--- a/sources/shiboken2/tests/libsmart/CMakeLists.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-project(libsmart)
-
-set(libsmart_SRC
-smart.cpp
-)
-
-add_library(libsmart SHARED ${libsmart_SRC})
-target_include_directories(libsmart PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
-target_compile_definitions(libsmart PRIVATE LIBSMART_BUILD)
-set_property(TARGET libsmart PROPERTY PREFIX "")
-
diff --git a/sources/shiboken2/tests/libsmart/libsmartmacros.h b/sources/shiboken2/tests/libsmart/libsmartmacros.h
deleted file mode 100644
index d85e219bb..000000000
--- a/sources/shiboken2/tests/libsmart/libsmartmacros.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef LIB_SMART_MACROS_H
-#define LIB_SMART_MACROS_H
-
-#if defined _WIN32 || defined __CYGWIN__
- #if LIBSMART_BUILD
- #define LIB_SMART_API __declspec(dllexport)
- #else
- #define LIB_SMART_API __declspec(dllimport)
- #endif
-#else
-#if __GNUC__ >= 4
- #define LIB_SMART_API __attribute__ ((visibility("default")))
-#else
- #define LIB_SMART_API
-#endif
-#endif
-
-#endif
diff --git a/sources/shiboken2/tests/libsmart/smart.cpp b/sources/shiboken2/tests/libsmart/smart.cpp
deleted file mode 100644
index 81fa30c7e..000000000
--- a/sources/shiboken2/tests/libsmart/smart.cpp
+++ /dev/null
@@ -1,261 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "smart.h"
-
-#include <algorithm>
-#include <iostream>
-
-static inline bool shouldPrint()
-{
- return Registry::getInstance()->shouldPrint();
-}
-
-void SharedPtrBase::logDefaultConstructor(const void *t)
-{
- if (shouldPrint())
- std::cout << "shared_ptr default constructor " << t << '\n';
-}
-
-void SharedPtrBase::logConstructor(const void *t, const void *pointee)
-{
- if (shouldPrint()) {
- std::cout << "shared_ptr constructor " << t << " with pointer "
- << pointee << '\n';
- }
-}
-
-void SharedPtrBase::logCopyConstructor(const void *t, const void *refData)
-{
- if (shouldPrint()) {
- std::cout << "shared_ptr copy constructor " << t << " with pointer "
- << refData << '\n';
- }
-}
-
-void SharedPtrBase::logAssignment(const void *t, const void *refData)
-{
- if (shouldPrint()) {
- std::cout << "shared_ptr assignment operator " << t << " with pointer "
- << refData << "\n";
- }
-}
-
-void SharedPtrBase::logDestructor(const void *t, int remainingRefCount)
-{
- if (shouldPrint()) {
- std::cout << "shared_ptr destructor " << t << " remaining refcount "
- << remainingRefCount << '\n';
- }
-}
-
-Obj::Obj() : m_integer(123), m_internalInteger(new Integer)
-{
- Registry::getInstance()->add(this);
- if (shouldPrint())
- std::cout << "Object constructor " << this << '\n';
-}
-
-Obj::~Obj()
-{
- Registry::getInstance()->remove(this);
- delete m_internalInteger;
- if (shouldPrint())
- std::cout << "Object destructor " << this << '\n';
-}
-
-
-void Obj::printObj() {
- if (shouldPrint()) {
- std::cout << "integer value: " << m_integer
- << " internal integer value: " << m_internalInteger->value() << '\n';
- }
-}
-
-
-SharedPtr<Obj> Obj::giveSharedPtrToObj()
-{
- SharedPtr<Obj> o(new Obj);
- return o;
-}
-
-std::vector<SharedPtr<Obj> > Obj::giveSharedPtrToObjList(int size)
-{
- std::vector<SharedPtr<Obj> > r;
- for (int i=0; i < size; i++)
- r.push_back(giveSharedPtrToObj());
- return r;
-}
-
-
-SharedPtr<Integer> Obj::giveSharedPtrToInteger()
-{
- SharedPtr<Integer> o(new Integer);
- return o;
-}
-
-SharedPtr<Smart::Integer2> Obj::giveSharedPtrToInteger2()
-{
- SharedPtr<Smart::Integer2> o(new Smart::Integer2);
- return o;
-}
-
-int Obj::takeSharedPtrToObj(SharedPtr<Obj> pObj)
-{
- pObj->printObj();
- return pObj->m_integer;
-}
-
-int Obj::takeSharedPtrToInteger(SharedPtr<Integer> pInt)
-{
- pInt->printInteger();
- return pInt->value();
-}
-
-SharedPtr<const Integer> Obj::giveSharedPtrToConstInteger()
-{
- SharedPtr<const Integer> co(new Integer);
- return co;
-}
-
-int Obj::takeSharedPtrToConstInteger(SharedPtr<const Integer> pInt)
-{
- return pInt->m_int;
-}
-
-Integer Obj::takeInteger(Integer val)
-{
- return val;
-}
-
-Integer::Integer() : m_int(456)
-{
- Registry::getInstance()->add(this);
- if (shouldPrint())
- std::cout << "Integer constructor " << this << '\n';
-}
-
-Integer::Integer(const Integer &other)
-{
- Registry::getInstance()->add(this);
- if (shouldPrint())
- std::cout << "Integer copy constructor " << this << '\n';
- m_int = other.m_int;
-}
-
-Integer &Integer::operator=(const Integer &other)
-{
- Registry::getInstance()->add(this);
- if (shouldPrint())
- std::cout << "Integer operator= " << this << '\n';
- m_int = other.m_int;
- return *this;
-}
-
-Integer::~Integer()
-{
- Registry::getInstance()->remove(this);
- if (shouldPrint())
- std::cout << "Integer destructor " << this << '\n';
-}
-
-int Integer::value() const
-{
- return m_int;
-}
-
-void Integer::setValue(int v)
-{
- m_int = v;
-}
-
-void Integer::printInteger() const
-{
- if (shouldPrint())
- std::cout << "Integer value for object " << this << " is " << m_int << '\n';
-}
-
-Registry *Registry::getInstance()
-{
- static Registry registry;
- return &registry;
-}
-
-Registry::Registry() = default;
-
-Registry::~Registry() = default;
-
-void Registry::add(Obj *p)
-{
- m_objects.push_back(p);
-}
-
-void Registry::add(Integer *p)
-{
- m_integers.push_back(p);
-}
-
-void Registry::remove(Obj *p)
-{
- m_objects.erase(std::remove(m_objects.begin(), m_objects.end(), p), m_objects.end());
-}
-
-void Registry::remove(Integer *p)
-{
- m_integers.erase(std::remove(m_integers.begin(), m_integers.end(), p), m_integers.end());
-}
-
-int Registry::countObjects() const
-{
- return static_cast<int>(m_objects.size());
-}
-
-int Registry::countIntegers() const
-{
- return static_cast<int>(m_integers.size());
-}
-
-bool Registry::shouldPrint() const
-{
- return m_printStuff;
-}
-
-void Registry::setShouldPrint(bool flag)
-{
- m_printStuff = flag;
-}
-
-Smart::Integer2::Integer2()
- : Integer ()
-{
-}
-
-Smart::Integer2::Integer2(const Smart::Integer2 &other)
- : Integer (other)
-{
-}
diff --git a/sources/shiboken2/tests/libsmart/smart.h b/sources/shiboken2/tests/libsmart/smart.h
deleted file mode 100644
index 6238f27d5..000000000
--- a/sources/shiboken2/tests/libsmart/smart.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SMART_H
-#define SMART_H
-
-#include "smart_sharedptr.h"
-#include "smart_integer.h"
-#include "smart_obj.h"
-#include "smart_registry.h"
-
-#endif // SMART_H
diff --git a/sources/shiboken2/tests/libsmart/smart_integer.h b/sources/shiboken2/tests/libsmart/smart_integer.h
deleted file mode 100644
index 126894120..000000000
--- a/sources/shiboken2/tests/libsmart/smart_integer.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SMART_INTEGER_H
-#define SMART_INTEGER_H
-
-#include "libsmartmacros.h"
-
-class LIB_SMART_API Integer {
-public:
- Integer();
- Integer(const Integer &other);
- Integer &operator=(const Integer &other);
- ~Integer();
- void printInteger() const;
-
- int value() const;
- void setValue(int v);
-
- int m_int; // public for testing member field access.
-};
-
-namespace Smart {
-class LIB_SMART_API Integer2 : public Integer {
-public:
- Integer2();
- Integer2(const Integer2 &other);
-};
-} // namespace Smart
-
-#endif // SMART_INTEGER_H
diff --git a/sources/shiboken2/tests/libsmart/smart_obj.h b/sources/shiboken2/tests/libsmart/smart_obj.h
deleted file mode 100644
index 8fe45993f..000000000
--- a/sources/shiboken2/tests/libsmart/smart_obj.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SMART_OBJ_H
-#define SMART_OBJ_H
-
-#include "libsmartmacros.h"
-#include "smart_sharedptr.h"
-
-#include <vector>
-
-class Integer;
-class Obj;
-namespace Smart { class Integer2; }
-
-// Couldn't name it Object because it caused some namespace clashes.
-class LIB_SMART_API Obj {
-public:
- Obj();
- virtual ~Obj();
-
- void printObj();
- Integer takeInteger(Integer val);
- SharedPtr<Obj> giveSharedPtrToObj();
- std::vector<SharedPtr<Obj> > giveSharedPtrToObjList(int size);
- virtual SharedPtr<Integer> giveSharedPtrToInteger(); // virtual for PYSIDE-1188
- SharedPtr<const Integer> giveSharedPtrToConstInteger();
- int takeSharedPtrToConstInteger(SharedPtr<const Integer> pInt);
- SharedPtr<Smart::Integer2> giveSharedPtrToInteger2();
- int takeSharedPtrToObj(SharedPtr<Obj> pObj);
- int takeSharedPtrToInteger(SharedPtr<Integer> pInt);
-
- int m_integer; // public for testing member field access.
- Integer *m_internalInteger;
-};
-
-#endif // SMART_OBJ_H
diff --git a/sources/shiboken2/tests/libsmart/smart_registry.h b/sources/shiboken2/tests/libsmart/smart_registry.h
deleted file mode 100644
index 6171ddb59..000000000
--- a/sources/shiboken2/tests/libsmart/smart_registry.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SMART_REGISTRY_H
-#define SMART_REGISTRY_H
-
-#include <vector>
-
-#include "libsmartmacros.h"
-
-class Obj;
-class Integer;
-
-// Used to track which C++ objects are alive.
-class LIB_SMART_API Registry {
-public:
- static Registry *getInstance();
- ~Registry();
-
- Registry(const Registry &) = delete;
- Registry &operator=(const Registry &) = delete;
- Registry(Registry &&) = delete;
- Registry &operator=(Registry &&) = delete;
-
- void add(Obj *p);
- void add(Integer *p);
- void remove(Obj *p);
- void remove(Integer *p);
- int countObjects() const;
- int countIntegers() const;
- bool shouldPrint() const;
- void setShouldPrint(bool flag);
-
-protected:
- Registry();
-
-private:
- std::vector<Obj *> m_objects;
- std::vector<Integer *> m_integers;
- bool m_printStuff = false;
-};
-
-#endif // SMART_REGISTRY_H
diff --git a/sources/shiboken2/tests/libsmart/smart_sharedptr.h b/sources/shiboken2/tests/libsmart/smart_sharedptr.h
deleted file mode 100644
index 84184e1f8..000000000
--- a/sources/shiboken2/tests/libsmart/smart_sharedptr.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2019 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SMART_SHARED_PTR_H
-#define SMART_SHARED_PTR_H
-
-#include "libsmartmacros.h"
-
-template <class T>
-class RefData {
-public:
- RefData(T *ptr) : m_refCount(1), m_heldPtr(ptr) {}
- ~RefData() { delete m_heldPtr; }
- int inc() { return ++m_refCount; }
- int dec() { return --m_refCount; }
- int useCount() { return m_refCount; }
- int m_refCount;
- T *m_heldPtr;
-};
-
-struct SharedPtrBase
-{
- LIB_SMART_API static void logDefaultConstructor(const void *t);
- LIB_SMART_API static void logConstructor(const void *t, const void *pointee);
- LIB_SMART_API static void logCopyConstructor(const void *t, const void *refData);
- LIB_SMART_API static void logAssignment(const void *t, const void *refData);
- LIB_SMART_API static void logDestructor(const void *t, int remainingRefCount);
-};
-
-template <class T>
-class SharedPtr : public SharedPtrBase {
-public:
- SharedPtr() { logDefaultConstructor(this); }
-
- SharedPtr(T *v)
- {
- logConstructor(this, v);
- if (v)
- m_refData = new RefData<T>(v);
- }
-
- SharedPtr(const SharedPtr<T> &other) : m_refData(other.m_refData)
- {
- logCopyConstructor(this, other.m_refData);
- if (m_refData)
- m_refData->inc();
- }
-
- SharedPtr<T> &operator=(const SharedPtr<T>& other)
- {
- if (this != &other) {
- logAssignment(this, other.m_refData);
- if (m_refData && m_refData->dec() == 0)
- delete m_refData;
- m_refData = other.m_refData;
- if (m_refData)
- m_refData->inc();
- }
- return *this;
- }
-
- T *data() const
- {
- return m_refData ? m_refData->m_heldPtr : nullptr;
- }
-
- int useCount() const
- {
- return m_refData ? m_refData->useCount() : 0;
- }
-
- void dummyMethod1()
- {
-
- }
-
- T& operator*() const
- {
- // Crashes if smart pointer is empty (just like std::shared_ptr).
- return *(m_refData->m_heldPtr);
- }
-
- T *operator->() const
- {
- return m_refData ? m_refData->m_heldPtr : nullptr;
- }
-
- bool operator!() const
- {
- return !m_refData || !m_refData->m_heldPtr;
- }
-
- bool isNull() const
- {
- return !m_refData || !m_refData->m_heldPtr;
- }
-
- operator bool() const
- {
- return m_refData && m_refData->m_heldPtr;
- }
-
- ~SharedPtr()
- {
- if (m_refData)
- logDestructor(this, m_refData->useCount() - 1);
- if (m_refData && m_refData->dec() == 0)
- delete m_refData;
- }
-
-private:
- RefData<T> *m_refData = nullptr;
-};
-
-#endif // SMART_SHARED_PTR_H
diff --git a/sources/shiboken2/tests/minimalbinding/CMakeLists.txt b/sources/shiboken2/tests/minimalbinding/CMakeLists.txt
deleted file mode 100644
index ffeb086a0..000000000
--- a/sources/shiboken2/tests/minimalbinding/CMakeLists.txt
+++ /dev/null
@@ -1,36 +0,0 @@
-project(minimal)
-
-set(minimal_TYPESYSTEM
-${CMAKE_CURRENT_SOURCE_DIR}/typesystem_minimal.xml
-)
-
-set(minimal_SRC
-${CMAKE_CURRENT_BINARY_DIR}/minimal/minimal_module_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/minimal/obj_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/minimal/val_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/minimal/listuser_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/minimal/minbooluser_wrapper.cpp
-)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/minimal-binding.txt.in"
- "${CMAKE_CURRENT_BINARY_DIR}/minimal-binding.txt" @ONLY)
-
-add_custom_command(
-OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/mjb_rejected_classes.log"
-BYPRODUCTS ${minimal_SRC}
-COMMAND shiboken2 --project-file=${CMAKE_CURRENT_BINARY_DIR}/minimal-binding.txt ${GENERATOR_EXTRA_FLAGS}
-DEPENDS ${minimal_TYPESYSTEM} ${CMAKE_CURRENT_SOURCE_DIR}/global.h shiboken2
-WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
-COMMENT "Running generator for 'minimal' test binding..."
-)
-
-add_library(minimal MODULE ${minimal_SRC})
-target_include_directories(minimal PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
-target_link_libraries(minimal PUBLIC libminimal libshiboken)
-set_property(TARGET minimal PROPERTY PREFIX "")
-set_property(TARGET minimal PROPERTY OUTPUT_NAME "minimal${PYTHON_EXTENSION_SUFFIX}")
-if(WIN32)
- set_property(TARGET minimal PROPERTY SUFFIX ".pyd")
-endif()
-
-create_generator_target(minimal)
diff --git a/sources/shiboken2/tests/minimalbinding/brace_pattern_test.py b/sources/shiboken2/tests/minimalbinding/brace_pattern_test.py
deleted file mode 100644
index e48027d2a..000000000
--- a/sources/shiboken2/tests/minimalbinding/brace_pattern_test.py
+++ /dev/null
@@ -1,125 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:LGPL$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU Lesser General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU Lesser
-## General Public License version 3 as published by the Free Software
-## Foundation and appearing in the file LICENSE.LGPL3 included in the
-## packaging of this file. Please review the following information to
-## ensure the GNU Lesser General Public License version 3 requirements
-## will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 2.0 or (at your option) the GNU General
-## Public license version 3 or any later version approved by the KDE Free
-## Qt Foundation. The licenses are as published by the Free Software
-## Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-2.0.html and
-## https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import absolute_import, print_function
-
-import os
-import re
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import shiboken2
-type.__signature__ # trigger bootstrap
-
-from shibokensupport.signature.lib.tool import build_brace_pattern
-
-"""
-This test tests the brace pattern from signature.lib.tool
-against a slower reference implementation.
-The pattern is crucial, because it is used heavily in signature.parser .
-"""
-
-# A slow reference parser for braces and strings
-def check(s):
- open, close = "[{(<", "]})>"
- escape, quote = "\\", '"'
- instring = blind = False
- stack = []
- for c in s:
- if instring:
- if blind:
- blind = False
- elif c == escape:
- blind = True
- elif c == quote:
- instring = False
- stack.pop()
- continue
- if c in open:
- stack.append(c)
- elif c in close:
- pos = close.index(c)
- if ((len(stack) > 0) and
- (open[pos] == stack[len(stack)-1])):
- stack.pop()
- else:
- return False
- elif c == escape:
- return False
- elif c == quote:
- instring = True
- stack.append(c)
- return len(stack) == 0
-
-
-class TestBracePattern(unittest.TestCase):
- tests = [
- (r'{[]{()}}', True),
- (r'[{}{})(]', False),
- (r'[{}{} ")(" ]', True),
- (r'[{}{} ")(\" ]', False),
- (r'[{}{} ")(\" ]"]', True),
- (r'a < b ( c [ d { "} \"\"}" } ] ) >', True),
- (r'a < b ( c [ d { } ] ) >', True),
- (r'a < b ( c [ d { "huh" } ] ) >', True),
- (r'a < b ( c [ d { "huh\" \" \\\"" } ] ) >', True),
- ]
-
- def test_checkfunc(self):
- for test, result in self.tests:
- if result:
- self.assertTrue(check(test))
- else:
- self.assertFalse(check(test))
-
- def test_the_brace_pattern(self):
- func = re.compile(build_brace_pattern(5) + "$", re.VERBOSE).match
- for test, result in self.tests:
- if result:
- self.assertTrue(func(test))
- else:
- self.assertFalse(func(test))
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/minimalbinding/global.h b/sources/shiboken2/tests/minimalbinding/global.h
deleted file mode 100644
index 1b06245c4..000000000
--- a/sources/shiboken2/tests/minimalbinding/global.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "obj.h"
-#include "val.h"
-#include "minbool.h"
-#include "listuser.h"
-#include "typedef.h"
diff --git a/sources/shiboken2/tests/minimalbinding/listuser_test.py b/sources/shiboken2/tests/minimalbinding/listuser_test.py
deleted file mode 100644
index e69bce346..000000000
--- a/sources/shiboken2/tests/minimalbinding/listuser_test.py
+++ /dev/null
@@ -1,330 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from minimal import ListUser, Val, Obj
-from py3kcompat import IS_PY3K
-
-if IS_PY3K:
- import functools
- reduce = functools.reduce
-
-
-class ExtListUser(ListUser):
- def __init__(self):
- ListUser.__init__(self)
-
- def createIntList(self, num):
- return list(range(0, num * 2, 2))
-
- def sumIntList(self, intList):
- return sum(intList) * 2
-
- def createMinBoolList(self, mb1, mb2):
- return [not mb1, not mb2]
-
- def oredMinBoolList(self, minBoolList):
- return not reduce(lambda a, b: a|b, minBoolList)
-
- def createValList(self, num):
- return [Val(i) for i in range(0, num * 2, 2)]
-
- def sumValList(self, valList):
- return sum([val.valId() for val in valList]) * 2
-
- def createObjList(self, o1, o2):
- o1.setObjId(o1.objId() * 2)
- o2.setObjId(o2.objId() * 2)
- return [o1, o2]
-
- def sumObjList(self, objList):
- return sum([obj.objId() for obj in objList]) * 2
-
- def createListOfIntLists(self, num):
- return [self.createIntList(num)] * 4
-
- def sumListOfIntLists(self, intListList):
- return sum([sum(line) for line in intListList]) * 2
-
-
-class IntListConversionTest(unittest.TestCase):
-
- def testCreateIntList(self):
- num = 4
- lu = ListUser()
- lst = lu.createIntList(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), int)
- self.assertEqual(lst, list(range(num)))
- lst = lu.callCreateIntList(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), int)
- self.assertEqual(lst, list(range(num)))
-
- def testCreateIntListFromExtendedClass(self):
- lu = ExtListUser()
- num = 4
- lst = lu.createIntList(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), int)
- self.assertEqual(lst, list(range(0, num * 2, 2)))
- lst = lu.callCreateIntList(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), int)
- self.assertEqual(lst, list(range(0, num * 2, 2)))
-
- def testSumIntList(self):
- lu = ListUser()
- lst = range(4)
- self.assertEqual(lu.sumIntList(lst), sum(lst))
- self.assertEqual(lu.callSumIntList(lst), sum(lst))
-
- def testSumIntListFromExtendedClass(self):
- lu = ExtListUser()
- lst = range(4)
- self.assertEqual(lu.sumIntList(lst), sum(lst) * 2)
- self.assertEqual(lu.callSumIntList(lst), sum(lst) * 2)
-
-
-class MinBoolListConversionTest(unittest.TestCase):
-
- def testCreateMinBoolList(self):
- lu = ListUser()
- lst = lu.createMinBoolList(True, False)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), 2)
- for i in lst:
- self.assertEqual(type(i), bool)
- self.assertEqual(lst, [True, False])
-
- lst = lu.callCreateMinBoolList(False, True)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), 2)
- for i in lst:
- self.assertEqual(type(i), bool)
- self.assertEqual(lst, [False, True])
-
- def testCreateMinBoolListFromExtendedClass(self):
- lu = ExtListUser()
- lst = lu.createMinBoolList(True, False)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), 2)
- for i in lst:
- self.assertEqual(type(i), bool)
- self.assertEqual(lst, [False, True])
-
- lst = lu.callCreateMinBoolList(False, True)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), 2)
- for i in lst:
- self.assertEqual(type(i), bool)
- self.assertEqual(lst, [True, False])
-
- def testOredMinBoolList(self):
- lu = ListUser()
- lst = [False, False, True]
- self.assertTrue(lu.oredMinBoolList(lst))
- self.assertTrue(lu.callOredMinBoolList(lst))
- lst = [False, False, False]
- self.assertFalse(lu.oredMinBoolList(lst))
- self.assertFalse(lu.callOredMinBoolList(lst))
-
- def testOredMinBoolListFromExtendedClass(self):
- lu = ExtListUser()
- lst = [False, False, True]
- self.assertFalse(lu.oredMinBoolList(lst))
- self.assertFalse(lu.callOredMinBoolList(lst))
- lst = [False, False, False]
- self.assertTrue(lu.oredMinBoolList(lst))
- self.assertTrue(lu.callOredMinBoolList(lst))
-
-
-class ValListConversionTest(unittest.TestCase):
-
- def testCreateValList(self):
- num = 4
- lu = ListUser()
- lst = lu.createValList(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), Val)
- self.assertEqual([val.valId() for val in lst], list(range(num)))
- lst = lu.callCreateValList(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), Val)
- self.assertEqual([val.valId() for val in lst], list(range(num)))
-
- def testCreateValListFromExtendedClass(self):
- lu = ExtListUser()
- num = 4
- lst = lu.createValList(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), Val)
- self.assertEqual([val.valId() for val in lst], list(range(0, num * 2, 2)))
- lst = lu.callCreateValList(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), Val)
- self.assertEqual([val.valId() for val in lst], list(range(0, num * 2, 2)))
-
- def testSumValList(self):
- lu = ListUser()
- lst = [Val(i) for i in range(4)]
- self.assertEqual(lu.sumValList(lst), sum([val.valId() for val in lst]))
- self.assertEqual(lu.callSumValList(lst), sum([val.valId() for val in lst]))
-
- def testSumValListFromExtendedClass(self):
- lu = ExtListUser()
- lst = [Val(i) for i in range(4)]
- self.assertEqual(lu.sumValList(lst), sum([val.valId() for val in lst]) * 2)
- self.assertEqual(lu.callSumValList(lst), sum([val.valId() for val in lst]) * 2)
-
-
-class ObjListConversionTest(unittest.TestCase):
-
- def testCreateObjList(self):
- o1 = Obj(1)
- o2 = Obj(2)
- lu = ListUser()
- lst = lu.createObjList(o1, o2)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), 2)
- for i in lst:
- self.assertEqual(type(i), Obj)
- self.assertEqual(lst, [o1, o2])
- self.assertEqual([obj.objId() for obj in lst], [1, 2])
-
- lst = lu.callCreateObjList(o1, o2)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), 2)
- for i in lst:
- self.assertEqual(type(i), Obj)
- self.assertEqual(lst, [o1, o2])
- self.assertEqual([obj.objId() for obj in lst], [1, 2])
-
- def testCreateObjListFromExtendedClass(self):
- o1 = Obj(1)
- o2 = Obj(2)
- lu = ExtListUser()
- lst = lu.createObjList(o1, o2)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), 2)
- for i in lst:
- self.assertEqual(type(i), Obj)
- self.assertEqual(lst, [o1, o2])
- self.assertEqual([obj.objId() for obj in lst], [2, 4])
-
- lst = lu.callCreateObjList(o1, o2)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), 2)
- for i in lst:
- self.assertEqual(type(i), Obj)
- self.assertEqual(lst, [o1, o2])
- self.assertEqual([obj.objId() for obj in lst], [4, 8])
-
- def testSumObjList(self):
- lu = ListUser()
- lst = [Obj(i) for i in list(range(4))]
- self.assertEqual(lu.sumObjList(lst), sum([obj.objId() for obj in lst]))
- self.assertEqual(lu.callSumObjList(lst), sum([obj.objId() for obj in lst]))
-
- def testSumObjListFromExtendedClass(self):
- lu = ExtListUser()
- lst = [Obj(i) for i in list(range(4))]
- self.assertEqual(lu.sumObjList(lst), sum([obj.objId() for obj in lst]) * 2)
- self.assertEqual(lu.callSumObjList(lst), sum([obj.objId() for obj in lst]) * 2)
-
-
-class ListOfIntListConversionTest(unittest.TestCase):
-
- def testCreateListOfIntLists(self):
- num = 4
- lu = ListUser()
- lst = lu.createListOfIntLists(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), list)
- self.assertEqual(i, list(range(num)))
- for j in i:
- self.assertEqual(type(j), int)
- self.assertEqual(lst, [list(range(num))] * 4)
-
- def testCreateListOfIntListsFromExtendedClass(self):
- num = 4
- lu = ExtListUser()
- lst = lu.createListOfIntLists(num)
- self.assertEqual(type(lst), list)
- self.assertEqual(len(lst), num)
- for i in lst:
- self.assertEqual(type(i), list)
- self.assertEqual(i, list(range(0, num * 2, 2)))
- for j in i:
- self.assertEqual(type(j), int)
- self.assertEqual(lst, [list(range(0, num * 2, 2))] * 4)
-
- def testSumListIntLists(self):
- lu = ListUser()
- lst = [range(4)] * 4
- self.assertEqual(lu.sumListOfIntLists(lst), sum([sum(line) for line in [range(4)] * 4]))
- self.assertEqual(lu.callSumListOfIntLists(lst), sum([sum(line) for line in [range(4)] * 4]))
-
- def testSumListOfIntListsFromExtendedClass(self):
- lu = ExtListUser()
- lst = [range(4)] * 4
- self.assertEqual(lu.sumListOfIntLists(lst), sum([sum(line) for line in [range(4)] * 4]) * 2)
- self.assertEqual(lu.callSumListOfIntLists(lst), sum([sum(line) for line in [range(4)] * 4]) * 2)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/minimalbinding/minbool_test.py b/sources/shiboken2/tests/minimalbinding/minbool_test.py
deleted file mode 100644
index adc0929fd..000000000
--- a/sources/shiboken2/tests/minimalbinding/minbool_test.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from minimal import MinBoolUser
-
-class DerivedMinBoolUser (MinBoolUser):
- def returnMyselfVirtual(self):
- return MinBoolUser()
-
-class MinBoolTest(unittest.TestCase):
-
- def testMinBoolUser(self):
- mbuTrue = MinBoolUser()
- mbuFalse = MinBoolUser()
- mbuTrue.setMinBool(True)
- self.assertEqual(mbuFalse.minBool(), False)
- self.assertEqual(mbuTrue.minBool(), True)
- self.assertEqual(mbuTrue.callInvertedMinBool(), False)
-
- self.assertEqual(mbuTrue.minBool() == True, True)
- self.assertEqual(False == mbuFalse.minBool(), True)
- self.assertEqual(mbuTrue.minBool() == mbuFalse.minBool(), False)
-
- self.assertEqual(mbuFalse.minBool() != True, True)
- self.assertEqual(True != mbuFalse.minBool(), True)
- self.assertEqual(mbuTrue.minBool() != mbuFalse.minBool(), True)
-
- def testVirtuals(self):
- dmbu = DerivedMinBoolUser()
- self.assertEqual(dmbu.invertedMinBool(), True)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/minimalbinding/minimal-binding.txt.in b/sources/shiboken2/tests/minimalbinding/minimal-binding.txt.in
deleted file mode 100644
index 85b139676..000000000
--- a/sources/shiboken2/tests/minimalbinding/minimal-binding.txt.in
+++ /dev/null
@@ -1,15 +0,0 @@
-[generator-project]
-
-generator-set = shiboken
-
-header-file = @CMAKE_CURRENT_SOURCE_DIR@/global.h
-typesystem-file = @minimal_TYPESYSTEM@
-
-output-directory = @CMAKE_CURRENT_BINARY_DIR@
-
-include-path = @libminimal_SOURCE_DIR@
-
-typesystem-path = @CMAKE_CURRENT_SOURCE_DIR@
-
-enable-parent-ctor-heuristic
-use-isnull-as-nb_nonzero
diff --git a/sources/shiboken2/tests/minimalbinding/obj_test.py b/sources/shiboken2/tests/minimalbinding/obj_test.py
deleted file mode 100644
index a0869a67b..000000000
--- a/sources/shiboken2/tests/minimalbinding/obj_test.py
+++ /dev/null
@@ -1,120 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from minimal import Obj
-
-class ExtObj(Obj):
- def __init__(self, objId):
- Obj.__init__(self, objId)
- self.virtual_method_called = False
-
- def virtualMethod(self, val):
- self.virtual_method_called = True
- return not Obj.virtualMethod(self, val)
-
- def passObjectType(self, obj):
- obj.setObjId(obj.objId() + 1)
- return obj
-
- def passObjectTypeReference(self, obj):
- obj.setObjId(obj.objId() + 1)
- return obj
-
-
-class ObjTest(unittest.TestCase):
-
- def testNormalMethod(self):
- objId = 123
- obj = Obj(objId)
- self.assertEqual(obj.objId(), objId)
-
- def testNormalMethodFromExtendedClass(self):
- objId = 123
- obj = ExtObj(objId)
- self.assertEqual(obj.objId(), objId)
-
- def testVirtualMethod(self):
- obj = Obj(0)
- even_number = 8
- self.assertEqual(obj.virtualMethod(even_number), obj.callVirtualMethod(even_number))
-
- def testVirtualMethodFromExtendedClass(self):
- obj = ExtObj(0)
- even_number = 8
- self.assertEqual(obj.virtualMethod(even_number), obj.callVirtualMethod(even_number))
- self.assertTrue(obj.virtual_method_called)
-
- def testPassObjectType(self):
- obj = Obj(0)
- self.assertEqual(obj, obj.passObjectType(obj))
- self.assertEqual(obj, obj.callPassObjectType(obj))
-
- def testPassObjectTypeNone(self):
- obj = Obj(0)
- self.assertEqual(None, obj.passObjectType(None))
- self.assertEqual(None, obj.callPassObjectType(None))
-
- def testPassObjectTypeReference(self):
- obj = Obj(0)
- self.assertEqual(obj, obj.passObjectTypeReference(obj))
- self.assertEqual(obj, obj.callPassObjectTypeReference(obj))
-
- def testPassObjectTypeFromExtendedClass(self):
- obj = ExtObj(0)
- self.assertEqual(obj.objId(), 0)
- sameObj = obj.passObjectType(obj)
- self.assertEqual(obj, sameObj)
- self.assertEqual(sameObj.objId(), 1)
- sameObj = obj.callPassObjectType(obj)
- self.assertEqual(obj, sameObj)
- self.assertEqual(sameObj.objId(), 2)
-
- def testPassObjectTypeReferenceFromExtendedClass(self):
- obj = ExtObj(0)
- self.assertEqual(obj.objId(), 0)
- sameObj = obj.passObjectTypeReference(obj)
- self.assertEqual(obj, sameObj)
- self.assertEqual(sameObj.objId(), 1)
- sameObj = obj.callPassObjectTypeReference(obj)
- self.assertEqual(obj, sameObj)
- self.assertEqual(sameObj.objId(), 2)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/minimalbinding/typedef_test.py b/sources/shiboken2/tests/minimalbinding/typedef_test.py
deleted file mode 100644
index 6595d0467..000000000
--- a/sources/shiboken2/tests/minimalbinding/typedef_test.py
+++ /dev/null
@@ -1,122 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from minimal import *
-from py3kcompat import IS_PY3K
-
-try:
- import numpy as np
-except ImportError as e:
- print(e)
- np = None
-
-
-if IS_PY3K:
- import functools
- reduce = functools.reduce
-
-
-class TypedefTest(unittest.TestCase):
-
- def setUp(self):
- self.the_size = 8
-
- def test_arrayFuncInt(self):
- none = ()
- full = range(self.the_size)
- self.assertTrue(arrayFuncInt(none), "None is empty, arrayFuncInt should return true")
- self.assertFalse(arrayFuncInt(full), "Full is NOT empty, arrayFuncInt should return false")
-
- self.assertTrue(arrayFuncInt(np.array(none)), "None is empty, arrayFuncInt should return true")
- self.assertFalse(arrayFuncInt(np.array(full)), "Full is NOT empty, arrayFuncInt should return false")
-
- def test_arrayFuncIntTypedef(self):
- none = ()
- full = (1, 2, 3)
- self.assertTrue(arrayFuncIntTypedef(none), "None is empty, arrayFuncIntTypedef should return true")
- self.assertFalse(arrayFuncIntTypedef(full), "Full is NOT empty, arrayFuncIntTypedef should return false")
-
- self.assertTrue(arrayFuncIntTypedef(np.array(none)), "None is empty, arrayFuncIntTypedef should return true")
- self.assertFalse(arrayFuncIntTypedef(np.array(full)), "Full is NOT empty, arrayFuncIntTypedef should return false")
-
- def test_arrayFuncIntReturn(self):
- none = arrayFuncIntReturn(0)
- full = arrayFuncIntReturn(self.the_size)
- self.assertTrue((len(none) == 0), "none should be empty")
- self.assertTrue((len(full) == self.the_size), "full should have " + str(self.the_size) + " elements")
-
- def test_arrayFuncIntReturnTypedef(self):
- none = arrayFuncIntReturnTypedef(0)
- full = arrayFuncIntReturnTypedef(self.the_size)
- self.assertTrue((len(none) == 0), "none should be empty")
- self.assertTrue((len(full) == self.the_size), "full should have " + str(self.the_size) + " elements")
-
- def test_arrayFunc(self):
- none = ()
- full = range(self.the_size)
- self.assertTrue(arrayFunc(none), "None is empty, arrayFunc should return true")
- self.assertFalse(arrayFunc(full), "Full is NOT empty, arrayFunc should return false")
-
- self.assertTrue(arrayFunc(np.array(none)), "None is empty, arrayFunc should return true")
- self.assertFalse(arrayFunc(np.array(full)), "Full is NOT empty, arrayFunc should return false")
-
- def test_arrayFuncTypedef(self):
- none = ()
- full = (1, 2, 3)
- self.assertTrue(arrayFuncTypedef(none), "None is empty, arrayFuncTypedef should return true")
- self.assertFalse(arrayFuncTypedef(full), "Full is NOT empty, arrayFuncTypedef should return false")
-
- self.assertTrue(arrayFuncTypedef(np.array(none)), "None is empty, arrayFuncTypedef should return true")
- self.assertFalse(arrayFuncTypedef(np.array(full)), "Full is NOT empty, arrayFuncTypedef should return false")
-
- def test_arrayFuncReturn(self):
- none = arrayFuncReturn(0)
- full = arrayFuncReturn(self.the_size)
- self.assertTrue((len(none) == 0), "none should be empty")
- self.assertTrue((len(full) == self.the_size), "full should have " + str(self.the_size) + " elements")
-
- def test_arrayFuncReturnTypedef(self):
- none = arrayFuncReturnTypedef(0)
- full = arrayFuncReturnTypedef(self.the_size)
- self.assertTrue((len(none) == 0), "none should be empty")
- self.assertTrue((len(full) == self.the_size), "full should have " + str(self.the_size) + " elements")
-
-
-if __name__ == '__main__':
- if np != None:
- unittest.main()
diff --git a/sources/shiboken2/tests/minimalbinding/typesystem_minimal.xml b/sources/shiboken2/tests/minimalbinding/typesystem_minimal.xml
deleted file mode 100644
index 03b88a970..000000000
--- a/sources/shiboken2/tests/minimalbinding/typesystem_minimal.xml
+++ /dev/null
@@ -1,93 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<typesystem package="minimal">
- <primitive-type name="bool"/>
- <primitive-type name="int"/>
-
- <primitive-type name="MinBool" target-lang-api-name="PyBool" default-constructor="MinBool(false)">
- <include file-name="minbool.h" location="global"/>
- <conversion-rule>
- <native-to-target>
- return PyBool_FromLong(%in.value());
- </native-to-target>
- <target-to-native>
- <add-conversion type="PyBool" check="PyBool_Check(%in)">
- %out = %OUTTYPE(%in == Py_True);
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <container-type name="std::list" type="list">
- <include file-name="list" location="global"/>
- <conversion-rule>
- <native-to-target>
- PyObject* %out = PyList_New((int) %in.size());
- %INTYPE::const_iterator it = %in.begin();
- for (int idx = 0; it != %in.end(); ++it, ++idx) {
- %INTYPE_0 cppItem(*it);
- PyList_SET_ITEM(%out, idx, %CONVERTTOPYTHON[%INTYPE_0](cppItem));
- }
- return %out;
- </native-to-target>
- <target-to-native>
- <add-conversion type="PySequence">
- Shiboken::AutoDecRef seq(PySequence_Fast(%in, 0));
- for (int i = 0; i &lt; PySequence_Fast_GET_SIZE(seq.object()); i++) {
- PyObject* pyItem = PySequence_Fast_GET_ITEM(seq.object(), i);
- %OUTTYPE_0 cppItem = %CONVERTTOCPP[%OUTTYPE_0](pyItem);
- %out.push_back(cppItem);
- }
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </container-type>
-
- <object-type name="Obj"/>
- <value-type name="Val">
- <enum-type name="ValEnum"/>
- </value-type>
- <value-type name="ListUser"/>
- <value-type name="MinBoolUser"/>
-
- <container-type name="std::vector" type="vector">
- <include file-name="vector" location="global"/>
- <conversion-rule>
- <native-to-target>
- %INTYPE::size_type vectorSize = %in.size();
- PyObject* %out = PyList_New((int) vectorSize);
- for (%INTYPE::size_type idx = 0; idx &lt; vectorSize; ++idx) {
- %INTYPE_0 cppItem(%in[idx]);
- PyList_SET_ITEM(%out, idx, %CONVERTTOPYTHON[%INTYPE_0](cppItem));
- }
- return %out;
- </native-to-target>
- <target-to-native>
- <add-conversion type="PySequence">
- Shiboken::AutoDecRef seq(PySequence_Fast(%in, 0));
- int vectorSize = PySequence_Fast_GET_SIZE(seq.object());
- %out.reserve(vectorSize);
- for (int idx = 0; idx &lt; vectorSize; ++idx ) {
- PyObject* pyItem = PySequence_Fast_GET_ITEM(seq.object(), idx);
- %OUTTYPE_0 cppItem = %CONVERTTOCPP[%OUTTYPE_0](pyItem);
- %out.push_back(cppItem);
- }
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </container-type>
- <!-- Test wrapping of a typedef -->
- <function signature="arrayFuncInt(std::vector&lt;int&gt;)" />
- <!-- Note manual expansion of the typedef -->
- <function signature="arrayFuncIntTypedef(std::vector&lt;int&gt;)" />
-
- <function signature="arrayFuncIntReturn(int)" />
- <function signature="arrayFuncIntReturnTypedef(int)" />
-
- <!-- Test wrapping of a typedef of a typedef -->
- <function signature="arrayFunc(std::vector&lt;int&gt;)" />
- <!-- Note manual expansion of the typedef -->
- <function signature="arrayFuncTypedef(std::vector&lt;int&gt;)" />
-
- <function signature="arrayFuncReturn(int)" />
- <function signature="arrayFuncReturnTypedef(int)" />
-</typesystem>
diff --git a/sources/shiboken2/tests/minimalbinding/val_test.py b/sources/shiboken2/tests/minimalbinding/val_test.py
deleted file mode 100644
index f97e9487d..000000000
--- a/sources/shiboken2/tests/minimalbinding/val_test.py
+++ /dev/null
@@ -1,121 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from minimal import Val
-
-
-class ExtVal(Val):
- def __init__(self, valId):
- Val.__init__(self, valId)
-
- def passValueType(self, val):
- return ExtVal(val.valId() + 1)
-
- def passValueTypePointer(self, val):
- val.setValId(val.valId() + 1)
- return val
-
- def passValueTypeReference(self, val):
- val.setValId(val.valId() + 1)
- return val
-
-
-class ValTest(unittest.TestCase):
-
- def testNormalMethod(self):
- valId = 123
- val = Val(valId)
- self.assertEqual(val.valId(), valId)
-
- def testPassValueType(self):
- val = Val(123)
- val1 = val.passValueType(val)
- self.assertNotEqual(val, val1)
- self.assertEqual(val1.valId(), 123)
- val2 = val.callPassValueType(val)
- self.assertNotEqual(val, val2)
- self.assertEqual(val2.valId(), 123)
-
- def testPassValueTypePointer(self):
- val = Val(0)
- self.assertEqual(val, val.passValueTypePointer(val))
- self.assertEqual(val, val.callPassValueTypePointer(val))
-
- def testPassValueTypeReference(self):
- val = Val(0)
- self.assertEqual(val, val.passValueTypeReference(val))
- self.assertEqual(val, val.callPassValueTypeReference(val))
-
- def testPassAndReceiveEnumValue(self):
- val = Val(0)
- self.assertEqual(val.oneOrTheOtherEnumValue(Val.One), Val.Other)
- self.assertEqual(val.oneOrTheOtherEnumValue(Val.Other), Val.One)
-
- def testPassValueTypeFromExtendedClass(self):
- val = ExtVal(0)
- val1 = val.passValueType(val)
- self.assertNotEqual(val, val1)
- self.assertEqual(val1.valId(), val.valId() + 1)
- val2 = val.callPassValueType(val)
- self.assertNotEqual(val, val2)
- self.assertEqual(val2.valId(), val.valId() + 1)
-
- def testPassValueTypePointerFromExtendedClass(self):
- val = ExtVal(0)
- self.assertEqual(val.valId(), 0)
- sameVal = val.passValueTypePointer(val)
- self.assertEqual(val, sameVal)
- self.assertEqual(sameVal.valId(), 1)
- sameVal = val.callPassValueTypePointer(val)
- self.assertEqual(val, sameVal)
- self.assertEqual(sameVal.valId(), 2)
-
- def testPassValueTypeReferenceFromExtendedClass(self):
- val = ExtVal(0)
- self.assertEqual(val.valId(), 0)
- sameVal = val.passValueTypeReference(val)
- self.assertEqual(val, sameVal)
- self.assertEqual(sameVal.valId(), 1)
- sameVal = val.callPassValueTypeReference(val)
- self.assertEqual(val, sameVal)
- self.assertEqual(sameVal.valId(), 2)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/otherbinding/CMakeLists.txt b/sources/shiboken2/tests/otherbinding/CMakeLists.txt
deleted file mode 100644
index 05a282838..000000000
--- a/sources/shiboken2/tests/otherbinding/CMakeLists.txt
+++ /dev/null
@@ -1,46 +0,0 @@
-project(other)
-
-set(other_TYPESYSTEM
-${CMAKE_CURRENT_SOURCE_DIR}/typesystem_other.xml
-)
-
-set(other_SRC
-${CMAKE_CURRENT_BINARY_DIR}/other/extendsnoimplicitconversion_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/other/number_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/other/otherderived_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/other/othermultiplederived_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/other/otherobjecttype_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/other/sharedptr_str_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/other/smartptrtester_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/other/other_module_wrapper.cpp
-)
-
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/other-binding.txt.in"
- "${CMAKE_CURRENT_BINARY_DIR}/other-binding.txt" @ONLY)
-
-add_custom_command(
-OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/mjb_rejected_classes.log"
-BYPRODUCTS ${other_SRC}
-COMMAND shiboken2 --project-file=${CMAKE_CURRENT_BINARY_DIR}/other-binding.txt ${GENERATOR_EXTRA_FLAGS}
-DEPENDS ${other_TYPESYSTEM} ${CMAKE_CURRENT_SOURCE_DIR}/global.h shiboken2
-WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
-COMMENT "Running generator for 'other' test binding..."
-)
-
-add_library(other MODULE ${other_SRC})
-target_include_directories(other PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}
- ${sample_BINARY_DIR}/sample
- ${smart_BINARY_DIR}/smart)
-target_link_libraries(other PUBLIC libother libsample libsmart libshiboken)
-set_property(TARGET other PROPERTY PREFIX "")
-set_property(TARGET other PROPERTY OUTPUT_NAME "other${PYTHON_EXTENSION_SUFFIX}")
-
-if(WIN32)
- set_property(TARGET other PROPERTY SUFFIX ".pyd")
-endif()
-
-
-add_dependencies(other sample smart)
-create_generator_target(other)
-
diff --git a/sources/shiboken2/tests/otherbinding/collector_external_operator_test.py b/sources/shiboken2/tests/otherbinding/collector_external_operator_test.py
deleted file mode 100644
index 6014b8a59..000000000
--- a/sources/shiboken2/tests/otherbinding/collector_external_operator_test.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for Collector shift operators defined in other modules.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Collector, ObjectType
-from other import OtherObjectType
-
-class CollectorOtherObjectType(unittest.TestCase):
- '''Test cases for Collector << OtherObjectType'''
-
- def testLShiftWithExpectedType(self):
- '''Collector << ObjectType # libsample << operator'''
- collector = Collector()
- obj = ObjectType()
- collector << obj
- self.assertEqual(collector.items()[0], obj.identifier())
-
- def testOtherReversal(self):
- '''Collector << OtherObjectType # libother << operator'''
- collector = Collector()
- obj = OtherObjectType()
- collector << obj
- self.assertEqual(collector.items()[0], obj.identifier() * 2)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/otherbinding/conversion_operator_for_class_without_implicit_conversions_test.py b/sources/shiboken2/tests/otherbinding/conversion_operator_for_class_without_implicit_conversions_test.py
deleted file mode 100644
index 1e992ebc8..000000000
--- a/sources/shiboken2/tests/otherbinding/conversion_operator_for_class_without_implicit_conversions_test.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests calling NoImplicitConversion using a ExtendsNoImplicitConversion parameter,
- being that the latter defines a new conversion operator for the former, and this one
- has no implicit conversions.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import NoImplicitConversion
-from other import ExtendsNoImplicitConversion
-
-class ConversionOperatorForClassWithoutImplicitConversionsTest(unittest.TestCase):
- '''Tests calling NoImplicitConversion constructor using a ExtendsNoImplicitConversion parameter.'''
-
- def testNoImplicitConversion(self):
- '''Basic test to see if the NoImplicitConversion is Ok.'''
- obj = NoImplicitConversion(123)
- # NoImplicitConversion.receivesNoImplicitConversionByValue(NoImplicitConversion)
- self.assertEqual(obj.objId(), NoImplicitConversion.receivesNoImplicitConversionByValue(obj))
- # NoImplicitConversion.receivesNoImplicitConversionByPointer(NoImplicitConversion*)
- self.assertEqual(obj.objId(), NoImplicitConversion.receivesNoImplicitConversionByPointer(obj))
- # NoImplicitConversion.receivesNoImplicitConversionByReference(NoImplicitConversion&)
- self.assertEqual(obj.objId(), NoImplicitConversion.receivesNoImplicitConversionByReference(obj))
-
- def testPassingExtendsNoImplicitConversionAsNoImplicitConversionByValue(self):
- '''Gives an ExtendsNoImplicitConversion object to a function expecting a NoImplicitConversion, passing by value.'''
- obj = ExtendsNoImplicitConversion(123)
- self.assertEqual(obj.objId(), NoImplicitConversion.receivesNoImplicitConversionByValue(obj))
-
- def testPassingExtendsNoImplicitConversionAsNoImplicitConversionByReference(self):
- '''Gives an ExtendsNoImplicitConversion object to a function expecting a NoImplicitConversion, passing by reference.'''
- obj = ExtendsNoImplicitConversion(123)
- self.assertEqual(obj.objId(), NoImplicitConversion.receivesNoImplicitConversionByReference(obj))
-
- def testPassingExtendsNoImplicitConversionAsNoImplicitConversionByPointer(self):
- '''Gives an ExtendsNoImplicitConversion object to a function expecting a NoImplicitConversion, passing by pointer.
- This should not be accepted, since pointers should not be converted.'''
- obj = ExtendsNoImplicitConversion(123)
- self.assertRaises(TypeError, NoImplicitConversion.receivesNoImplicitConversionByPointer, obj)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/otherbinding/extended_multiply_operator_test.py b/sources/shiboken2/tests/otherbinding/extended_multiply_operator_test.py
deleted file mode 100644
index 5ad4763b7..000000000
--- a/sources/shiboken2/tests/otherbinding/extended_multiply_operator_test.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for libsample's Point multiply operator defined in libother module.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Point
-from other import Number
-
-class PointOperationsWithNumber(unittest.TestCase):
- '''Test cases for libsample's Point multiply operator defined in libother module.'''
-
- def testPointTimesInt(self):
- '''sample.Point * int'''
- pt1 = Point(2, 7)
- num = 3
- pt2 = Point(pt1.x() * num, pt1.y() * num)
- self.assertEqual(pt1 * num, pt2)
-
- def testIntTimesPoint(self):
- '''int * sample.Point'''
- pt1 = Point(2, 7)
- num = 3
- pt2 = Point(pt1.x() * num, pt1.y() * num)
- self.assertEqual(num * pt1, pt2)
-
- def testPointTimesNumber(self):
- '''sample.Point * other.Number'''
- pt = Point(2, 7)
- num = Number(11)
- self.assertEqual(pt * num.value(), pt * 11)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/otherbinding/global.h b/sources/shiboken2/tests/otherbinding/global.h
deleted file mode 100644
index 763566ae0..000000000
--- a/sources/shiboken2/tests/otherbinding/global.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "../samplebinding/global.h"
-#include "extendsnoimplicitconversion.h"
-#include "number.h"
-#include "otherderived.h"
-#include "otherobjecttype.h"
-#include "othermultiplederived.h"
-#include "smartptrtester.h"
-
diff --git a/sources/shiboken2/tests/otherbinding/module_reload_test.py b/sources/shiboken2/tests/otherbinding/module_reload_test.py
deleted file mode 100644
index 368425cd0..000000000
--- a/sources/shiboken2/tests/otherbinding/module_reload_test.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import shutil
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from py3kcompat import IS_PY3K
-
-if IS_PY3K:
- from imp import reload
-
-orig_path = os.path.join(os.path.dirname(__file__))
-workdir = os.getcwd()
-src = os.path.join(orig_path, 'test_module_template.py')
-dst = os.path.join(workdir, 'test_module.py')
-shutil.copyfile(src, dst)
-sys.path.append(workdir)
-
-class TestModuleReloading(unittest.TestCase):
-
- def testModuleReloading(self):
- '''Test module reloading with on-the-fly modifications.'''
- import test_module
- for i in range(3):
- oldObject = test_module.obj
- self.assertTrue(oldObject is test_module.obj)
- reload(test_module)
- self.assertFalse(oldObject is test_module.obj)
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/sources/shiboken2/tests/otherbinding/new_ctor_operator_test.py b/sources/shiboken2/tests/otherbinding/new_ctor_operator_test.py
deleted file mode 100644
index 84dfe9839..000000000
--- a/sources/shiboken2/tests/otherbinding/new_ctor_operator_test.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests calling Str constructor using a Number parameter, being that number defines a cast operator to Str.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Str
-from other import Number
-
-class NewCtorOperatorTest(unittest.TestCase):
- '''Tests calling Str constructor using a Number parameter, being that number defines a cast operator to Str.'''
-
- def testNumber(self):
- '''Basic test to see if the Number class is Ok.'''
- value = 123
- num = Number(value)
- self.assertEqual(num.value(), value)
-
- def testStrCtorWithNumberArgument(self):
- '''Try to build a Str from 'sample' module with a Number argument from 'other' module.'''
- value = 123
- num = Number(value)
- string = Str(num)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/otherbinding/objtypehashes_test.py b/sources/shiboken2/tests/otherbinding/objtypehashes_test.py
deleted file mode 100644
index 92f93a090..000000000
--- a/sources/shiboken2/tests/otherbinding/objtypehashes_test.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import *
-from other import *
-import shiboken2 as shiboken
-
-class TestHashFuncs (unittest.TestCase):
-
- def testIt(self):
- obj1 = HandleHolder()
- obj2 = HandleHolder()
-
- hash1 = hash(obj1)
- hash2 = hash(obj2)
- self.assertNotEqual(hash1, hash2)
-
- # Now invalidate the object and test its hash. It shouldn't segfault.
- shiboken.invalidate(obj1)
-
- hash1_2 = hash(obj1)
- self.assertEqual(hash1_2, hash1)
-
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/otherbinding/other-binding.txt.in b/sources/shiboken2/tests/otherbinding/other-binding.txt.in
deleted file mode 100644
index dbe935a9f..000000000
--- a/sources/shiboken2/tests/otherbinding/other-binding.txt.in
+++ /dev/null
@@ -1,20 +0,0 @@
-[generator-project]
-
-generator-set = shiboken
-
-header-file = @CMAKE_CURRENT_SOURCE_DIR@/global.h
-typesystem-file = @other_TYPESYSTEM@
-
-output-directory = @CMAKE_CURRENT_BINARY_DIR@
-
-include-path = @libother_SOURCE_DIR@
-include-path = @libsmart_SOURCE_DIR@
-include-path = @libsample_SOURCE_DIR@
-include-path = @libsample_SOURCE_DIR@/..
-
-typesystem-path = @CMAKE_CURRENT_SOURCE_DIR@
-typesystem-path = @sample_SOURCE_DIR@
-typesystem-path = @smart_SOURCE_DIR@
-
-enable-parent-ctor-heuristic
-
diff --git a/sources/shiboken2/tests/otherbinding/otherderived_test.py b/sources/shiboken2/tests/otherbinding/otherderived_test.py
deleted file mode 100644
index d8dc9b686..000000000
--- a/sources/shiboken2/tests/otherbinding/otherderived_test.py
+++ /dev/null
@@ -1,125 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for OtherDerived class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Abstract, Derived
-from other import OtherDerived, Number
-
-class Multiple(Derived, Number):
- def __init__(self):
- Derived.__init__(self, 42)
- Number.__init__(self, 42)
-
- def testCall(self):
- return True
-
-class OtherDeviant(OtherDerived):
- def __init__(self):
- OtherDerived.__init__(self)
- self.pure_virtual_called = False
- self.unpure_virtual_called = False
-
- def pureVirtual(self):
- self.pure_virtual_called = True
-
- def unpureVirtual(self):
- self.unpure_virtual_called = True
-
- def className(self):
- return 'OtherDeviant'
-
-class MultipleTest(unittest.TestCase):
- '''Test case for Multiple derived class'''
-
- def testConstructor(self):
- o = Multiple()
- self.assertTrue(isinstance(o, Multiple))
- self.assertTrue(isinstance(o, Number))
- self.assertTrue(isinstance(o, Derived))
- del o
-
- def testMethodCall(self):
- o = Multiple()
- self.assertTrue(o.id_(), 42)
- self.assertTrue(o.value(), 42)
- self.assertTrue(o.testCall())
-
-class OtherDerivedTest(unittest.TestCase):
- '''Test case for OtherDerived class'''
-
- def testParentClassMethodsAvailability(self):
- '''Test if OtherDerived class really inherits its methods from parent.'''
- inherited_methods = set(['callPureVirtual', 'callUnpureVirtual',
- 'id_', 'pureVirtual', 'unpureVirtual'])
- self.assertTrue(inherited_methods.issubset(dir(OtherDerived)))
-
- def testReimplementedPureVirtualMethodCall(self):
- '''Test if a Python override of a implemented pure virtual method is correctly called from C++.'''
- d = OtherDeviant()
- d.callPureVirtual()
- self.assertTrue(d.pure_virtual_called)
-
- def testReimplementedVirtualMethodCall(self):
- '''Test if a Python override of a reimplemented virtual method is correctly called from C++.'''
- d = OtherDeviant()
- d.callUnpureVirtual()
- self.assertTrue(d.unpure_virtual_called)
-
- def testVirtualMethodCallString(self):
- '''Test virtual method call returning string.'''
- d = OtherDerived()
- self.assertEqual(d.className(), 'OtherDerived')
- self.assertEqual(d.getClassName(), 'OtherDerived')
-
- def testReimplementedVirtualMethodCallReturningString(self):
- '''Test if a Python override of a reimplemented virtual method is correctly called from C++.'''
- d = OtherDeviant()
- self.assertEqual(d.className(), 'OtherDeviant')
- self.assertEqual(d.getClassName(), 'OtherDeviant')
-
- def testCallToMethodWithAbstractArgument(self):
- '''Call to method that expects an Abstract argument.'''
- objId = 123
- d = OtherDerived(objId)
- self.assertEqual(Abstract.getObjectId(d), objId)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/otherbinding/signature_test.py b/sources/shiboken2/tests/otherbinding/signature_test.py
deleted file mode 100644
index f3b712d04..000000000
--- a/sources/shiboken2/tests/otherbinding/signature_test.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for functions signature'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from other import OtherObjectType
-from shiboken_test_helper import objectFullname
-
-class SignatureTest(unittest.TestCase):
-
- # Check if the argument of 'OtherObjectType::enumAsInt(SampleNamespace::SomeClass::PublicScopedEnum value)'
- # has the correct representation
- def testNamespaceFromOtherModule(self):
- argType = OtherObjectType.enumAsInt.__signature__.parameters['value'].annotation
- self.assertEqual(objectFullname(argType), 'sample.SampleNamespace.SomeClass.PublicScopedEnum')
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/otherbinding/smartptr_test.py b/sources/shiboken2/tests/otherbinding/smartptr_test.py
deleted file mode 100644
index 04f657757..000000000
--- a/sources/shiboken2/tests/otherbinding/smartptr_test.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2020 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for the SmartPtrTester class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from smart import Integer
-from sample import Str
-from other import SmartPtrTester
-
-
-class SmartPtrTest(unittest.TestCase):
- '''Test case for the SmartPtrTester class'''
-
- def test(self):
- tester = SmartPtrTester()
-
- integerPtr = tester.createSharedPtrInteger(42)
- self.assertEqual(tester.valueOfSharedPtrInteger(integerPtr), 42)
-
- strPtr = tester.createSharedPtrStr('hello')
- self.assertEqual(tester.valueOfSharedPtrStr(strPtr), 'hello')
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/otherbinding/test_module_template.py b/sources/shiboken2/tests/otherbinding/test_module_template.py
deleted file mode 100644
index 5d08944f3..000000000
--- a/sources/shiboken2/tests/otherbinding/test_module_template.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from other import *
-from sample import *
-
-
-class MyObjectType(ObjectType):
- pass
-
-class MyOtherObjectType(OtherObjectType):
- value = 10
-
-
-obj = MyObjectType()
diff --git a/sources/shiboken2/tests/otherbinding/typediscovery_test.py b/sources/shiboken2/tests/otherbinding/typediscovery_test.py
deleted file mode 100644
index 200d091b0..000000000
--- a/sources/shiboken2/tests/otherbinding/typediscovery_test.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for type discovery'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Abstract, Base1, Derived, MDerived1, MDerived3, SonOfMDerived1
-from other import OtherMultipleDerived
-
-class TypeDiscoveryTest(unittest.TestCase):
-
- def testPureVirtualsOfImpossibleTypeDiscovery(self):
- a = Derived.triggerImpossibleTypeDiscovery()
- self.assertEqual(type(a), Abstract)
- # call some pure virtual method
- a.pureVirtual()
-
- def testAnotherImpossibleTypeDiscovery(self):
- a = Derived.triggerAnotherImpossibleTypeDiscovery()
- self.assertEqual(type(a), Derived)
-
- def testMultipleInheritance(self):
- obj = OtherMultipleDerived.createObject("Base1");
- self.assertEqual(type(obj), Base1)
- # PYSIDE-868: In case of multiple inheritance, a factory
- # function will return the base class wrapper.
- obj = OtherMultipleDerived.createObject("MDerived1");
- self.assertEqual(type(obj), Base1)
- obj = OtherMultipleDerived.createObject("SonOfMDerived1");
- self.assertEqual(type(obj), Base1)
- obj = OtherMultipleDerived.createObject("MDerived3");
- self.assertEqual(type(obj), Base1)
- obj = OtherMultipleDerived.createObject("OtherMultipleDerived");
- self.assertEqual(type(obj), Base1)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/otherbinding/typesystem_other.xml b/sources/shiboken2/tests/otherbinding/typesystem_other.xml
deleted file mode 100644
index 78c4dd016..000000000
--- a/sources/shiboken2/tests/otherbinding/typesystem_other.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<typesystem package="other">
- <load-typesystem name="typesystem_sample.xml" generate="no" />
- <load-typesystem name="typesystem_smart.xml" generate="no" />
-
- <object-type name="OtherObjectType" />
- <object-type name="OtherDerived" />
- <object-type name="OtherMultipleDerived" />
-
- <value-type name="ExtendsNoImplicitConversion" />
- <value-type name="Number" />
-
- <smart-pointer-type name="SharedPtr" type="shared" getter="data" ref-count-method="useCount"
- instantiations="Str"/>
- <value-type name="SmartPtrTester"/>
-
- <suppress-warning text="signature 'operator!=(ByteArray,const char*)' for function modification in 'ByteArray' not found." />
- <suppress-warning text="signature 'operator+(ByteArray,const char*)' for function modification in 'ByteArray' not found." />
- <suppress-warning text="signature 'operator==(ByteArray,const char*)' for function modification in 'ByteArray' not found." />
-</typesystem>
diff --git a/sources/shiboken2/tests/otherbinding/usersprimitivefromothermodule_test.py b/sources/shiboken2/tests/otherbinding/usersprimitivefromothermodule_test.py
deleted file mode 100644
index a69ee23f0..000000000
--- a/sources/shiboken2/tests/otherbinding/usersprimitivefromothermodule_test.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests user defined primitive type from a required module.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from other import Number
-
-class UserDefinedPrimitiveTypeFromRequiredModuleTest(unittest.TestCase):
-
- def testUsersPrimitiveFromRequiredModuleAsArgument(self):
- '''static Number Number::fromComplex(Complex)'''
- cpx = complex(3.0, 1.2)
- number = Number.fromComplex(cpx)
- self.assertEqual(number.value(), int(cpx.real))
-
- def testUsersPrimitiveFromRequiredModuleAsReturnValue(self):
- '''Complex Number::toComplex()'''
- number = Number(12)
- cpx = number.toComplex()
- self.assertEqual(number.value(), int(cpx.real))
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/otherbinding/wrongctor_test.py b/sources/shiboken2/tests/otherbinding/wrongctor_test.py
deleted file mode 100644
index 29d085315..000000000
--- a/sources/shiboken2/tests/otherbinding/wrongctor_test.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import *
-from other import *
-
-class Foo(OtherDerived):
- def __init__(self):
- Abstract.__init__(self, 2) # this should raise an exception
-
-class Foo2(ObjectType, OtherDerived):
- def __init__(self):
- ObjectType.__init__(self)
- Abstract.__init__(self, 2) # this should raise an exception
-
-
-class WrongCtorTest(unittest.TestCase):
- def testIt(self):
- self.assertRaises(TypeError, Foo)
- self.assertRaises(TypeError, Foo2)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/py3k.py b/sources/shiboken2/tests/py3k.py
deleted file mode 100644
index 5f2961a6a..000000000
--- a/sources/shiboken2/tests/py3k.py
+++ /dev/null
@@ -1,2 +0,0 @@
-def printToFile(f, str):
- print(str, file=f)
diff --git a/sources/shiboken2/tests/py3kcompat.py b/sources/shiboken2/tests/py3kcompat.py
deleted file mode 100644
index 357ea4fba..000000000
--- a/sources/shiboken2/tests/py3kcompat.py
+++ /dev/null
@@ -1,82 +0,0 @@
-# -*- coding: utf-8 -*-
-
-#############################################################################
-##
-## Copyright (C) 2020 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-# Copy of ../../pyside2/tests/util/py3kcompat.py
-
-import sys
-
-IS_PY3K = sys.version_info[0] == 3
-
-if IS_PY3K:
- def b(s):
- if type(s) == bytes:
- return s
- return bytes(s, "UTF8")
-
- def buffer_(s):
- if s == None:
- return None
- elif type(s) == str:
- return bytes(s, "UTF8")
- elif type(s) == bytes:
- return s
- else:
- memoryview(s)
-
- def l(n):
- return n
-
- def unicode_(s):
- return s
-
- unicode = str
- unichr = chr
- long = int
- unichr = chr
- buffer = buffer_
-else:
- def b(s):
- return s
-
- def l(n):
- return long(n)
-
- def unicode_(s):
- if type(s) == str:
- import codecs
- c = codecs.lookup('utf-8')
- s2 = c.decode(s, 'ignore')
- return s2[0]
- return u'%s' % s
-
- unicode = unicode
- unichr = unichr
- long = long
- buffer = buffer
diff --git a/sources/shiboken2/tests/samplebinding/CMakeLists.txt b/sources/shiboken2/tests/samplebinding/CMakeLists.txt
deleted file mode 100644
index b65068dc3..000000000
--- a/sources/shiboken2/tests/samplebinding/CMakeLists.txt
+++ /dev/null
@@ -1,153 +0,0 @@
-project(sample)
-
-set(sample_TYPESYSTEM
-${CMAKE_CURRENT_SOURCE_DIR}/typesystem_sample.xml
-)
-
-set(sample_SRC
-${CMAKE_CURRENT_BINARY_DIR}/sample/abstractmodifications_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/abstract_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/arraymodifytest_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/base1_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/base2_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/base3_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/base4_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/base5_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/base6_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/blackbox_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/bytearray_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/bucket_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/classwithfunctionpointer_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/collector_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/color_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/ctorconvrule_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/cvlistuser_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/cvvaluetype_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/sbkdate_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/derived_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/derived_someinnerclass_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/echo_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/event_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/expression_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/exceptiontest_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/friendofonlycopy_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/handleholder_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/implicitconv_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/implicitbase_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/implicittarget_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/intarray2_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/intarray3_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/intlist_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/sortedoverload_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/intwrapper_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/injectcode_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/listuser_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/mapuser_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/mderived1_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/mderived2_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/mderived3_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/mderived4_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/mderived5_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/modelindex_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/modifications_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/modifiedconstructor_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/noimplicitconversion_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/nondefaultctor_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objectmodel_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objecttype_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objecttypebyvalue_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objecttypeholder_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objecttypederived_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objecttypelayout_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objecttypeptrlist_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objecttypeoperators_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objectview_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/objtypereference_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/oddbooluser_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/onlycopy_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/otherbase_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/overload_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/overload2_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/pairuser_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/pen_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/persistentmodelindex_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/photon_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/photon_base_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/photon_valueidentity_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/photon_valueduplicator_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/point_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/pointerholder_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/pointf_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/pointvaluelist_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/polygon_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/primitivestructpointerholder_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/privatector_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/privatedtor_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/protectedenumclass_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/protectednonpolymorphic_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/protectedpolymorphic_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/protectedpolymorphicdaughter_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/protectedpolymorphicgranddaughter_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/protectedproperty_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/protectedvirtualdestructor_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/rect_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/rectf_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/reference_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/referentmodelindex_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/toberenamedvalue_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/renameduser_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/sample_module_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/sample_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/sample_sample_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/samplenamespace_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/samplenamespace_someclass_someinnerclass_okthisisrecursiveenough_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/samplenamespace_someclass_someinnerclass_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/samplenamespace_someclass_someotherinnerclass_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/samplenamespace_someclass_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/samplenamespace_derivedfromnamespace_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/simplefile_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/size_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/sizef_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/sonofmderived1_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/str_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/strlist_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/time_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/templateptr_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/unremovednamespace_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/virtualdaughter_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/virtualdaughter2_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/virtualfinaldaughter_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/virtualdtor_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/virtualmethods_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/voidholder_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/valueandvirtual_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/filter_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/data_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/intersection_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/union_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/sample/invisible_objectoninvisiblenamespace_wrapper.cpp
-)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/sample-binding.txt.in"
- "${CMAKE_CURRENT_BINARY_DIR}/sample-binding.txt" @ONLY)
-
-add_custom_command(
-OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/mjb_rejected_classes.log"
-BYPRODUCTS ${sample_SRC}
-COMMAND shiboken2 --project-file=${CMAKE_CURRENT_BINARY_DIR}/sample-binding.txt ${GENERATOR_EXTRA_FLAGS}
-DEPENDS ${sample_TYPESYSTEM} ${CMAKE_CURRENT_SOURCE_DIR}/global.h shiboken2
-WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
-COMMENT "Running generator for 'sample' test binding..."
-)
-
-add_library(sample MODULE ${sample_SRC})
-target_include_directories(sample PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
-target_link_libraries(sample PUBLIC libsample libshiboken)
-set_property(TARGET sample PROPERTY PREFIX "")
-set_property(TARGET sample PROPERTY OUTPUT_NAME "sample${PYTHON_EXTENSION_SUFFIX}")
-
-if(WIN32)
- set_property(TARGET sample PROPERTY SUFFIX ".pyd")
-endif()
-
-create_generator_target(sample)
diff --git a/sources/shiboken2/tests/samplebinding/__del___test.py b/sources/shiboken2/tests/samplebinding/__del___test.py
deleted file mode 100644
index eba837eb8..000000000
--- a/sources/shiboken2/tests/samplebinding/__del___test.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import sample
-
-delCalled = False
-
-class MyObject(sample.ObjectType):
- def __del__(self):
- global delCalled
- delCalled = True
-
-class TestDel(unittest.TestCase):
- def testIt(self):
- a = MyObject()
- del a
- self.assertTrue(delCalled)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/abstract_test.py b/sources/shiboken2/tests/samplebinding/abstract_test.py
deleted file mode 100644
index 23a984870..000000000
--- a/sources/shiboken2/tests/samplebinding/abstract_test.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for Abstract class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Abstract
-
-class Incomplete(Abstract):
- def __init__(self):
- Abstract.__init__(self)
-
-class Concrete(Abstract):
- def __init__(self):
- Abstract.__init__(self)
- self.pure_virtual_called = False
- self.unpure_virtual_called = False
-
- def pureVirtual(self):
- self.pure_virtual_called = True
-
- def pureVirtualReturningVoidPtr(self):
- return 42
-
- def unpureVirtual(self):
- self.unpure_virtual_called = True
-
- def virtualGettingAEnum(self, enum):
- self.virtual_getting_enum = True
-
-
-class AbstractTest(unittest.TestCase):
- '''Test case for Abstract class'''
-
- def testAbstractPureVirtualMethodAvailability(self):
- '''Test if Abstract class pure virtual method was properly wrapped.'''
- self.assertTrue('pureVirtual' in dir(Abstract))
-
- def testAbstractInstanciation(self):
- '''Test if instanciation of an abstract class raises the correct exception.'''
- self.assertRaises(NotImplementedError, Abstract)
-
- def testUnimplementedPureVirtualMethodCall(self):
- '''Test if calling a pure virtual method raises the correct exception.'''
- i = Incomplete()
- self.assertRaises(NotImplementedError, i.pureVirtual)
-
- def testPureVirtualReturningVoidPtrReturnValue(self):
- '''Test if a pure virtual method returning void ptr can be properly reimplemented'''
- # Note that the semantics of reimplementing the pure virtual method in
- # Python and calling it from C++ is undefined until it's decided how to
- # cast the Python data types to void pointers
- c = Concrete()
- self.assertEqual(c.pureVirtualReturningVoidPtr(),42)
-
- def testReimplementedVirtualMethodCall(self):
- '''Test if instanciation of an abstract class raises the correct exception.'''
- i = Concrete()
- self.assertRaises(NotImplementedError, i.callPureVirtual)
-
- def testReimplementedVirtualMethodCall(self):
- '''Test if a Python override of a virtual method is correctly called from C++.'''
- c = Concrete()
- c.callUnpureVirtual()
- self.assertTrue(c.unpure_virtual_called)
-
- def testImplementedPureVirtualMethodCall(self):
- '''Test if a Python override of a pure virtual method is correctly called from C++.'''
- c = Concrete()
- c.callPureVirtual()
- self.assertTrue(c.pure_virtual_called)
-
- def testEnumParameterOnVirtualMethodCall(self):
- '''testEnumParameterOnVirtualMethodCall'''
- c = Concrete()
- c.callVirtualGettingEnum(Abstract.Short)
- self.assertTrue(c.virtual_getting_enum)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/addedfunction_test.py b/sources/shiboken2/tests/samplebinding/addedfunction_test.py
deleted file mode 100644
index d7f5f3994..000000000
--- a/sources/shiboken2/tests/samplebinding/addedfunction_test.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for added functions.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import SampleNamespace, ObjectType, Point
-
-class TestAddedFunctionsWithSimilarTypes(unittest.TestCase):
- '''Adds new signatures very similar to already existing ones.'''
-
- def testValueTypeReferenceAndValue(self):
- '''In C++ we have "function(const ValueType&, double)",
- in Python we add "function(ValueType)".'''
- point = Point(10, 20)
- multiplier = 4.0
- control = (point.x() + point.y()) * multiplier
- self.assertEqual(SampleNamespace.passReferenceToValueType(point, multiplier), control)
- control = point.x() + point.y()
- self.assertEqual(SampleNamespace.passReferenceToValueType(point), control)
-
- def testObjectTypeReferenceAndPointer(self):
- '''In C++ we have "function(const ObjectType&, int)",
- in Python we add "function(ValueType)".'''
- obj = ObjectType()
- obj.setObjectName('sbrubbles')
- multiplier = 3.0
- control = len(obj.objectName()) * multiplier
- self.assertEqual(SampleNamespace.passReferenceToObjectType(obj, multiplier), control)
- control = len(obj.objectName())
- self.assertEqual(SampleNamespace.passReferenceToObjectType(obj), control)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/addedfunction_with_container_args_test.py b/sources/shiboken2/tests/samplebinding/addedfunction_with_container_args_test.py
deleted file mode 100644
index 9666b251c..000000000
--- a/sources/shiboken2/tests/samplebinding/addedfunction_with_container_args_test.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for added functions with nested and multi-argument container types.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import sum2d, sumproduct
-
-class TestAddedFunctionsWithContainerArgs(unittest.TestCase):
- '''Tests added functions with nested and multi-argument container types.'''
-
- def testNestedContainerType(self):
- '''Test added function with single-argument containers.'''
- values = [[1,2],[3,4,5],[6]]
- self.assertEqual(sum2d(values), 21)
-
- def testMultiArgContainerType(self):
- '''Test added function with a two-argument container.'''
- values = [(1,2),(3,4),(5,6)]
- self.assertEqual(sumproduct(values), 44)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/argumentmodifications_test.py b/sources/shiboken2/tests/samplebinding/argumentmodifications_test.py
deleted file mode 100644
index 8a2775db3..000000000
--- a/sources/shiboken2/tests/samplebinding/argumentmodifications_test.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for method arguments modifications performed as described on typesystem.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Modifications, Point
-
-class ArgumentModificationsTest(unittest.TestCase):
- '''Test cases for method arguments modifications performed as described on typesystem.'''
-
- def setUp(self):
- self.mods = Modifications()
-
- def tearDown(self):
- del self.mods
-
- def testArgRemoval0(self):
- '''Tests argument removal modifications on Modifications.argRemoval0.'''
- # void [-> PyObject*] argRemoval0(int, bool, int = 123 [removed, new val = 321], int = 456)
- # code-injection: returns tuple with received parameters plus removed ones
- a0, a1, a2 = 1, True, 2
- self.assertEqual(self.mods.argRemoval0(a0, a1), (a0, a1, 321, 456))
- self.assertEqual(self.mods.argRemoval0(a0, a1, a2), (a0, a1, 321, a2))
- # the other wasn't modified
- # void argRemoval0(int, bool, int, bool)
- self.assertEqual(self.mods.argRemoval0(0, False, 0, False), None)
-
- def testArgRemoval1(self):
- '''Tests argument removal modifications on Modifications.argRemoval1.'''
- # void [-> PyObject*] argRemoval1(int, bool, Point = Point(1, 2) [removed], Point = Point(3, 4) [removed], int = 333)
- # code-injection: returns tuple with received parameters plus removed ones
- a0, a1, a2 = 1, True, 2
- self.assertEqual(self.mods.argRemoval1(a0, a1), (a0, a1, Point(1, 2), Point(3, 4), 333))
- self.assertEqual(self.mods.argRemoval1(a0, a1, a2), (a0, a1, Point(1, 2), Point(3, 4), a2))
- # the other wasn't modified
- # void argRemoval1(int, bool, int, bool)
- self.assertEqual(self.mods.argRemoval1(0, False, 0, False), None)
-
- def testArgRemoval2(self):
- '''Tests argument removal modifications on Modifications.argRemoval2.'''
- # void [-> PyObject*] argRemoval2(int, bool, Point = Point(1, 2) [removed], Point = Point(3, 4) [removed], int = 333)
- # code-injection: returns tuple with received parameters plus removed ones
- a0, a1, a2 = 1, True, 2
- self.assertEqual(self.mods.argRemoval2(a0, a1), (a0, a1, Point(1, 2), Point(3, 4), 333))
- self.assertEqual(self.mods.argRemoval2(a0, a1, a2), (a0, a1, Point(1, 2), Point(3, 4), a2))
-
- def testArgRemoval3(self):
- '''Tests argument removal modifications on Modifications.argRemoval3.'''
- # void [-> PyObject*] argRemoval3(int, Point = Point(1, 2) [removed], bool = true, Point = Point(3, 4) [removed], int = 333)
- # code-injection: returns tuple with received parameters plus removed ones
- a0, a1, a2 = 1, True, 2
- self.assertEqual(self.mods.argRemoval3(a0), (a0, Point(1, 2), True, Point(3, 4), 333))
- self.assertEqual(self.mods.argRemoval3(a0, a1), (a0, Point(1, 2), a1, Point(3, 4), 333))
- self.assertEqual(self.mods.argRemoval3(a0, a1, a2), (a0, Point(1, 2), a1, Point(3, 4), a2))
-
- def testArgRemoval4(self):
- '''Tests argument removal modifications on Modifications.argRemoval4.'''
- # void [-> PyObject*] argRemoval4(int, Point [removed, new val = Point(6, 9)], bool, Point = Point(3, 4) [removed], int = 333)
- # code-injection: returns tuple with received parameters plus removed ones
- a0, a1, a2 = 1, True, 2
- self.assertRaises(TypeError, self.mods.argRemoval4, a0)
- self.assertEqual(self.mods.argRemoval4(a0, a1), (a0, Point(6, 9), a1, Point(3, 4), 333))
- self.assertEqual(self.mods.argRemoval4(a0, a1, a2), (a0, Point(6, 9), a1, Point(3, 4), a2))
-
- def testArgRemoval5(self):
- '''Tests argument removal modifications on Modifications.argRemoval5.'''
- # void [-> PyObject*] argRemoval5(int [removed, new val = 100], bool,
- # Point = Point(1, 2) [removed],
- # Point = Point(3, 4) [removed], int = 333)
- # code-injection: returns tuple with received parameters plus removed ones
- a0, a1, a2 = True, 2, True
- self.assertEqual(self.mods.argRemoval5(a0), (100, a0, Point(1, 2), Point(3, 4), 333))
- self.assertEqual(self.mods.argRemoval5(a0, a1), (100, a0, Point(1, 2), Point(3, 4), a1))
- # void [-> PyObject*] argRemoval5(int [removed, new val = 200], bool, int, bool)
- # code-injection: returns tuple with received parameters plus removed ones
- self.assertEqual(self.mods.argRemoval5(a0, a1, a2), (200, a0, a1, a2))
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/array_numpy_test.py b/sources/shiboken2/tests/samplebinding/array_numpy_test.py
deleted file mode 100644
index 2c2a2852a..000000000
--- a/sources/shiboken2/tests/samplebinding/array_numpy_test.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python
-
-#############################################################################
-##
-## Copyright (C) 2017 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for NumPy Array types.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import sample
-
-hasNumPy = False
-
-try:
- import numpy
- hasNumPy = True
-except ImportError:
- pass
-
-class ArrayTester(unittest.TestCase):
- '''Test case for NumPy arrays.'''
-
- def testIntArray(self):
- intList = numpy.array([1, 2, 3, 4], dtype = 'int32')
- self.assertEqual(sample.sumIntArray(intList), 10)
-
- def testDoubleArray(self):
- doubleList = numpy.array([1, 2, 3, 4], dtype = 'double')
- self.assertEqual(sample.sumDoubleArray(doubleList), 10)
-
- def testIntMatrix(self):
- intMatrix = numpy.array([[1, 2, 3], [4, 5, 6]], dtype = 'int32')
- self.assertEqual(sample.sumIntMatrix(intMatrix), 21)
-
- def testDoubleMatrix(self):
- doubleMatrix = numpy.array([[1, 2, 3], [4, 5, 6]], dtype = 'double')
- self.assertEqual(sample.sumDoubleMatrix(doubleMatrix), 21)
-
-if __name__ == '__main__' and hasNumPy:
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/array_sequence_test.py b/sources/shiboken2/tests/samplebinding/array_sequence_test.py
deleted file mode 100644
index 520a5f928..000000000
--- a/sources/shiboken2/tests/samplebinding/array_sequence_test.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-
-#############################################################################
-##
-## Copyright (C) 2017 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for Array types (PySequence).'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import sample
-
-class ArrayTester(unittest.TestCase):
- '''Test case for arrays.'''
-
- def testIntArray(self):
- intList = [1, 2, 3, 4]
- self.assertEqual(sample.sumIntArray(intList), 10)
-
- def testIntArrayModified(self):
- intList = [1, 2, 3, 4]
- tester = sample.ArrayModifyTest()
- self.assertEqual(tester.sumIntArray(4, intList), 10)
-
- def testDoubleArray(self):
- doubleList = [1.2, 2.3, 3.4, 4.5]
- self.assertEqual(sample.sumDoubleArray(doubleList), 11.4)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/bug_554_test.py b/sources/shiboken2/tests/samplebinding/bug_554_test.py
deleted file mode 100644
index c1c06a17f..000000000
--- a/sources/shiboken2/tests/samplebinding/bug_554_test.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Unit test for bug#554'''
-
-import os
-import sys
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class Bug554:
- def crash(self):
- class Crasher(ObjectType):
- pass
-
-if __name__ == '__main__':
- bug = Bug554()
- bug.crash()
-
-
diff --git a/sources/shiboken2/tests/samplebinding/bug_704_test.py b/sources/shiboken2/tests/samplebinding/bug_704_test.py
deleted file mode 100644
index 28c90aba4..000000000
--- a/sources/shiboken2/tests/samplebinding/bug_704_test.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from py3kcompat import IS_PY3K
-
-from sample import ObjectType
-
-
-class NewStyle(object):
- def name(self):
- return "NewStyle"
-
-class OldStyle:
- def name(self):
- return "OldStyle"
-
-def defineNewStyle():
- class MyObjectNew(ObjectType, NewStyle):
- pass
-
-def defineOldStyle():
- class MyObjectOld(ObjectType, OldStyle):
- pass
-
-class ObjectTypeTest(unittest.TestCase):
- '''Test cases to avoid declaring Shiboken classes with multiple inheritance from old style classes.'''
-
- def testObjectTypeNewStype(self):
- defineNewStyle()
-
- def testObjectTypeOldStype(self):
- # Py 3k doesn't have old style classes
- if not IS_PY3K:
- self.assertRaises(TypeError, defineOldStyle)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/bytearray_bufferprotocol.cpp b/sources/shiboken2/tests/samplebinding/bytearray_bufferprotocol.cpp
deleted file mode 100644
index 322387088..000000000
--- a/sources/shiboken2/tests/samplebinding/bytearray_bufferprotocol.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#if PY_VERSION_HEX < 0x03000000
-// ByteArray buffer protocol functions
-// See: http://www.python.org/dev/peps/pep-3118/
-extern "C" {
-static Py_ssize_t SbkByteArray_segcountproc(PyObject* self, Py_ssize_t* lenp)
-{
- if (lenp)
- *lenp = Py_TYPE(self)->tp_as_sequence->sq_length(self);
- return 1;
-}
-static Py_ssize_t SbkByteArray_readbufferproc(PyObject* self, Py_ssize_t segment, void** ptrptr)
-{
- if (segment || !Shiboken::Object::isValid(self))
- return -1;
-
- ByteArray* cppSelf = %CONVERTTOCPP[ByteArray*](self);
- *ptrptr = reinterpret_cast<void*>(const_cast<char*>(cppSelf->data()));
- return cppSelf->size();
-}
-PyBufferProcs SbkByteArrayBufferProc = {
- /*bf_getreadbuffer*/ &SbkByteArray_readbufferproc,
- /*bf_getwritebuffer*/ (writebufferproc)&SbkByteArray_readbufferproc,
- /*bf_getsegcount*/ &SbkByteArray_segcountproc,
- /*bf_getcharbuffer*/ (charbufferproc)&SbkByteArray_readbufferproc
-};
-}
-#endif
diff --git a/sources/shiboken2/tests/samplebinding/bytearray_test.py b/sources/shiboken2/tests/samplebinding/bytearray_test.py
deleted file mode 100644
index f1094e54e..000000000
--- a/sources/shiboken2/tests/samplebinding/bytearray_test.py
+++ /dev/null
@@ -1,157 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from os.path import isdir
-from sample import ByteArray
-from py3kcompat import b
-
-
-class ByteArrayBufferProtocolTest(unittest.TestCase):
- '''Tests ByteArray implementation of Python buffer protocol.'''
-
- def testByteArrayBufferProtocol(self):
- # Tests ByteArray implementation of Python buffer protocol using the os.path.isdir
- # function which an unicode object or other object implementing the Python buffer protocol.
- isdir(str(ByteArray('/tmp')))
-
-
-class ByteArrayConcatenationOperatorTest(unittest.TestCase):
- '''Test cases for ByteArray concatenation with '+' operator.'''
-
- def testConcatByteArrayAndPythonString(self):
- # Test concatenation of a ByteArray with a Python string, in this order.
- ba = ByteArray('foo')
- result = ba + '\x00bar'
- self.assertEqual(type(result), ByteArray)
- self.assertEqual(result, 'foo\x00bar')
-
- def testConcatPythonStringAndByteArray(self):
- # Test concatenation of a Python string with a ByteArray, in this order.
- concat_python_string_add_qbytearray_worked = True
- ba = ByteArray('foo')
- result = 'bar\x00' + ba
- self.assertEqual(type(result), ByteArray)
- self.assertEqual(result, 'bar\x00foo')
-
-
-class ByteArrayOperatorEqual(unittest.TestCase):
- '''TestCase for operator ByteArray == ByteArray.'''
-
- def testDefault(self):
- # ByteArray() == ByteArray()
- obj1 = ByteArray()
- obj2 = ByteArray()
- self.assertEqual(obj1, obj2)
-
- def testSimple(self):
- # ByteArray(some_string) == ByteArray(some_string)
- string = 'egg snakes'
- self.assertEqual(ByteArray(string), ByteArray(string))
-
- def testPyString(self):
- # ByteArray(string) == string
- string = 'my test string'
- self.assertEqual(ByteArray(string), string)
-
- def testQString(self):
- # ByteArray(string) == string
- string = 'another test string'
- self.assertEqual(ByteArray(string), string)
-
-
-class ByteArrayOperatorAt(unittest.TestCase):
- '''TestCase for operator ByteArray[]'''
-
- def testInRange(self):
- # ByteArray[x] where x is a valid index.
- string = 'abcdefgh'
- obj = ByteArray(string)
- for i in range(len(string)):
- self.assertEqual(obj[i], b(string[i]))
-
- def testInRangeReverse(self):
- # ByteArray[x] where x is a valid index (reverse order).
- string = 'abcdefgh'
- obj = ByteArray(string)
- for i in range(len(string)-1, 0, -1):
- self.assertEqual(obj[i], b(string[i]))
-
- def testOutOfRange(self):
- # ByteArray[x] where x is out of index.
- string = '1234567'
- obj = ByteArray(string)
- self.assertRaises(IndexError, lambda :obj[len(string)])
-
- def testNullStrings(self):
- ba = ByteArray('\x00')
- self.assertEqual(ba.at(0), '\x00')
- self.assertEqual(ba[0], b('\x00'))
-
-
-class ByteArrayOperatorLen(unittest.TestCase):
- '''Test case for __len__ operator of ByteArray'''
-
- def testBasic(self):
- '''ByteArray __len__'''
- self.assertEqual(len(ByteArray()), 0)
- self.assertEqual(len(ByteArray('')), 0)
- self.assertEqual(len(ByteArray(' ')), 1)
- self.assertEqual(len(ByteArray('yabadaba')), 8)
-
-
-class ByteArrayAndPythonStr(unittest.TestCase):
- '''Test case for __str__ operator of ByteArray'''
-
- def testStrOperator(self):
- '''ByteArray __str__'''
- self.assertEqual(ByteArray().__str__(), '')
- self.assertEqual(ByteArray('').__str__(), '')
- self.assertEqual(ByteArray('aaa').__str__(), 'aaa')
-
- def testPythonStrAndNull(self):
- s1 = b('123\000321')
- ba = ByteArray(s1)
- s2 = ba.data()
- self.assertEqual(s1, s2)
- self.assertEqual(type(s1), type(s2))
- self.assertEqual(s1, ba)
- self.assertNotEqual(type(s1), type(ba))
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/child_return_test.py b/sources/shiboken2/tests/samplebinding/child_return_test.py
deleted file mode 100644
index 28fde4926..000000000
--- a/sources/shiboken2/tests/samplebinding/child_return_test.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''The BlackBox class has cases of ownership transference between C++ and Python.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class ReturnOfChildTest(unittest.TestCase):
- '''The BlackBox class has cases of ownership transference between C++ and Python.'''
-
- def testKillParentKeepingChild(self):
- '''Ownership transference from Python to C++ and back again.'''
- o1 = ObjectType.createWithChild()
- child = o1.children()[0]
- del o1
- self.assertRaises(RuntimeError, child.objectName)
-
- def testKillParentKeepingChild2(self):
- '''Ownership transference from Python to C++ and back again.'''
- o1 = ObjectType.createWithChild()
- child = o1.findChild("child")
- del o1
- self.assertRaises(RuntimeError, child.objectName)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/class_fields_test.py b/sources/shiboken2/tests/samplebinding/class_fields_test.py
deleted file mode 100644
index 202efcafb..000000000
--- a/sources/shiboken2/tests/samplebinding/class_fields_test.py
+++ /dev/null
@@ -1,174 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Simple test case for accessing the exposed C++ class fields.'''
-
-import os
-import sys
-from sys import getrefcount
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Derived, Point, ObjectType
-
-class TestAccessingCppFields(unittest.TestCase):
- '''Simple test case for accessing the exposed C++ class fields.'''
-
- def testAccessingPrimitiveTypeField(self):
- '''Reads and writes a primitive type (in this case an 'int') field.'''
- d = Derived()
- self.assertEqual(type(d.primitiveField), int)
-
- # attribution
- old_value = d.primitiveField
- new_value = 2255
- d.primitiveField = new_value
- self.assertEqual(d.primitiveField, new_value)
- self.assertNotEqual(d.primitiveField, old_value)
-
- # attribution with a convertible type
- value = 1.2
- d.primitiveField = value
- self.assertEqual(d.primitiveField, int(value))
-
- # attribution with invalid type
- self.assertRaises(TypeError, lambda : setattr(d, 'primitiveField', None))
-
- def testAccessingUsersPrimitiveTypeField(self):
- '''Reads and writes an user's primitive type (in this case an 'Complex') field.'''
- d = Derived()
- self.assertEqual(type(d.userPrimitiveField), complex)
-
- # attribution
- old_value = d.userPrimitiveField
- new_value = complex(1.1, 2.2)
- d.userPrimitiveField = new_value
- self.assertEqual(d.userPrimitiveField, new_value)
- self.assertNotEqual(d.userPrimitiveField, old_value)
-
- # attribution with invalid type
- self.assertRaises(TypeError, lambda : setattr(d, 'userPrimitiveField', None))
-
- def testAccessingValueTypeField(self):
- '''Reads and writes a value type (in this case a 'Point') field.'''
- d = Derived()
- self.assertEqual(type(d.valueTypeField), Point)
-
- # attribution
- old_value = d.valueTypeField
- new_value = Point(-10, 537)
- d.valueTypeField = new_value
- self.assertEqual(d.valueTypeField, new_value)
-
- #object modify
- d.valueTypeField.setX(10)
- d.valueTypeField.setY(20)
- self.assertEqual(d.valueTypeField.x(), 10)
- self.assertEqual(d.valueTypeField.y(), 20)
-
- # attribution with invalid type
- self.assertRaises(TypeError, lambda : setattr(d, 'valueTypeField', 123))
-
- def testAccessingObjectTypeField(self):
- '''Reads and writes a object type (in this case an 'ObjectType') field.'''
- d = Derived()
-
- # attribution
- old_value = d.objectTypeField
- new_value = ObjectType()
- d.objectTypeField = new_value
- self.assertEqual(d.objectTypeField, new_value)
- self.assertNotEqual(d.objectTypeField, old_value)
-
- # attribution with a convertible type
- value = None
- d.objectTypeField = value
- self.assertEqual(d.objectTypeField, value)
-
- # attribution with invalid type
- self.assertRaises(TypeError, lambda : setattr(d, 'objectTypeField', 123))
-
- def testRefCountingAccessingObjectTypeField(self):
- '''Accessing a object type field should respect the reference counting rules.'''
- d = Derived()
-
- # attributing object to instance's field should increase its reference count
- o1 = ObjectType()
- refcount1 = getrefcount(o1)
- d.objectTypeField = o1
- self.assertEqual(d.objectTypeField, o1)
- self.assertEqual(getrefcount(d.objectTypeField), refcount1 + 1)
-
- # attributing a new object to instance's field should decrease the previous object's reference count
- o2 = ObjectType()
- refcount2 = getrefcount(o2)
- d.objectTypeField = o2
- self.assertEqual(d.objectTypeField, o2)
- self.assertEqual(getrefcount(o1), refcount1)
- self.assertEqual(getrefcount(d.objectTypeField), refcount2 + 1)
-
- def testRefCountingOfReferredObjectAfterDeletingReferrer(self):
- '''Deleting the object referring to other object should decrease the reference count of the referee.'''
- d = Derived()
- o = ObjectType()
- refcount = getrefcount(o)
- d.objectTypeField = o
- self.assertEqual(getrefcount(o), refcount + 1)
- del d
- self.assertEqual(getrefcount(o), refcount)
-
- def testStaticField(self):
- self.assertEqual(Derived.staticPrimitiveField, 0)
-
- def testAccessingUnsignedIntBitField(self):
- d = Derived()
-
- # attribution
- old_value = d.bitField
- new_value = 1
- d.bitField= new_value
- self.assertEqual(d.bitField, new_value)
- self.assertNotEqual(d.bitField, old_value)
-
- # attribution with a convertible type
- value = 1.2
- d.bitField = value
- self.assertEqual(d.bitField, int(value))
-
- # attribution with invalid type
- self.assertRaises(TypeError, lambda : setattr(d, 'bitField', None))
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/collector_test.py b/sources/shiboken2/tests/samplebinding/collector_test.py
deleted file mode 100644
index d6d10165e..000000000
--- a/sources/shiboken2/tests/samplebinding/collector_test.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for Collector class' shift operators.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Collector, IntWrapper, ObjectType
-
-
-class CollectorTest(unittest.TestCase):
- '''Test cases for Collector class' shift operators.'''
-
- def testLShiftOperatorSingleUse(self):
- '''Test case for using the Collector.__lshift__ operator just one time.'''
- collector = Collector()
- collector << 13
- self.assertEqual(collector.size(), 1)
- self.assertEqual(collector.items(), [13])
-
- def testLShiftOperatorMultipleUses(self):
- '''Test case for using the Collector.__lshift__ operator many times in the same line.'''
- collector = Collector()
- collector << 2 << 3 << 5 << 7 << 11
- self.assertEqual(collector.size(), 5)
- self.assertEqual(collector.items(), [2, 3, 5, 7, 11])
-
-class CollectorExternalOperator(unittest.TestCase):
- '''Test cases for external operators of Collector'''
-
- def testLShiftExternal(self):
- '''Collector external operator'''
- collector = Collector()
- collector << IntWrapper(5)
- self.assertEqual(collector.size(), 1)
- self.assertEqual(collector.items(), [5])
-
-
-class CollectorObjectType(unittest.TestCase):
- '''Test cases for Collector ObjectType'''
-
- def testBasic(self):
- '''Collector << ObjectType # greedy collector'''
- collector = Collector()
- obj = ObjectType()
- collector << obj
- self.assertEqual(collector.items()[0], obj.identifier())
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/complex_test.py b/sources/shiboken2/tests/samplebinding/complex_test.py
deleted file mode 100644
index bff7b5828..000000000
--- a/sources/shiboken2/tests/samplebinding/complex_test.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for Complex class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import sample
-from sample import Point
-
-class ComplexTest(unittest.TestCase):
- '''Test case for conversions between C++ Complex class to Python complex class'''
-
- def testFunctionReturningComplexObject(self):
- '''Test function returning a C++ Complex object.'''
- cpx = sample.transmutePointIntoComplex(Point(5.0, 2.3))
- self.assertEqual(cpx, complex(5.0, 2.3))
-
- def testFunctionReceivingComplexObjectAsArgument(self):
- '''Test function returning a C++ Complex object.'''
- pt = sample.transmuteComplexIntoPoint(complex(1.2, 3.4))
- # these assertions intentionally avoids to test the == operator,
- # it should have its own test cases.
- self.assertEqual(pt.x(), 1.2)
- self.assertEqual(pt.y(), 3.4)
-
- def testComplexList(self):
- '''Test list of C++ Complex objects conversion to a list of Python complex objects.'''
- # the global function gimmeComplexList() is expected to return a list
- # containing the following Complex values: [0j, 1.1+2.2j, 1.3+2.4j]
- cpxlist = sample.gimmeComplexList()
- self.assertEqual(cpxlist, [complex(), complex(1.1, 2.2), complex(1.3, 2.4)])
-
- def testSumComplexPair(self):
- '''Test sum of a tuple containing two complex objects.'''
- cpx1 = complex(1.2, 3.4)
- cpx2 = complex(5.6, 7.8)
- self.assertEqual(sample.sumComplexPair((cpx1, cpx2)), cpx1 + cpx2)
-
- def testUsingTuples(self):
- cpx1, cpx2 = (1.2, 3.4), (5.6, 7.8)
- self.assertEqual(sample.sumComplexPair((cpx1, cpx2)), sample.sumComplexPair((complex(*cpx1), complex(*cpx2))))
- cpx1, cpx2 = (1, 3), (5, 7)
- self.assertEqual(sample.sumComplexPair((cpx1, cpx2)), sample.sumComplexPair((complex(*cpx1), complex(*cpx2))))
- cpx1, cpx2 = (1.2, 3), (5.6, 7)
- self.assertEqual(sample.sumComplexPair((cpx1, cpx2)), sample.sumComplexPair((complex(*cpx1), complex(*cpx2))))
- cpx1, cpx2 = (1, 2, 3), (4, 5, 7)
- self.assertRaises(TypeError, sample.sumComplexPair, (cpx1, cpx2))
- cpx1, cpx2 = ('1', '2'), ('4', '5')
- self.assertRaises(TypeError, sample.sumComplexPair, (cpx1, cpx2))
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/conversion_operator_test.py b/sources/shiboken2/tests/samplebinding/conversion_operator_test.py
deleted file mode 100644
index a18d27a0c..000000000
--- a/sources/shiboken2/tests/samplebinding/conversion_operator_test.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for implicit conversion generated by conversion operator.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Time, StrList
-
-class ConversionOperatorTest(unittest.TestCase):
- '''Test cases for implicit conversion generated by conversion operator.'''
-
- def testConversionOperator(self):
- '''Time defined an conversion operator for Str, so passing a Time object to a method expecting a Str should work.'''
- t = Time(1, 2, 3)
- t_str = t.toString()
- sl = StrList()
-
- # StrList.append expects a Str object.
- sl.append(t)
-
- self.assertEqual(len(sl), 1)
- self.assertEqual(sl[0], t_str)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/copy_test.py b/sources/shiboken2/tests/samplebinding/copy_test.py
deleted file mode 100644
index a8e02d979..000000000
--- a/sources/shiboken2/tests/samplebinding/copy_test.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for deep copy of objects'''
-
-import copy
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-try:
- import cPickle as pickle
-except ImportError:
- import pickle
-
-
-from sample import Point
-
-
-class SimpleCopy(unittest.TestCase):
- '''Simple copy of objects'''
-
- def testCopy(self):
- point = Point(0.1, 2.4)
- new_point = copy.copy(point)
-
- self.assertTrue(point is not new_point)
- self.assertEqual(point, new_point)
-
-
-class DeepCopy(unittest.TestCase):
- '''Deep copy with shiboken objects'''
-
- def testDeepCopy(self):
- '''Deep copy of value types'''
- point = Point(3.1, 4.2)
- new_point = copy.deepcopy([point])[0]
-
- self.assertTrue(point is not new_point)
- self.assertEqual(point, new_point)
-
-
-class PicklingTest(unittest.TestCase):
- '''Support pickling'''
-
- def testSimple(self):
- '''Simple pickling and unpickling'''
-
- point = Point(10.2, 43.5)
-
- data = pickle.dumps(point)
- new_point = pickle.loads(data)
-
- self.assertEqual(point, new_point)
- self.assertTrue(point is not new_point)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ctorconvrule_test.py b/sources/shiboken2/tests/samplebinding/ctorconvrule_test.py
deleted file mode 100644
index 7fd9b502c..000000000
--- a/sources/shiboken2/tests/samplebinding/ctorconvrule_test.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for proper generation of constructor altered by conversion-rule tag.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import CtorConvRule
-
-class TestCtorConvRule(unittest.TestCase):
- '''Simple test case for CtorConvRule'''
-
- def testCtorConvRule(self):
- '''Test CtorConvRule argument modification through conversion-rule tag.'''
- value = 123
- obj = CtorConvRule(value)
- self.assertEqual(obj.value(), value + 1)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/cyclic_test.py b/sources/shiboken2/tests/samplebinding/cyclic_test.py
deleted file mode 100644
index 8fe029d59..000000000
--- a/sources/shiboken2/tests/samplebinding/cyclic_test.py
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import ObjectType
-from sample import ObjectView
-from sample import ObjectModel
-
-
-
-class ObjTest(unittest.TestCase):
-
- def test_cyclic_dependency_withParent(self):
- """Create 2 objects with a cyclic dependency, so that they can
- only be removed by the garbage collector, and then invoke the
- garbage collector in a different thread.
- """
- import gc
-
- class CyclicChildObject(ObjectType):
- def __init__(self, parent):
- super(CyclicChildObject, self).__init__(parent)
- self._parent = parent
-
- class CyclicObject(ObjectType):
- def __init__(self):
- super(CyclicObject, self).__init__()
- CyclicChildObject(self)
-
- # turn off automatic garbage collection, to be able to trigger it
- # at the 'right' time
- gc.disable()
- alive = lambda :sum(isinstance(o, CyclicObject) for o in gc.get_objects() )
-
- #
- # first proof that the wizard is only destructed by the garbage
- # collector
- #
- cycle = CyclicObject()
- self.assertTrue(alive())
- del cycle
- self.assertTrue(alive())
- gc.collect()
- self.assertFalse(alive())
-
- def test_cyclic_dependency_withKeepRef(self):
- """Create 2 objects with a cyclic dependency, so that they can
- only be removed by the garbage collector, and then invoke the
- garbage collector in a different thread.
- """
- import gc
-
- class CyclicChildObject(ObjectView):
- def __init__(self, model):
- super(CyclicChildObject, self).__init__(None)
- self.setModel(model)
-
- class CyclicObject(ObjectModel):
- def __init__(self):
- super(CyclicObject, self).__init__()
- self._view = CyclicChildObject(self)
-
- # turn off automatic garbage collection, to be able to trigger it
- # at the 'right' time
- gc.disable()
- alive = lambda :sum(isinstance(o, CyclicObject) for o in gc.get_objects() )
-
- #
- # first proof that the wizard is only destructed by the garbage
- # collector
- #
- cycle = CyclicObject()
- self.assertTrue(alive())
- del cycle
- self.assertTrue(alive())
- gc.collect()
- self.assertFalse(alive())
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/date_test.py b/sources/shiboken2/tests/samplebinding/date_test.py
deleted file mode 100644
index 0a89db871..000000000
--- a/sources/shiboken2/tests/samplebinding/date_test.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for python conversions types '''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from datetime import date
-
-from sample import SbkDate
-
-class DateConversionTest(unittest.TestCase):
-
- def testConstructorWithDateObject(self):
- pyDate = date(2010, 12, 12)
- cDate = SbkDate(pyDate)
- self.assertTrue(cDate.day(), pyDate.day)
- self.assertTrue(cDate.month(), pyDate.month)
- self.assertTrue(cDate.year(), pyDate.year)
-
- def testToPythonFunction(self):
- cDate = SbkDate(2010, 12, 12)
- pyDate = cDate.toPython()
- self.assertTrue(cDate.day(), pyDate.day)
- self.assertTrue(cDate.month(), pyDate.month)
- self.assertTrue(cDate.year(), pyDate.year)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/decisor_test.py b/sources/shiboken2/tests/samplebinding/decisor_test.py
deleted file mode 100644
index e98e45bfc..000000000
--- a/sources/shiboken2/tests/samplebinding/decisor_test.py
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for the method overload decisor.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import SampleNamespace, Point, ObjectType, ObjectModel
-
-class DecisorTest(unittest.TestCase):
- '''Test cases for the method overload decisor.'''
-
- def testCallWithInvalidParametersSideA(self):
- '''Call a method missing with the last argument missing.
- This can trigger the bug #262, which means using an argument
- not provided by the user.'''
- pt = Point()
- # This exception may move from a TypeError to a ValueError.
- self.assertRaises((TypeError, ValueError), SampleNamespace.forceDecisorSideA, pt)
-
- def testCallWithInvalidParametersSideB(self):
- '''Same as the previous test, but with an integer as first argument,
- just to complicate things for the overload method decisor.'''
- pt = Point()
- # This exception may move from a TypeError to a ValueError.
- self.assertRaises((TypeError, ValueError), SampleNamespace.forceDecisorSideB, 1, pt)
-
- def testDecideCallWithInheritance(self):
- '''Call methods overloads that receive parent and inheritor classes' instances.'''
- objecttype = ObjectType()
- objectmodel = ObjectModel()
- self.assertEqual(ObjectModel.receivesObjectTypeFamily(objecttype), ObjectModel.ObjectTypeCalled)
- self.assertNotEqual(ObjectModel.receivesObjectTypeFamily(objecttype), ObjectModel.ObjectModelCalled)
- self.assertEqual(ObjectModel.receivesObjectTypeFamily(objectmodel), ObjectModel.ObjectModelCalled)
- self.assertNotEqual(ObjectModel.receivesObjectTypeFamily(objectmodel), ObjectModel.ObjectTypeCalled)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/delete_test.py b/sources/shiboken2/tests/samplebinding/delete_test.py
deleted file mode 100644
index b35bba4b0..000000000
--- a/sources/shiboken2/tests/samplebinding/delete_test.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import sample
-import shiboken2 as shiboken
-
-class DeleteTest(unittest.TestCase):
- def testNonCppWrapperClassDelete(self):
- """Would segfault when shiboken.delete called on obj not created from
- Python """
- obj = sample.ObjectType()
- child = obj.createChild(None)
- shiboken.delete(child)
- assert not shiboken.isValid(child)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/deprecated_test.py b/sources/shiboken2/tests/samplebinding/deprecated_test.py
deleted file mode 100644
index d75490e17..000000000
--- a/sources/shiboken2/tests/samplebinding/deprecated_test.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-import warnings
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType
-
-class TestDeprecatedCall(unittest.TestCase):
- def testCallWithError(self):
- o = ObjectType()
- warnings.simplefilter('error')
- self.assertRaises(DeprecationWarning, o.deprecatedFunction)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/derived_test.py b/sources/shiboken2/tests/samplebinding/derived_test.py
deleted file mode 100644
index 81f3a8034..000000000
--- a/sources/shiboken2/tests/samplebinding/derived_test.py
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for Derived class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import sample
-from sample import Abstract, Derived, OverloadedFuncEnum
-
-class Deviant(Derived):
- def __init__(self):
- Derived.__init__(self)
- self.pure_virtual_called = False
- self.unpure_virtual_called = False
-
- def pureVirtual(self):
- self.pure_virtual_called = True
-
- def unpureVirtual(self):
- self.unpure_virtual_called = True
-
- def className(self):
- return 'Deviant'
-
-class DerivedTest(unittest.TestCase):
- '''Test case for Derived class'''
-
- def testParentClassMethodsAvailability(self):
- '''Test if Derived class really inherits its methods from parent.'''
- inherited_methods = set(['callPureVirtual', 'callUnpureVirtual',
- 'id_', 'pureVirtual', 'unpureVirtual'])
- self.assertTrue(inherited_methods.issubset(dir(Derived)))
-
- def testOverloadedMethodCall(self):
- '''Test if the correct overloaded method is being called.'''
- derived = Derived()
-
- result = derived.overloaded(1, 2)
- self.assertEqual(type(result), OverloadedFuncEnum)
- self.assertEqual(result, sample.OverloadedFunc_ii)
-
- result = derived.overloaded(3)
- self.assertEqual(type(result), OverloadedFuncEnum)
- self.assertEqual(result, sample.OverloadedFunc_ii)
-
- result = derived.overloaded(4.4)
- self.assertEqual(type(result), OverloadedFuncEnum)
- self.assertEqual(result, sample.OverloadedFunc_d)
-
- def testOtherOverloadedMethodCall(self):
- '''Another test to check overloaded method calling, just to double check.'''
- derived = Derived()
-
- result = derived.otherOverloaded(1, 2, True, 3.3)
- self.assertEqual(type(result), Derived.OtherOverloadedFuncEnum)
- self.assertEqual(result, sample.Derived.OtherOverloadedFunc_iibd)
-
- result = derived.otherOverloaded(1, 2.2)
- self.assertEqual(type(result), Derived.OtherOverloadedFuncEnum)
- self.assertEqual(result, Derived.OtherOverloadedFunc_id)
-
- def testOverloadedMethodCallWithDifferentNumericTypes(self):
- '''Test if the correct overloaded method accepts a different numeric type as argument.'''
- derived = Derived()
- result = derived.overloaded(1.1, 2.2)
- self.assertEqual(type(result), OverloadedFuncEnum)
- self.assertEqual(result, sample.OverloadedFunc_ii)
-
- def testOverloadedMethodCallWithWrongNumberOfArguments(self):
- '''Test if a call to an overloaded method with the wrong number of arguments raises an exception.'''
- derived = Derived()
- self.assertRaises(TypeError, derived.otherOverloaded, 1, 2, True)
-
- def testReimplementedPureVirtualMethodCall(self):
- '''Test if a Python override of a implemented pure virtual method is correctly called from C++.'''
- d = Deviant()
- d.callPureVirtual()
- self.assertTrue(d.pure_virtual_called)
-
- def testReimplementedVirtualMethodCall(self):
- '''Test if a Python override of a reimplemented virtual method is correctly called from C++.'''
- d = Deviant()
- d.callUnpureVirtual()
- self.assertTrue(d.unpure_virtual_called)
-
- def testVirtualMethodCallString(self):
- '''Test virtual method call returning string.'''
- d = Derived()
- self.assertEqual(d.className(), 'Derived')
- self.assertEqual(d.getClassName(), 'Derived')
-
- def testReimplementedVirtualMethodCallReturningString(self):
- '''Test if a Python override of a reimplemented virtual method is correctly called from C++.'''
- d = Deviant()
- self.assertEqual(d.className(), 'Deviant')
- self.assertEqual(d.getClassName(), 'Deviant')
-
- def testSingleArgument(self):
- '''Test singleArgument call.'''
- d = Derived()
- self.assertTrue(d.singleArgument(False))
- self.assertTrue(not d.singleArgument(True))
-
- def testMethodCallWithDefaultValue(self):
- '''Test method call with default value.'''
- d = Derived()
- self.assertEqual(d.defaultValue(3), 3.1)
- self.assertEqual(d.defaultValue(), 0.1)
-
- def testCallToMethodWithAbstractArgument(self):
- '''Call to method that expects an Abstract argument.'''
- objId = 123
- d = Derived(objId)
- self.assertEqual(Abstract.getObjectId(d), objId)
-
- def testObjectCreationWithParentType(self):
- '''Derived class creates an instance of itself in C++ and returns it as a pointer to its ancestor Abstract.'''
- obj = Derived.createObject()
- self.assertEqual(type(obj), Derived)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/duck_punching_test.py b/sources/shiboken2/tests/samplebinding/duck_punching_test.py
deleted file mode 100644
index 3f9d69b47..000000000
--- a/sources/shiboken2/tests/samplebinding/duck_punching_test.py
+++ /dev/null
@@ -1,182 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for virtual methods.'''
-
-import os
-import sys
-import types
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from py3kcompat import IS_PY3K
-
-from sample import VirtualMethods, SimpleFile, Point
-
-def MethodTypeCompat(func, instance):
- if IS_PY3K:
- return types.MethodType(func, instance)
- else:
- return types.MethodType(func, instance, type(instance))
-
-class Duck(VirtualMethods):
- def __init__(self):
- VirtualMethods.__init__(self)
-
-class Monkey(SimpleFile):
- def __init__(self, filename):
- SimpleFile.__init__(self, filename)
-
-class DuckPunchingTest(unittest.TestCase):
- '''Test case for duck punching (aka "monkey patching").'''
-
- def setUp(self):
- self.multiplier = 2.0
- self.duck_method_called = False
- self.call_counter = 0
-
- def testMonkeyPatchOnVirtualMethod(self):
- '''Injects new 'virtualMethod0' on a VirtualMethods instance and makes C++ call it.'''
- vm = VirtualMethods()
- pt, val, cpx, b = Point(1.1, 2.2), 4, complex(3.3, 4.4), True
-
- result1 = vm.virtualMethod0(pt, val, cpx, b)
- result2 = vm.callVirtualMethod0(pt, val, cpx, b)
- self.assertEqual(result1, result2)
- self.assertEqual(result1, VirtualMethods.virtualMethod0(vm, pt, val, cpx, b))
-
- def myVirtualMethod0(obj, pt, val, cpx, b):
- self.duck_method_called = True
- return VirtualMethods.virtualMethod0(obj, pt, val, cpx, b) * self.multiplier
- vm.virtualMethod0 = MethodTypeCompat(myVirtualMethod0, vm)
-
- result1 = vm.callVirtualMethod0(pt, val, cpx, b)
- self.assertTrue(self.duck_method_called)
-
- result2 = vm.virtualMethod0(pt, val, cpx, b)
- self.assertEqual(result1, result2)
- self.assertEqual(result1, VirtualMethods.virtualMethod0(vm, pt, val, cpx, b) * self.multiplier)
-
- # This is done to decrease the refcount of the vm object
- # allowing the object wrapper to be deleted before the
- # BindingManager. This is useful when compiling Shiboken
- # for debug, since the BindingManager destructor has an
- # assert that checks if the wrapper mapper is empty.
- vm.virtualMethod0 = None
-
- def testMonkeyPatchOnVirtualMethodWithInheritance(self):
- '''Injects new 'virtualMethod0' on an object that inherits from VirtualMethods and makes C++ call it.'''
- duck = Duck()
- pt, val, cpx, b = Point(1.1, 2.2), 4, complex(3.3, 4.4), True
-
- result1 = duck.virtualMethod0(pt, val, cpx, b)
- result2 = duck.callVirtualMethod0(pt, val, cpx, b)
- self.assertEqual(result1, result2)
- self.assertEqual(result1, VirtualMethods.virtualMethod0(duck, pt, val, cpx, b))
-
- def myVirtualMethod0(obj, pt, val, cpx, b):
- self.duck_method_called = True
- return VirtualMethods.virtualMethod0(obj, pt, val, cpx, b) * self.multiplier
- duck.virtualMethod0 = MethodTypeCompat(myVirtualMethod0, duck)
-
- result1 = duck.callVirtualMethod0(pt, val, cpx, b)
- self.assertTrue(self.duck_method_called)
-
- result2 = duck.virtualMethod0(pt, val, cpx, b)
- self.assertEqual(result1, result2)
- self.assertEqual(result1, VirtualMethods.virtualMethod0(duck, pt, val, cpx, b) * self.multiplier)
-
- duck.virtualMethod0 = None
-
- def testMonkeyPatchOnMethodWithStaticAndNonStaticOverloads(self):
- '''Injects new 'exists' on a SimpleFile instance and makes C++ call it.'''
- simplefile = SimpleFile('foobar')
-
- # Static 'exists'
- simplefile.exists('sbrubbles')
- self.assertFalse(self.duck_method_called)
- # Non-static 'exists'
- simplefile.exists()
- self.assertFalse(self.duck_method_called)
-
- def myExists(obj):
- self.duck_method_called = True
- return False
- simplefile.exists = MethodTypeCompat(myExists, simplefile)
-
- # Static 'exists' was overridden by the monkey patch, which accepts 0 arguments
- self.assertRaises(TypeError, simplefile.exists, 'sbrubbles')
- # Monkey patched exists
- simplefile.exists()
- self.assertTrue(self.duck_method_called)
-
- simplefile.exists = None
-
- def testMonkeyPatchOnMethodWithStaticAndNonStaticOverloadsWithInheritance(self):
- '''Injects new 'exists' on an object that inherits from SimpleFile and makes C++ call it.'''
- monkey = Monkey('foobar')
-
- # Static 'exists'
- monkey.exists('sbrubbles')
- self.assertFalse(self.duck_method_called)
- # Non-static 'exists'
- monkey.exists()
- self.assertFalse(self.duck_method_called)
-
- def myExists(obj):
- self.duck_method_called = True
- return False
- monkey.exists = MethodTypeCompat(myExists, monkey)
-
- # Static 'exists' was overridden by the monkey patch, which accepts 0 arguments
- self.assertRaises(TypeError, monkey.exists, 'sbrubbles')
- # Monkey patched exists
- monkey.exists()
- self.assertTrue(self.duck_method_called)
-
- monkey.exists = None
-
- def testForInfiniteRecursion(self):
- def myVirtualMethod0(obj, pt, val, cpx, b):
- self.call_counter += 1
- return VirtualMethods.virtualMethod0(obj, pt, val, cpx, b)
- vm = VirtualMethods()
- vm.virtualMethod0 = MethodTypeCompat(myVirtualMethod0, vm)
- pt, val, cpx, b = Point(1.1, 2.2), 4, complex(3.3, 4.4), True
- vm.virtualMethod0(pt, val, cpx, b)
- self.assertEqual(self.call_counter, 1)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/echo_test.py b/sources/shiboken2/tests/samplebinding/echo_test.py
deleted file mode 100644
index cd3fcc090..000000000
--- a/sources/shiboken2/tests/samplebinding/echo_test.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for <add-function> with const char* as argument'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Echo
-
-class TestEcho(unittest.TestCase):
- '''Simple test case for Echo.echo'''
-
- def testEcho(self):
- '''Test function added with const char * as arg'''
- x = 'Foobar'
- y = Echo().echo(x)
- self.assertEqual(x, y)
-
- def testCallOperator(self):
- e = Echo()
- self.assertEqual(e("Hello", 3), "Hello3");
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/enum_test.py b/sources/shiboken2/tests/samplebinding/enum_test.py
deleted file mode 100644
index 0beb72033..000000000
--- a/sources/shiboken2/tests/samplebinding/enum_test.py
+++ /dev/null
@@ -1,188 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for Python representation of C++ enums.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import shiboken2
-# This is needed after the introduction of BUILD_DIR.
-
-import sample
-from sample import SampleNamespace, ObjectType, Event
-from py3kcompat import IS_PY3K, b
-
-def createTempFile():
- if sys.version_info >= (2, 6):
- import tempfile
- return tempfile.SpooledTemporaryFile(mode='rw')
- else:
- return os.tmpfile()
-
-class EnumTest(unittest.TestCase):
- '''Test case for Python representation of C++ enums.'''
-
- def testEnumRepr(self):
- enum = SampleNamespace.Option(1)
- self.assertEqual(eval(repr(enum)), enum)
-
- enum = SampleNamespace.Option(999)
- self.assertEqual(eval(repr(enum)), enum)
-
- def testHashability(self):
- self.assertEqual(hash(SampleNamespace.TwoIn), hash(SampleNamespace.TwoOut))
- self.assertNotEqual(hash(SampleNamespace.TwoIn), hash(SampleNamespace.OneIn))
-
- def testEnumValuesInsideEnum(self):
- '''Enum values should be accessible inside the enum as well as outside.'''
- for value_name in SampleNamespace.Option.values:
- enum_item1 = getattr(SampleNamespace.Option, value_name)
- enum_item2 = getattr(SampleNamespace, value_name)
- self.assertEqual(enum_item1, enum_item2)
-
- def testPassingIntegerOnEnumArgument(self):
- '''Tries to use an integer in place of an enum argument.'''
- self.assertRaises(TypeError, SampleNamespace.getNumber, 1)
-
- def testBuildingEnumFromIntegerValue(self):
- '''Tries to build the proper enum using an integer.'''
- SampleNamespace.getNumber(SampleNamespace.Option(1))
-
- def testBuildingEnumWithDefaultValue(self):
- '''Enum constructor with default value'''
- enum = SampleNamespace.Option()
- self.assertEqual(enum, SampleNamespace.None_)
-
- def testEnumConversionToAndFromPython(self):
- '''Conversion of enum objects from Python to C++ back again.'''
- enumout = SampleNamespace.enumInEnumOut(SampleNamespace.TwoIn)
- self.assertTrue(enumout, SampleNamespace.TwoOut)
- self.assertEqual(repr(enumout), repr(SampleNamespace.TwoOut))
-
- def testEnumConstructorWithTooManyParameters(self):
- '''Calling the constructor of non-extensible enum with the wrong number of parameters.'''
- self.assertRaises(TypeError, SampleNamespace.InValue, 13, 14)
-
- def testEnumConstructorWithNonNumberParameter(self):
- '''Calling the constructor of non-extensible enum with a string.'''
- self.assertRaises(TypeError, SampleNamespace.InValue, '1')
-
- def testEnumItemAsDefaultValueToIntArgument(self):
- '''Calls function with an enum item as default value to an int argument.'''
- self.assertEqual(SampleNamespace.enumItemAsDefaultValueToIntArgument(), SampleNamespace.ZeroIn)
- self.assertEqual(SampleNamespace.enumItemAsDefaultValueToIntArgument(SampleNamespace.ZeroOut), SampleNamespace.ZeroOut)
- self.assertEqual(SampleNamespace.enumItemAsDefaultValueToIntArgument(123), 123)
-
- def testAnonymousGlobalEnums(self):
- '''Checks availability of anonymous global enum items.'''
- self.assertEqual(sample.AnonymousGlobalEnum_Value0, 0)
- self.assertEqual(sample.AnonymousGlobalEnum_Value1, 1)
-
- def testAnonymousClassEnums(self):
- '''Checks availability of anonymous class enum items.'''
- self.assertEqual(SampleNamespace.AnonymousClassEnum_Value0, 0)
- self.assertEqual(SampleNamespace.AnonymousClassEnum_Value1, 1)
-
- def testEnumClasses(self):
- # C++ 11: values of enum classes need to be fully qualified to match C++
- 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()
- if IS_PY3K:
- from py3k import printToFile
- printToFile(tmpfile, Event.ANY_EVENT)
- else:
- sys.stdout = tmpfile
- print(Event.ANY_EVENT)
- sys.stdout = sys.__stdout__
- tmpfile.seek(0)
- text = tmpfile.read().strip()
- tmpfile.close()
- self.assertEqual(text, str(Event.ANY_EVENT))
- self.assertEqual(text, repr(Event.ANY_EVENT))
-
- def testEnumArgumentWithDefaultValue(self):
- '''Option enumArgumentWithDefaultValue(Option opt = UnixTime);'''
- self.assertEqual(SampleNamespace.enumArgumentWithDefaultValue(), SampleNamespace.UnixTime)
- self.assertEqual(SampleNamespace.enumArgumentWithDefaultValue(SampleNamespace.RandomNumber), SampleNamespace.RandomNumber)
-
-
-class MyEvent(Event):
- def __init__(self):
- Event.__init__(self, Event.EventType(999))
-
-class OutOfBoundsTest(unittest.TestCase):
- def testValue(self):
- e = MyEvent()
- self.assertEqual(repr(e.eventType()), 'sample.Event.EventType(999)')
-
- def testNoneName(self):
- e = MyEvent()
- t = e.eventType()
- self.assertEqual(t.name, None)
-
-class EnumOverloadTest(unittest.TestCase):
- '''Test case for overloads involving enums'''
-
- def testWithInt(self):
- '''Overload with Enums and ints with default value'''
- o = ObjectType()
-
- self.assertEqual(o.callWithEnum('', Event.ANY_EVENT, 9), 81)
- self.assertEqual(o.callWithEnum('', 9), 9)
-
-class EnumOperators(unittest.TestCase):
- '''Test case for operations on enums'''
-
- def testInequalitySameObject(self):
- self.assertFalse(Event.ANY_EVENT != Event.ANY_EVENT)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/enumfromremovednamespace_test.py b/sources/shiboken2/tests/samplebinding/enumfromremovednamespace_test.py
deleted file mode 100644
index 4b0866c4e..000000000
--- a/sources/shiboken2/tests/samplebinding/enumfromremovednamespace_test.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import sample
-
-class TestEnumFromRemovedNamespace(unittest.TestCase):
- def testEnumPromotedToGlobal(self):
- sample.RemovedNamespace1_Enum
- sample.RemovedNamespace1_Enum_Value0
- sample.RemovedNamespace1_AnonymousEnum_Value0
- sample.RemovedNamespace2_Enum
- sample.RemovedNamespace2_Enum_Value0
-
- def testEnumPromotedToUpperNamespace(self):
- sample.UnremovedNamespace
- sample.UnremovedNamespace.RemovedNamespace3_Enum
- sample.UnremovedNamespace.RemovedNamespace3_Enum_Value0
- sample.UnremovedNamespace.RemovedNamespace3_AnonymousEnum_Value0
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/event_loop_call_virtual_test.py b/sources/shiboken2/tests/samplebinding/event_loop_call_virtual_test.py
deleted file mode 100644
index 41b91ed70..000000000
--- a/sources/shiboken2/tests/samplebinding/event_loop_call_virtual_test.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/env python
-
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Simple event loop dispatcher test.'''
-
-import os
-import sys
-import time
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from random import random
-
-from sample import ObjectType, Event
-
-
-class NoOverride(ObjectType):
-
- pass
-
-
-class Override(ObjectType):
-
- def __init__(self):
- ObjectType.__init__(self)
- self.called = False
-
- def event(self, event):
- self.called = True
- return True
-
-
-class TestEventLoop(unittest.TestCase):
-
- def testEventLoop(self):
- '''Calling virtuals in a event loop'''
- objs = [ObjectType(), NoOverride(), Override()]
-
- evaluated = ObjectType.processEvent(objs,
- Event(Event.BASIC_EVENT))
-
- self.assertEqual(evaluated, 3)
- self.assertTrue(objs[2].called)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/event_loop_thread_test.py b/sources/shiboken2/tests/samplebinding/event_loop_thread_test.py
deleted file mode 100644
index 4c63d0665..000000000
--- a/sources/shiboken2/tests/samplebinding/event_loop_thread_test.py
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/env python
-
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-from random import random
-import sys
-import time
-import threading
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType, Event
-
-
-class Producer(ObjectType):
-
- def __init__(self):
- ObjectType.__init__(self)
- self.data = None
- self.read = False
-
- def event(self, event):
- self.data = random()
-
- while not self.read:
- time.sleep(0.01)
-
- return True
-
-
-class Collector(threading.Thread):
-
- def __init__(self, objects):
- threading.Thread.__init__(self)
- self.max_runs = len(objects)
- self.objects = objects
- self.data = []
-
- def run(self):
- i = 0
- while i < self.max_runs:
- if self.objects[i].data is not None:
- self.data.append(self.objects[i].data)
- self.objects[i].read = True
- i += 1
- time.sleep(0.01)
-
-
-class TestEventLoopWithThread(unittest.TestCase):
- '''Communication between a python thread and an simple
- event loop in C++'''
-
- def testBasic(self):
- '''Allowing threads and calling virtuals from C++'''
- number = 10
- objs = [Producer() for x in range(number)]
- thread = Collector(objs)
-
- thread.start()
-
- evaluated = ObjectType.processEvent(objs,
- Event(Event.BASIC_EVENT))
-
- thread.join()
-
- producer_data = [x.data for x in objs]
- self.assertEqual(evaluated, number)
- self.assertEqual(producer_data, thread.data)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/exception_test.py b/sources/shiboken2/tests/samplebinding/exception_test.py
deleted file mode 100644
index 3224dfe17..000000000
--- a/sources/shiboken2/tests/samplebinding/exception_test.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env python
-#
-#############################################################################
-##
-## Copyright (C) 2018 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ExceptionTest
-
-class CppExceptionTest(unittest.TestCase):
-
- def testVoid(self):
- exceptionCount = 0
- et = ExceptionTest()
-
- et.voidThrowStdException(False)
-
- try:
- et.voidThrowStdException(True)
- except:
- exceptionCount += 1
-
- et.voidThrowInt(False)
-
- try:
- et.voidThrowInt(True)
- except:
- exceptionCount += 1
-
- self.assertEqual(exceptionCount, 2)
-
- def testReturnValue(self):
- exceptionCount = 0
- et = ExceptionTest()
-
- result = et.intThrowStdException(False);
-
- try:
- result = et.intThrowStdException(True);
- except:
- exceptionCount += 1
-
- result = et.intThrowInt(False);
-
- try:
- result = et.intThrowInt(True);
- except:
- exceptionCount += 1
-
- self.assertEqual(exceptionCount, 2)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/filter_test.py b/sources/shiboken2/tests/samplebinding/filter_test.py
deleted file mode 100644
index b09d89980..000000000
--- a/sources/shiboken2/tests/samplebinding/filter_test.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Data, Intersection, Union
-
-class TestFilters(unittest.TestCase):
-
- def testAnd(self):
-
- f1 = Data(Data.Name, "joe")
- f2 = Union()
-
- inter = f1 & f2
-
- self.assertEqual(type(inter), Intersection)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/global.h b/sources/shiboken2/tests/samplebinding/global.h
deleted file mode 100644
index f4e20b74f..000000000
--- a/sources/shiboken2/tests/samplebinding/global.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "abstract.h"
-#include "blackbox.h"
-#include "bytearray.h"
-#include "bucket.h"
-#include "collector.h"
-#include "complex.h"
-#include "ctorconvrule.h"
-#include "cvlist.h"
-#include "sbkdate.h"
-#include "derived.h"
-#include "echo.h"
-#include "exceptiontest.h"
-#include "functions.h"
-#include "implicitconv.h"
-#include "nontypetemplate.h"
-#include "overloadsort.h"
-#include "handle.h"
-#include "injectcode.h"
-#include "list.h"
-#include "listuser.h"
-#include "mapuser.h"
-#include "modelindex.h"
-#include "modifications.h"
-#include "modified_constructor.h"
-#include "multiple_derived.h"
-#include "noimplicitconversion.h"
-#include "nondefaultctor.h"
-#include "objectmodel.h"
-#include "objecttype.h"
-#include "objecttypebyvalue.h"
-#include "objecttypeholder.h"
-#include "objecttypelayout.h"
-#include "objecttypeoperators.h"
-#include "objectview.h"
-#include "oddbool.h"
-#include "onlycopy.h"
-#include "overload.h"
-#include "pairuser.h"
-#include "pen.h"
-#include "photon.h"
-#include "point.h"
-#include "pointf.h"
-#include "pointerholder.h"
-#include "polygon.h"
-#include "privatector.h"
-#include "privatedtor.h"
-#include "protected.h"
-#include "rect.h"
-#include "reference.h"
-#include "renaming.h"
-#include "removednamespaces.h"
-#include "sample.h"
-#include "samplenamespace.h"
-#include "simplefile.h"
-#include "size.h"
-#include "str.h"
-#include "strlist.h"
-#include "sometime.h"
-#include "templateptr.h"
-#include "transform.h"
-#include "virtualmethods.h"
-#include "voidholder.h"
-#include "valueandvirtual.h"
-#include "expression.h"
-#include "filter.h"
diff --git a/sources/shiboken2/tests/samplebinding/handleholder_test.py b/sources/shiboken2/tests/samplebinding/handleholder_test.py
deleted file mode 100644
index a4cbd1c72..000000000
--- a/sources/shiboken2/tests/samplebinding/handleholder_test.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-''' Test case for a class that holds a unknown handle object.
- Test case for BUG #1105.
-'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import HandleHolder
-
-class HandleHolderTest(unittest.TestCase):
- def testCreation(self):
- holder = HandleHolder(HandleHolder.createHandle())
- holder2 = HandleHolder(HandleHolder.createHandle())
- self.assertEqual(holder.compare(holder2), False)
-
- def testTransfer(self):
- holder = HandleHolder()
- holder2 = HandleHolder(holder.handle())
- self.assertTrue(holder.compare(holder2))
-
- def testUseDefinedType(self):
- holder = HandleHolder(8)
- holder2 = HandleHolder(holder.handle2())
- self.assertTrue(holder.compare2(holder2))
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/hashabletype_test.py b/sources/shiboken2/tests/samplebinding/hashabletype_test.py
deleted file mode 100644
index b985abaad..000000000
--- a/sources/shiboken2/tests/samplebinding/hashabletype_test.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for __hash__'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class HashableTest(unittest.TestCase):
-
- def testStrHash(self):
- h = {}
- s = Str("Hi")
- h[s] = 2
- self.assertTrue(h.get(s), 2)
-
- def testObjectTypeHash(self):
- h = {}
- o = ObjectType()
- h[o] = 2
- self.assertTrue(h.get(o), 2)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ignorederefop_test.py b/sources/shiboken2/tests/samplebinding/ignorederefop_test.py
deleted file mode 100644
index 2237443b3..000000000
--- a/sources/shiboken2/tests/samplebinding/ignorederefop_test.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import *
-
-class TestLackOfDereferenceOperators (unittest.TestCase):
- def testIf(self):
- r = Reference()
- self.assertFalse(hasattr(r, "__mul__"))
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/implicitconv_numerical_test.py b/sources/shiboken2/tests/samplebinding/implicitconv_numerical_test.py
deleted file mode 100644
index ebecf9ad8..000000000
--- a/sources/shiboken2/tests/samplebinding/implicitconv_numerical_test.py
+++ /dev/null
@@ -1,157 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for inplicit converting C++ numeric types.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import sys
-import sample
-from py3kcompat import IS_PY3K, l, long
-
-# Hardcode the limits of the underlying C-types depending on architecture and memory
-# model (taking MSVC using LLP64 into account).
-cIntMin = -2147483648
-cIntMax = 2147483647
-cLongMin = cIntMin
-cLongMax = cIntMax
-maxRepresentableInt = sys.maxsize if IS_PY3K else sys.maxint
-is64bitArchitecture = maxRepresentableInt > 2**32
-if is64bitArchitecture and sys.platform != 'win32':
- cLongMin = -9223372036854775808
- cLongMax = 9223372036854775807
-
-class NumericTester(unittest.TestCase):
- '''Helper class for numeric comparison testing'''
-
- def check_value(self, source, expected, callback, desired_type=None):
- result = callback(source)
- self.assertEqual(result, expected)
-
- if desired_type:
- self.assertEqual(type(result), desired_type)
-
-
-class FloatImplicitConvert(NumericTester):
- '''Test case for implicit converting C++ numeric types.'''
-
- def testFloatAsInt(self):
- '''Float as Int'''
- self.check_value(3.14, 3, sample.acceptInt, int)
- self.assertRaises(OverflowError, sample.acceptInt, cIntMax + 400)
-
- def testFloatAsLong(self):
- '''Float as Long'''
- #C++ longs are python ints for us
- self.check_value(3.14, 3, sample.acceptLong, int)
- self.assertRaises(OverflowError, sample.acceptLong, cLongMax + 400)
-
- def testFloatAsUInt(self):
- '''Float as unsigned Int'''
- self.check_value(3.14, 3, sample.acceptUInt, long)
- self.assertRaises(OverflowError, sample.acceptUInt, -3.14)
-
- def testFloatAsULong(self):
- '''Float as unsigned Long'''
- #FIXME Breaking with SystemError "bad argument to internal function"
- self.check_value(3.14, 3, sample.acceptULong, long)
- self.assertRaises(OverflowError, sample.acceptULong, -3.14)
-
- def testFloatAsDouble(self):
- '''Float as double'''
- self.check_value(3.14, 3.14, sample.acceptDouble, float)
-
-
-class IntImplicitConvert(NumericTester):
- '''Test case for implicit converting C++ numeric types.'''
-
- def testIntAsInt(self):
- '''Int as Int'''
- self.check_value(3, 3, sample.acceptInt, int)
-
- def testIntAsLong(self):
- '''Int as Long'''
- self.check_value(3, 3, sample.acceptLong, int)
-
- # cLongMax goes here as CPython implements int as a C long
- self.check_value(cLongMax, cLongMax, sample.acceptLong, int)
- self.check_value(cLongMin, cLongMin, sample.acceptLong, int)
-
- def testIntAsUInt(self):
- '''Int as unsigned Int'''
- self.check_value(3, 3, sample.acceptUInt, long)
- self.assertRaises(OverflowError, sample.acceptUInt, -3)
-
- def testIntAsULong(self):
- '''Int as unsigned Long'''
- self.check_value(3, 3, sample.acceptULong, long)
- self.assertRaises(OverflowError, sample.acceptULong, -3)
-
- def testFloatAsDouble(self):
- '''Float as double'''
- self.check_value(3.14, 3.14, sample.acceptDouble, float)
-
-
-class LongImplicitConvert(NumericTester):
- '''Test case for implicit converting C++ numeric types.'''
-
- def testLongAsInt(self):
- '''Long as Int'''
- self.check_value(l(24224), 24224, sample.acceptInt, int)
- self.assertRaises(OverflowError, sample.acceptInt, cIntMax + 20)
-
- def testLongAsLong(self):
- '''Long as Long'''
- self.check_value(l(2405), 2405, sample.acceptLong, int)
- self.assertRaises(OverflowError, sample.acceptLong, cLongMax + 20)
-
- def testLongAsUInt(self):
- '''Long as unsigned Int'''
- self.check_value(l(260), 260, sample.acceptUInt, long)
- self.assertRaises(OverflowError, sample.acceptUInt, -42)
-
- def testLongAsULong(self):
- '''Long as unsigned Long'''
- self.check_value(l(128), 128, sample.acceptULong, long)
- self.assertRaises(OverflowError, sample.acceptULong, l(-334))
-
- def testLongAsDouble(self):
- '''Float as double'''
- self.check_value(l(42), 42, sample.acceptDouble, float)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/implicitconv_test.py b/sources/shiboken2/tests/samplebinding/implicitconv_test.py
deleted file mode 100644
index a6b770c9b..000000000
--- a/sources/shiboken2/tests/samplebinding/implicitconv_test.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for implicit conversions'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ImplicitConv, ObjectType
-
-class ImplicitConvTest(unittest.TestCase):
- '''Test case for implicit conversions'''
-
- def testImplicitConversions(self):
- '''Test if overloaded function call decisor takes implicit conversions into account.'''
- ic = ImplicitConv.implicitConvCommon(ImplicitConv())
- self.assertEqual(ic.ctorEnum(), ImplicitConv.CtorNone)
-
- ic = ImplicitConv.implicitConvCommon(3)
- self.assertEqual(ic.ctorEnum(), ImplicitConv.CtorOne)
- self.assertEqual(ic.objId(), 3)
-
- ic = ImplicitConv.implicitConvCommon(ImplicitConv.CtorThree)
- self.assertEqual(ic.ctorEnum(), ImplicitConv.CtorThree)
-
- obj = ObjectType()
- ic = ImplicitConv.implicitConvCommon(obj)
- self.assertEqual(ic.ctorEnum(), ImplicitConv.CtorObjectTypeReference)
-
- ic = ImplicitConv.implicitConvCommon(42.42)
- self.assertEqual(ic.value(), 42.42)
-
- ic = ImplicitConv(None)
- self.assertEqual(ic.ctorEnum(), ImplicitConv.CtorPrimitiveType)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/inheritanceandscope_test.py b/sources/shiboken2/tests/samplebinding/inheritanceandscope_test.py
deleted file mode 100644
index 6b8a91573..000000000
--- a/sources/shiboken2/tests/samplebinding/inheritanceandscope_test.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for finding scope in cases involving inheritance.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import SampleNamespace
-
-class ScopeAndInheritanceTest(unittest.TestCase):
- '''Test cases for finding scope in cases involving inheritance.'''
-
- def testMethodCorrectlyWrapper(self):
- '''A method returning a type declared in the scope of the method's
- class parent must be found and the method correctly exported.'''
- meth = getattr(SampleNamespace.DerivedFromNamespace, 'methodReturningTypeFromParentScope')
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/injectcode_test.py b/sources/shiboken2/tests/samplebinding/injectcode_test.py
deleted file mode 100644
index 8bdcdbe61..000000000
--- a/sources/shiboken2/tests/samplebinding/injectcode_test.py
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for std::list container conversions'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import InjectCode
-
-class MyInjectCode(InjectCode):
- def __init__(self):
- InjectCode.__init__(self)
- self.multiplier = 2
-
- def arrayMethod(self, values):
- return self.multiplier * sum(values)
-
-class InjectCodeTest(unittest.TestCase):
-
- def testTypeNativeBeginning_TypeTargetBeginning(self):
- ic = InjectCode()
- self.assertEqual(str(ic), "Hi! I'm the inject code dummy class.")
-
- def testFunctionTargetBeginning_FunctionTargetEnd(self):
- ic = InjectCode()
- ret = ic.simpleMethod1(2, 1)
- self.assertEqual(ret, "4end")
- ret = ic.simpleMethod1(4, 2)
- self.assertEqual(ret, "7end")
-
- def testFunctionTargetBeginning(self):
- ic = InjectCode()
- ret = ic.simpleMethod2()
- self.assertEqual(ret, "_end")
-
- def testArgsModification(self):
- ic = InjectCode()
- ret = ic.overloadedMethod(["1", "2", "3", "4"])
- self.assertEqual(ret, "1234")
- ret = ic.overloadedMethod(2, 0.5)
- self.assertEqual(ret, "2.5")
- ret = ic.overloadedMethod(6, True)
- self.assertEqual(ret, "6true")
-
- def testArgsModification2(self):
- ic = InjectCode()
- ret = ic.simpleMethod3(["1", "2", "3", "4"])
- self.assertEqual(ret, "1234")
-
- def testArgumentRemovalAndArgumentTypeModification(self):
- '''A method has its first argument removed and the second modified.'''
- ic = InjectCode()
- values = (1, 2, 3, 4, 5)
- result = ic.arrayMethod(values)
- self.assertEqual(result, sum(values))
-
- def testCallVirtualMethodWithArgumentRemovalAndArgumentTypeModification(self):
- '''A virtual method has its first argument removed and the second modified.'''
- ic = InjectCode()
- values = (1, 2, 3, 4, 5)
- result = ic.callArrayMethod(values)
- self.assertEqual(result, sum(values))
-
- def testCallReimplementedVirtualMethodWithArgumentRemovalAndArgumentTypeModification(self):
- '''Calls a reimplemented virtual method that had its first argument removed and the second modified.'''
- ic = MyInjectCode()
- values = (1, 2, 3, 4, 5)
- result = ic.callArrayMethod(values)
- self.assertEqual(result, ic.multiplier * sum(values))
-
- def testUsageOfTypeSystemCheckVariableOnPrimitiveType(self):
- '''When the sequence item is convertible to an integer -1 is returned, or -2 if its not convertible.'''
- ic = InjectCode()
- values = (1, 2, 3, 4, '5', 6.7)
- result = ic.arrayMethod(values)
-
- fixedValues = [v for v in values if isinstance(v, int)]\
- + [-1 for v in values if isinstance(v, float)]\
- + [-2 for v in values if not isinstance(v, int) and not isinstance(v, float)]
- self.assertEqual(result, sum(fixedValues))
-
-
-class IntArrayTest(unittest.TestCase):
- '''Test case for converting python sequence to int array'''
-
- def testBasic(self):
- '''Shiboken::sequenceToIntArray - basic case'''
- args = [1, 2, 3, 4]
- ic = InjectCode()
- self.assertEqual(sum(args) + len(args), ic.sumArrayAndLength(args))
-
- def testEmpty(self):
- '''Shiboken::sequenceToIntArray - empty sequence'''
- args = []
- ic = InjectCode()
- self.assertEqual(sum(args) + len(args), ic.sumArrayAndLength(args))
-
- def testWithZero(self):
- '''Shiboken::sequenceToIntArray - count only up to zero'''
- args = [1, 2, 0, 3]
- ic = InjectCode()
- self.assertEqual(sum([1, 2]) + len([1, 2]), ic.sumArrayAndLength(args))
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/innerclass_test.py b/sources/shiboken2/tests/samplebinding/innerclass_test.py
deleted file mode 100644
index 287726587..000000000
--- a/sources/shiboken2/tests/samplebinding/innerclass_test.py
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Derived
-
-class TestInnerClass(unittest.TestCase):
- def testInstaciate(self):
- d = Derived.SomeInnerClass()
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/intlist_test.py b/sources/shiboken2/tests/samplebinding/intlist_test.py
deleted file mode 100644
index 19043b99c..000000000
--- a/sources/shiboken2/tests/samplebinding/intlist_test.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import IntList
-
-class IntListTest(unittest.TestCase):
-
- def testAutoFunctionsToBaseList(self):
- lst = IntList()
- self.assertEqual(len(lst), 0)
- lst.append(10)
- self.assertEqual(lst[0], 10)
- lst.append(20)
- self.assertEqual(lst[1], 20)
- lst.append(30)
- self.assertEqual(lst[2], 30)
- lst[1] = 25
- self.assertEqual(lst[0], 10)
- self.assertEqual(lst[1], 25)
- self.assertEqual(lst[2], 30)
- self.assertEqual(len(lst), 3)
-
- def testIntListCtor_NoParams(self):
- '''IntList constructor receives no parameter.'''
- il = IntList()
- self.assertEqual(len(il), 0)
- self.assertEqual(il.constructorUsed(), IntList.NoParamsCtor)
-
- def testIntListCtor_int(self):
- '''IntList constructor receives an integer.'''
- value = 123
- il = IntList(value)
- self.assertEqual(len(il), 1)
- self.assertEqual(il[0], value)
- self.assertEqual(il.constructorUsed(), IntList.IntCtor)
-
- def testIntListCtor_IntList(self):
- '''IntList constructor receives an IntList object.'''
- il1 = IntList(123)
- il2 = IntList(il1)
- self.assertEqual(len(il1), len(il2))
- for i in range(len(il1)):
- self.assertEqual(il1[i], il2[i])
- self.assertEqual(il2.constructorUsed(), IntList.CopyCtor)
-
- def testIntListCtor_ListOfInts(self):
- '''IntList constructor receives an integer list.'''
- ints = [123, 456]
- il = IntList(ints)
- self.assertEqual(len(il), len(ints))
- for i in range(len(il)):
- self.assertEqual(il[i], ints[i])
- self.assertEqual(il.constructorUsed(), IntList.ListOfIntCtor)
-
- def testIntListAttributeTypeCheck(self):
- '''Attribute values to IntList.'''
- il = IntList([0, 1, 2])
- self.assertEqual(len(il), 3)
- il[0] = 123
- self.assertEqual(len(il), 3)
- self.assertEqual(il[0], 123)
- il[1] = 432.1
- self.assertEqual(len(il), 3)
- self.assertEqual(il[1], int(432.1))
- self.assertRaises(TypeError, il.__setitem__, 2, '78')
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/invalid_virtual_return_test.py b/sources/shiboken2/tests/samplebinding/invalid_virtual_return_test.py
deleted file mode 100644
index 36e583a4f..000000000
--- a/sources/shiboken2/tests/samplebinding/invalid_virtual_return_test.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for returning invalid types in a virtual function'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import ObjectModel, ObjectType, ObjectView
-
-import warnings
-
-
-class MyObject(ObjectType):
- pass
-
-
-class ListModelWrong(ObjectModel):
-
- def __init__(self, parent=None):
- ObjectModel.__init__(self, parent)
- self.obj = 0
-
- def data(self):
- warnings.simplefilter('error')
- # Shouldn't segfault. Must set TypeError
- return self.obj
-
-
-class ModelWrongReturnTest(unittest.TestCase):
-
- def testWrongTypeReturn(self):
- model = ListModelWrong()
- view = ObjectView(model)
- self.assertRaises(RuntimeWarning, view.getRawModelData) # calls model.data()
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/keep_reference_test.py b/sources/shiboken2/tests/samplebinding/keep_reference_test.py
deleted file mode 100644
index db3ddc2d4..000000000
--- a/sources/shiboken2/tests/samplebinding/keep_reference_test.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for objects that keep references to other object without owning them (e.g. model/view relationships).'''
-
-import os
-import sys
-from sys import getrefcount
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectModel, ObjectView
-
-class TestKeepReference(unittest.TestCase):
- '''Test case for objects that keep references to other object without owning them (e.g. model/view relationships).'''
-
- def testReferenceCounting(self):
- '''Tests reference count of model-like object referred by view-like objects.'''
- model1 = ObjectModel()
- refcount1 = getrefcount(model1)
- view1 = ObjectView()
- view1.setModel(model1)
- self.assertEqual(getrefcount(view1.model()), refcount1 + 1)
-
- view2 = ObjectView()
- view2.setModel(model1)
- self.assertEqual(getrefcount(view2.model()), refcount1 + 2)
-
- model2 = ObjectModel()
- view2.setModel(model2)
- self.assertEqual(getrefcount(view1.model()), refcount1 + 1)
-
- def testReferenceCountingWhenDeletingReferrer(self):
- '''Tests reference count of model-like object referred by deceased view-like object.'''
- model = ObjectModel()
- refcount1 = getrefcount(model)
- view = ObjectView()
- view.setModel(model)
- self.assertEqual(getrefcount(view.model()), refcount1 + 1)
-
- del view
- self.assertEqual(getrefcount(model), refcount1)
-
- def testReferreedObjectSurvivalAfterContextEnd(self):
- '''Model-like object assigned to a view-like object must survive after get out of context.'''
- def createModelAndSetToView(view):
- model = ObjectModel()
- model.setObjectName('created model')
- view.setModel(model)
- view = ObjectView()
- createModelAndSetToView(view)
- model = view.model()
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/list_test.py b/sources/shiboken2/tests/samplebinding/list_test.py
deleted file mode 100644
index 74091422c..000000000
--- a/sources/shiboken2/tests/samplebinding/list_test.py
+++ /dev/null
@@ -1,127 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for std::list container conversions'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ListUser, Point, PointF
-
-class ExtendedListUser(ListUser):
- def __init__(self):
- ListUser.__init__(self)
- self.create_list_called = False
-
- def createList(self):
- self.create_list_called = True
- return [2, 3, 5, 7, 13]
-
-class ListConversionTest(unittest.TestCase):
- '''Test case for std::list container conversions'''
-
- def testReimplementedVirtualMethodCall(self):
- '''Test if a Python override of a virtual method is correctly called from C++.'''
- lu = ExtendedListUser()
- lst = lu.callCreateList()
- self.assertTrue(lu.create_list_called)
- self.assertEqual(type(lst), list)
- for item in lst:
- self.assertEqual(type(item), int)
-
- def testPrimitiveConversionInsideContainer(self):
- '''Test primitive type conversion inside conversible std::list container.'''
- cpx0 = complex(1.2, 3.4)
- cpx1 = complex(5.6, 7.8)
- lst = ListUser.createComplexList(cpx0, cpx1)
- self.assertEqual(type(lst), list)
- for item in lst:
- self.assertEqual(type(item), complex)
- self.assertEqual(lst, [cpx0, cpx1])
-
- def testSumListIntegers(self):
- '''Test method that sums a list of integer values.'''
- lu = ListUser()
- lst = [3, 5, 7]
- result = lu.sumList(lst)
- self.assertEqual(result, sum(lst))
-
- def testSumListFloats(self):
- '''Test method that sums a list of float values.'''
- lu = ListUser()
- lst = [3.3, 4.4, 5.5]
- result = lu.sumList(lst)
- self.assertEqual(result, sum(lst))
-
- def testConversionInBothDirections(self):
- '''Test converting a list from Python to C++ and back again.'''
- lu = ListUser()
- lst = [3, 5, 7]
- lu.setList(lst)
- result = lu.getList()
- self.assertEqual(result, lst)
-
- def testConversionInBothDirectionsWithSimilarContainer(self):
- '''Test converting a tuple, instead of the expected list, from Python to C++ and back again.'''
- lu = ListUser()
- lst = (3, 5, 7)
- lu.setList(lst)
- result = lu.getList()
- self.assertNotEqual(result, lst)
- self.assertEqual(result, list(lst))
-
- def testConversionOfListOfObjectsPassedAsArgument(self):
- '''Calls method with a Python list of wrapped objects to be converted to a C++ list.'''
- mult = 3
- pts0 = (Point(1.0, 2.0), Point(3.3, 4.4), Point(5, 6))
- pts1 = (Point(1.0, 2.0), Point(3.3, 4.4), Point(5, 6))
- ListUser.multiplyPointList(pts1, mult)
- for pt0, pt1 in zip(pts0, pts1):
- self.assertEqual(pt0.x() * mult, pt1.x())
- self.assertEqual(pt0.y() * mult, pt1.y())
-
- def testConversionOfInvalidLists(self):
- mult = 3
- pts = (Point(1.0, 2.0), 3, Point(5, 6))
- self.assertRaises(TypeError, ListUser.multiplyPointList, pts, mult)
-
- def testOverloadMethodReceivingRelatedContainerTypes(self):
- self.assertEqual(ListUser.ListOfPointF, ListUser.listOfPoints([PointF()]))
- self.assertEqual(ListUser.ListOfPoint, ListUser.listOfPoints([Point()]))
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/lock_test.py b/sources/shiboken2/tests/samplebinding/lock_test.py
deleted file mode 100644
index 93c632e34..000000000
--- a/sources/shiboken2/tests/samplebinding/lock_test.py
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/env python
-
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Simple test with a blocking C++ method that should allow python
- threads to run.'''
-
-import os
-import sys
-import threading
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Bucket
-
-
-class Unlocker(threading.Thread):
-
- def __init__(self, bucket):
- threading.Thread.__init__(self)
- self.bucket = bucket
-
- def run(self):
- while not self.bucket.locked():
- pass
-
- self.bucket.unlock()
-
-
-class MyBucket(Bucket):
-
- def __init__(self):
- Bucket.__init__(self)
-
- def virtualBlockerMethod(self):
- self.lock()
- return True
-
-
-class TestLockUnlock(unittest.TestCase):
-
- def testBasic(self):
- '''Locking in C++ and releasing in a python thread'''
- bucket = Bucket()
- unlocker = Unlocker(bucket)
-
- unlocker.start()
- bucket.lock()
- unlocker.join()
-
- def testVirtualBlocker(self):
- '''Same as the basic case but blocker method is a C++ virtual called from C++.'''
- bucket = Bucket()
- unlocker = Unlocker(bucket)
-
- unlocker.start()
- result = bucket.callVirtualBlockerMethodButYouDontKnowThis()
- unlocker.join()
- self.assertTrue(result)
-
- def testReimplementedVirtualBlocker(self):
- '''Same as the basic case but blocker method is a C++ virtual reimplemented in Python and called from C++.'''
- mybucket = MyBucket()
- unlocker = Unlocker(mybucket)
-
- unlocker.start()
- result = mybucket.callVirtualBlockerMethodButYouDontKnowThis()
- unlocker.join()
- self.assertTrue(result)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/map_test.py b/sources/shiboken2/tests/samplebinding/map_test.py
deleted file mode 100644
index f6696c3d8..000000000
--- a/sources/shiboken2/tests/samplebinding/map_test.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for std::map container conversions'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import MapUser
-
-class ExtendedMapUser(MapUser):
- def __init__(self):
- MapUser.__init__(self)
- self.create_map_called = False
-
- def createMap(self):
- self.create_map_called = True
- return {'two' : (complex(2.2, 2.2), 2),
- 'three' : (complex(3.3, 3.3), 3),
- 'five' : (complex(5.5, 5.5), 5),
- 'seven' : (complex(7.7, 7.7), 7)}
-
-class MapConversionTest(unittest.TestCase):
- '''Test case for std::map container conversions'''
-
- def testReimplementedVirtualMethodCall(self):
- '''Test if a Python override of a virtual method is correctly called from C++.'''
- mu = ExtendedMapUser()
- map_ = mu.callCreateMap()
- self.assertTrue(mu.create_map_called)
- self.assertEqual(type(map_), dict)
- for key, value in map_.items():
- self.assertEqual(type(key), str)
- self.assertEqual(type(value[0]), complex)
- self.assertEqual(type(value[1]), int)
-
- def testConversionInBothDirections(self):
- '''Test converting a map from Python to C++ and back again.'''
- mu = MapUser()
- map_ = {'odds' : [2, 4, 6], 'evens' : [3, 5, 7], 'primes' : [3, 4, 6]}
- mu.setMap(map_)
- result = mu.getMap()
- self.assertEqual(result, map_)
-
- def testConversionMapIntKeyValueTypeValue(self):
- '''C++ signature: MapUser::passMapIntValueType(const std::map<int, const ByteArray>&)'''
- mu = MapUser()
- map_ = {0 : 'string'}
- result = mu.passMapIntValueType(map_)
- self.assertEqual(map_, result)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/metaclass_test.py b/sources/shiboken2/tests/samplebinding/metaclass_test.py
deleted file mode 100644
index ad4c08f0d..000000000
--- a/sources/shiboken2/tests/samplebinding/metaclass_test.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class MetaA(type):
- pass
-
-class A(object):
- __metaclass__ = MetaA
-
-MetaB = type(Point)
-B = Point
-
-class MetaC(MetaA, MetaB):
- pass
-class C(A, B):
- __metaclass__ = MetaC
-
-class D(C):
- pass
-
-class TestMetaClass(unittest.TestCase):
- def testIt(self):
- w1 = C() # works
- w1.setX(1)
- w1.setY(2)
-
- w2 = D() # should work!
- w2.setX(3)
- w2.setY(4)
-
- w3 = w1 + w2
- self.assertEqual(w3.x(), 4)
- self.assertEqual(w3.y(), 6)
diff --git a/sources/shiboken2/tests/samplebinding/mi_virtual_methods_test.py b/sources/shiboken2/tests/samplebinding/mi_virtual_methods_test.py
deleted file mode 100644
index aea8a4d46..000000000
--- a/sources/shiboken2/tests/samplebinding/mi_virtual_methods_test.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for virtual methods in multiple inheritance scenarios'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import VirtualMethods, ObjectType, Event
-
-
-class ImplementsNone(ObjectType, VirtualMethods):
- '''Implements no virtual methods'''
-
- def __init__(self):
- ObjectType.__init__(self)
- VirtualMethods.__init__(self)
-
-
-class ImplementsBoth(ObjectType, VirtualMethods):
- '''Implements ObjectType.event and VirtualMethods.sum1'''
-
- def __init__(self):
- ObjectType.__init__(self)
- VirtualMethods.__init__(self)
- self.event_processed = False
-
- def event(self, event):
- self.event_processed = True
- return True
-
- def sum1(self, arg0, arg1, arg2):
- return (arg0 + arg1 + arg2) * 2
-
-
-class CppVirtualTest(unittest.TestCase):
- '''Virtual method defined in c++ called from C++'''
-
- def testCpp(self):
- '''C++ calling C++ virtual method in multiple inheritance scenario'''
- obj = ImplementsNone()
- self.assertTrue(ObjectType.processEvent([obj], Event(Event.BASIC_EVENT)))
- self.assertRaises(AttributeError, getattr, obj, 'event_processed')
-
- self.assertEqual(obj.callSum0(1, 2, 3), 6)
-
-
-class PyVirtualTest(unittest.TestCase):
- '''Virtual method reimplemented in python called from C++'''
-
- def testEvent(self):
- '''C++ calling Python reimplementation of virtual in multiple inheritance'''
- obj = ImplementsBoth()
- self.assertTrue(ObjectType.processEvent([obj], Event(Event.BASIC_EVENT)))
- self.assertTrue(obj.event_processed)
-
- self.assertEqual(obj.callSum1(1, 2, 3), 12)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/mixed_mi_test.py b/sources/shiboken2/tests/samplebinding/mixed_mi_test.py
deleted file mode 100644
index d33d033ba..000000000
--- a/sources/shiboken2/tests/samplebinding/mixed_mi_test.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for multiple inheritance in mixed Python/C++ scenarios'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType
-
-
-class Base(object):
- '''Base Python class'''
-
- def __init__(self):
- self.name = ''
-
- def pythonName(self):
- return self.name
-
- def setPythonName(self, name):
- self.name = name
-
-
-class Child(Base, ObjectType):
- '''Dummy class with mixed parents'''
-
- def __init__(self):
- Base.__init__(self)
- ObjectType.__init__(self)
-
-
-class MixedInheritanceTest(unittest.TestCase):
-
- def testMixed(self):
- '''Mixed Python/C++ multiple inheritance'''
- obj = Child()
-
- obj.setObjectName('aaa')
- self.assertEqual(obj.objectName(), 'aaa')
-
- obj.setPythonName('python')
- self.assertEqual(obj.pythonName(), 'python')
-
-
-if __name__ == '__main__':
- unittest.main()
-
-
diff --git a/sources/shiboken2/tests/samplebinding/modelindex_test.py b/sources/shiboken2/tests/samplebinding/modelindex_test.py
deleted file mode 100644
index 905d14269..000000000
--- a/sources/shiboken2/tests/samplebinding/modelindex_test.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ModelIndex, ReferentModelIndex, PersistentModelIndex
-
-class TestCastOperator(unittest.TestCase):
-
- def testCastOperatorReturningValue(self):
- index = PersistentModelIndex()
- index.setValue(123)
- self.assertEqual(index.value(), 123)
- self.assertEqual(index.value(), ModelIndex.getValue(index))
-
- def testCastOperatorReturningReference(self):
- index = ReferentModelIndex()
- index.setValue(123)
- self.assertEqual(index.value(), 123)
- self.assertEqual(index.value(), ModelIndex.getValue(index))
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/modelview_test.py b/sources/shiboken2/tests/samplebinding/modelview_test.py
deleted file mode 100644
index f421ca41d..000000000
--- a/sources/shiboken2/tests/samplebinding/modelview_test.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for objects that keep references to other object without owning them (e.g. model/view relationships).'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import ObjectModel, ObjectType, ObjectView
-
-
-object_name = 'test object'
-
-class MyObject(ObjectType):
- pass
-
-class ListModelKeepsReference(ObjectModel):
- def __init__(self, parent=None):
- ObjectModel.__init__(self, parent)
- self.obj = MyObject()
- self.obj.setObjectName(object_name)
-
- def data(self):
- return self.obj
-
-class ListModelDoesntKeepsReference(ObjectModel):
- def data(self):
- obj = MyObject()
- obj.setObjectName(object_name)
- return obj
-
-
-class ModelViewTest(unittest.TestCase):
-
- def testListModelDoesntKeepsReference(self):
- model = ListModelDoesntKeepsReference()
- view = ObjectView(model)
- obj = view.getRawModelData()
- self.assertEqual(type(obj), MyObject)
- self.assertEqual(obj.objectName(), object_name)
-
- def testListModelKeepsReference(self):
- model = ListModelKeepsReference()
- view = ObjectView(model)
- obj = view.getRawModelData()
- self.assertEqual(type(obj), MyObject)
- self.assertEqual(obj.objectName(), object_name)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/modifications_test.py b/sources/shiboken2/tests/samplebinding/modifications_test.py
deleted file mode 100644
index 763ba04e5..000000000
--- a/sources/shiboken2/tests/samplebinding/modifications_test.py
+++ /dev/null
@@ -1,248 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for method modifications performed as described on type system. '''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Modifications, Point, ByteArray
-
-class ExtModifications(Modifications):
- def __init__(self):
- Modifications.__init__(self)
- self.multiplier = 3.0
- self.increment = 10.0
-
- def name(self):
- return 'ExtModifications'
-
- def differenceOfPointCoordinates(self, point):
- ok, res = Modifications.differenceOfPointCoordinates(self, point)
- return ok, res * self.multiplier + self.increment
-
-
-class ModificationsTest(unittest.TestCase):
- '''Test cases for method modifications performed as described on type system. '''
-
- def setUp(self):
- self.mods = Modifications()
-
- def tearDown(self):
- del self.mods
-
- def testClassMembersAvailability(self):
- '''Test if Modified class really have the expected members.'''
- expected_members = set(['OverloadedModFunc', 'OverloadedNone',
- 'Overloaded_ibiP', 'Overloaded_ibib',
- 'Overloaded_ibid', 'Overloaded_ibii',
- 'calculateArea', 'doublePlus', 'increment',
- 'multiplyPointCoordsPlusValue', 'name',
- 'pointToPair', 'overloaded', 'power',
- 'timesTen'])
- self.assertTrue(expected_members.issubset(dir(Modifications)))
-
- def testRenamedMethodAvailability(self):
- '''Test if Modification class really have renamed the 'className' virtual method to 'name'.'''
- self.assertTrue('className' not in dir(Modifications))
- self.assertTrue('name' in dir(Modifications))
-
- def testReimplementationOfRenamedVirtualMethod(self):
- '''Test if class inheriting from Modification class have the reimplementation of renamed virtual method called.'''
- em = ExtModifications()
- self.assertEqual(self.mods.name(), 'Modifications')
- self.assertEqual(em.name(), 'ExtModifications')
-
- def testRegularMethodRenaming(self):
- '''Test if Modifications::cppMultiply was correctly renamed to calculateArea.'''
- self.assertTrue('cppMultiply' not in dir(Modifications))
- self.assertTrue('calculateArea' in dir(Modifications))
- self.assertEqual(self.mods.calculateArea(3, 6), 3 * 6)
-
- def testRegularMethodRemoval(self):
- '''Test if 'Modifications::exclusiveCppStuff' was removed from Python bindings.'''
- self.assertTrue('exclusiveCppStuff' not in dir(Modifications))
-
- def testArgumentRemoval(self):
- '''Test if second argument of Modifications::doublePlus(int, int) was removed.'''
- self.assertRaises(TypeError, self.mods.doublePlus, 3, 7)
- self.assertEqual(self.mods.doublePlus(7), 14)
-
- def testDefaultValueRemoval(self):
- '''Test if default value was removed from first argument of Modifications::increment(int).'''
- self.assertRaises(TypeError, self.mods.increment)
- self.assertEqual(self.mods.increment(7), 8)
-
- def testDefaultValueReplacement(self):
- '''Test if default values for both arguments of Modifications::power(int, int) were modified.'''
- # original default values: int power(int base = 1, int exponent = 0);
- self.assertNotEqual(self.mods.power(4), 1)
- # modified default values: int power(int base = 2, int exponent = 1);
- self.assertEqual(self.mods.power(), 2)
- self.assertEqual(self.mods.power(3), 3)
- self.assertEqual(self.mods.power(5, 3), 5**3)
-
- def testSetNewDefaultValue(self):
- '''Test if default value was correctly set to 10 for first argument of Modifications::timesTen(int).'''
- self.assertEqual(self.mods.timesTen(7), 70)
- self.assertEqual(self.mods.timesTen(), 100)
-
- def testArgumentRemovalAndReturnTypeModificationWithTypesystemTemplates1(self):
- '''Test modifications to method signature and return value using type system templates (case 1).'''
- result, ok = self.mods.pointToPair(Point(2, 5))
- self.assertEqual(type(ok), bool)
- self.assertEqual(type(result), tuple)
- self.assertEqual(len(result), 2)
- self.assertEqual(type(result[0]), float)
- self.assertEqual(type(result[1]), float)
- self.assertEqual(result[0], 2.0)
- self.assertEqual(result[1], 5.0)
-
- def testArgumentRemovalAndReturnTypeModificationWithTypesystemTemplates2(self):
- '''Test modifications to method signature and return value using type system templates (case 2).'''
- result, ok = self.mods.multiplyPointCoordsPlusValue(Point(2, 5), 4.1)
- self.assertEqual(type(ok), bool)
- self.assertEqual(type(result), float)
- self.assertEqual(result, 14.1)
-
- def testOverloadedMethodModifications(self):
- '''Tests modifications to an overloaded method'''
- # overloaded(int, bool[removed], int, double)
- self.assertEqual(self.mods.overloaded(1, 2, 3.1), Modifications.Overloaded_ibid)
- # overloaded(int, bool, int[removed,default=321], int)
- self.assertEqual(self.mods.overloaded(1, True, 2), Modifications.Overloaded_ibii)
- # the others weren't modified
- self.assertEqual(self.mods.overloaded(1, True, 2, False), Modifications.Overloaded_ibib)
- self.assertEqual(self.mods.overloaded(1, False, 2, Point(3, 4)), Modifications.Overloaded_ibiP)
- self.assertRaises(TypeError, self.mods.overloaded, 1, True, Point(2, 3), Point(4, 5))
- self.assertEqual(self.mods.over(1, True, Point(2, 3), Point(4, 5)), Modifications.Overloaded_ibPP)
-
- def testPointArrayModification(self):
- points = (Point(1, 1), Point(2, 2))
- summedPoint = Point(1, 1) + Point(2, 2)
- self.assertEqual(self.mods.sumPointArray(points), summedPoint)
-
- def testTypeSystemVariableReplacementInFunctionModification(self):
- ba = ByteArray('12345')
- self.assertEqual(self.mods.getSize(ba), len(ba))
- self.assertEqual(self.mods.getSize(ba, 20), 20)
-
- def testNoNulPointerTag(self):
- point = Point(12, 34)
- self.assertEqual(self.mods.sumPointCoordinates(point), 12 + 34)
- self.assertRaises(TypeError, self.mods.sumPointCoordinates, None)
-
- def testNonConversionRuleForArgumentWithDefaultValue(self):
- status, obj = self.mods.nonConversionRuleForArgumentWithDefaultValue()
- self.assertTrue(status)
- self.assertEqual(obj, self.mods.getObject())
- self.assertEqual(obj.objectName(), 'MyObject')
-
- def testInjectCodeWithConversionVariableForUserPrimitive(self):
- self.assertTrue(Modifications.invertBoolean(False))
- self.assertFalse(Modifications.invertBoolean(True))
-
- def testConversionRuleForReturnType(self):
- x, y = 11, 2
- diff = float(abs(x - y))
- point = Point(x, y)
-
- ok, res = self.mods.differenceOfPointCoordinates(point)
- self.assertTrue(isinstance(ok, bool))
- self.assertTrue(isinstance(res, float))
- self.assertEqual(res, diff)
-
- ok, res = self.mods.callDifferenceOfPointCoordinates(point)
- self.assertTrue(isinstance(ok, bool))
- self.assertTrue(isinstance(res, float))
- self.assertEqual(res, diff)
-
- ok, res = self.mods.differenceOfPointCoordinates(None)
- self.assertTrue(isinstance(ok, bool))
- self.assertTrue(isinstance(res, float))
- self.assertEqual(res, 0.0)
-
- ok, res = self.mods.callDifferenceOfPointCoordinates(None)
- self.assertTrue(isinstance(ok, bool))
- self.assertTrue(isinstance(res, float))
- self.assertEqual(res, 0.0)
-
- def testConversionRuleForReturnTypeOnExtendedClass(self):
- x, y = 11, 2
- diff = float(abs(x - y))
- point = Point(x, y)
- em = ExtModifications()
-
- ok, res = em.differenceOfPointCoordinates(point)
- self.assertTrue(isinstance(ok, bool))
- self.assertTrue(isinstance(res, float))
- self.assertEqual(res, diff * em.multiplier + em.increment)
-
- ok, res = em.callDifferenceOfPointCoordinates(point)
- self.assertTrue(isinstance(ok, bool))
- self.assertTrue(isinstance(res, float))
- self.assertEqual(res, diff * em.multiplier + em.increment)
-
- ok, res = em.differenceOfPointCoordinates(None)
- self.assertTrue(isinstance(ok, bool))
- self.assertTrue(isinstance(res, float))
- self.assertEqual(res, em.increment)
-
- ok, res = em.callDifferenceOfPointCoordinates(None)
- self.assertTrue(isinstance(ok, bool))
- self.assertTrue(isinstance(res, float))
- self.assertEqual(res, em.increment)
-
- def testDefaultValueModifications(self):
- # PSYIDE-1095: setEnumValue() has the default value modified to
- # calling defaultEnumValue() which returns Modifications.TestEnumValue2.
- # This used to generated broken code since defaultEnumValue() was
- # qualified by the enum scope.
- modifications = Modifications()
- modifications.setEnumValue()
- self.assertEqual(modifications.enumValue(), Modifications.TestEnumValue2)
-
- def testSetGetAttro(self):
- modifications = Modifications()
- self.assertFalse(modifications.wasSetAttroCalled())
- setattr(modifications, 'Foo', 'Bar')
- self.assertTrue(modifications.wasSetAttroCalled())
- self.assertEqual(getattr(modifications, 'Foo'), 'Bar')
- self.assertTrue(modifications.wasGetAttroCalled())
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/modified_constructor_test.py b/sources/shiboken2/tests/samplebinding/modified_constructor_test.py
deleted file mode 100644
index 11d931c5f..000000000
--- a/sources/shiboken2/tests/samplebinding/modified_constructor_test.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests cases for ConstructorWithModifiedArgument class.'''
-
-import sys
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-
-class ConstructorWithModifiedArgumentTest(unittest.TestCase):
- '''Test cases for ConstructorWithModifiedArgument class.'''
-
- def testConstructorWithModifiedArgument(self):
- sampleClass = ModifiedConstructor("10")
- self.assertTrue(sampleClass.retrieveValue(), 10)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/modifiedvirtualmethods_test.py b/sources/shiboken2/tests/samplebinding/modifiedvirtualmethods_test.py
deleted file mode 100644
index c15a0db08..000000000
--- a/sources/shiboken2/tests/samplebinding/modifiedvirtualmethods_test.py
+++ /dev/null
@@ -1,254 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for modified virtual methods.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import VirtualMethods, Str
-
-class ExtendedVirtualMethods(VirtualMethods):
- def __init__(self):
- VirtualMethods.__init__(self)
- self.name_called = False
- self.sum0_called = False
- self.sum1_called = False
- self.sum2_called = False
- self.sum3_called = False
- self.sum4_called = False
- self.sumThree_called = False
- self.callMe_called = 0
- self.multiplier = 12345
-
- def sum0(self, a0, a1, a2):
- self.sum0_called = True
- return VirtualMethods.sumThree(self, a0, a1, a2) * self.multiplier
-
- def sumThree(self, a0, a1, a2):
- self.sumThree_called = True
- return VirtualMethods.sumThree(self, a0, a1, a2) * self.multiplier
-
- def sum1(self, a0, a1, a2):
- self.sum1_called = True
- return VirtualMethods.sum1(self, a0, a1, a2) * self.multiplier
-
- def sum2(self, a0, a1):
- self.sum2_called = True
- return VirtualMethods.sum2(self, a0, a1) * self.multiplier
-
- def sum3(self, a0, a1):
- self.sum3_called = True
- return VirtualMethods.sum3(self, a0, a1) * self.multiplier
-
- def sum4(self, a0, a1):
- self.sum4_called = True
- return VirtualMethods.sum4(self, a0, a1) * self.multiplier
-
- def name(self):
- self.name_called = True
- return Str('ExtendedVirtualMethods')
-
- def callMe(self):
- self.callMe_called += 1
-
- def getMargins(self):
- return tuple([m*2 for m in VirtualMethods.getMargins(self)])
-
-
-class VirtualMethodsTest(unittest.TestCase):
- '''Test case for modified virtual methods.'''
-
- def setUp(self):
- self.vm = VirtualMethods()
- self.evm = ExtendedVirtualMethods()
-
- def tearDown(self):
- del self.vm
- del self.evm
-
- def testModifiedVirtualMethod0(self):
- '''Renamed virtual method.'''
- a0, a1, a2 = 2, 3, 5
- result0 = self.vm.callSum0(a0, a1, a2)
- result1 = self.vm.sumThree(a0, a1, a2)
- self.assertEqual(result0, a0 + a1 + a2)
- self.assertEqual(result0, result1)
- self.assertRaises(AttributeError, getattr, self.vm, 'sum0')
-
- def testReimplementedModifiedVirtualMethod0(self):
- '''Override of a renamed virtual method.'''
- a0, a1, a2 = 2, 3, 5
- result0 = self.vm.callSum0(a0, a1, a2)
- result1 = self.vm.sumThree(a0, a1, a2)
- result2 = self.evm.callSum0(a0, a1, a2)
- self.assertEqual(result0, result1)
- self.assertEqual(result0 * self.evm.multiplier, result2)
- self.assertTrue(self.evm.sumThree_called)
- self.assertFalse(self.evm.sum0_called)
-
- def testModifiedVirtualMethod1(self):
- '''Virtual method with three arguments and the last one
- changed to have the default value set to 1000.'''
- a0, a1, a2 = 2, 3, 5
- result0 = self.vm.sum1(a0, a1)
- self.assertEqual(result0, a0 + a1 + 1000)
- result1 = self.vm.sum1(a0, a1, a2)
- result2 = self.vm.callSum1(a0, a1, a2)
- self.assertEqual(result1, result2)
-
- def testReimplementedModifiedVirtualMethod1(self):
- '''Override of the virtual method with three arguments and
- the last one changed to have the default value set to 1000.'''
- a0, a1 = 2, 3
- result0 = self.vm.sum1(a0, a1)
- result1 = self.evm.callSum1(a0, a1, 1000)
- self.assertEqual(result0 * self.evm.multiplier, result1)
- self.assertTrue(self.evm.sum1_called)
-
- def testModifiedVirtualMethod2(self):
- '''Virtual method originally with three arguments, the last
- one was removed and the default value set to 2000.'''
- a0, a1 = 1, 2
- result0 = self.vm.sum2(a0, a1)
- self.assertEqual(result0, a0 + a1 + 2000)
- result1 = self.vm.sum2(a0, a1)
- result2 = self.vm.callSum2(a0, a1, 2000)
- self.assertEqual(result1, result2)
- self.assertRaises(TypeError, self.vm.sum2, 1, 2, 3)
-
- def testReimplementedModifiedVirtualMethod2(self):
- '''Override of the virtual method originally with three arguments,
- the last one was removed and the default value set to 2000.'''
- a0, a1 = 1, 2
- ignored = 54321
- result0 = self.vm.sum2(a0, a1)
- result1 = self.evm.callSum2(a0, a1, ignored)
- self.assertEqual(result0 * self.evm.multiplier, result1)
- self.assertTrue(self.evm.sum2_called)
-
- def testModifiedVirtualMethod3(self):
- '''Virtual method originally with three arguments have the second
- one removed and replaced by custom code that replaces it by the sum
- of the first and the last arguments.'''
- a0, a1 = 1, 2
- result0 = self.vm.sum3(a0, a1)
- self.assertEqual(result0, a0 + (a0 + a1) + a1)
- result1 = self.vm.callSum3(a0, 10, a1)
- self.assertNotEqual(result0, result1)
- result2 = self.vm.callSum3(a0, a0 + a1, a1)
- self.assertEqual(result0, result2)
- self.assertRaises(TypeError, self.vm.sum3, 1, 2, 3)
-
- def testReimplementedModifiedVirtualMethod3(self):
- '''Override of the virtual method originally with three arguments
- have the second one removed and replaced by custom code that
- replaces it by the sum of the first and the last arguments.'''
- a0, a1 = 1, 2
- ignored = 54321
- result0 = self.vm.sum3(a0, a1)
- result1 = self.evm.callSum3(a0, ignored, a1)
- self.assertEqual(result0 * self.evm.multiplier, result1)
- self.assertTrue(self.evm.sum3_called)
-
- def testModifiedVirtualMethod4(self):
- '''Virtual method originally with three arguments, the
- last one was removed and the default value set to 3000.'''
- a0, a1 = 1, 2
- default_value = 3000
- result0 = self.vm.sum4(a0, a1)
- self.assertEqual(result0, a0 + default_value + a1)
- removed_arg_value = 100
- result1 = self.vm.callSum4(a0, removed_arg_value, a1)
- self.assertEqual(result1, a0 + removed_arg_value + a1)
- self.assertRaises(TypeError, self.vm.sum4, 1, 2, 3)
-
- def testReimplementedModifiedVirtualMethod4(self):
- '''Override of the virtual method originally with three arguments,
- the last one was removed and the default value set to 3000.
- The method was modified with code injection on the binding override
- (the one that receives calls from C++ with the original signature
- and forwards it to Python overrides) that subtracts the value of the
- second argument (removed in Python) from the value of the first
- before sending them to Python.'''
- a0, a1 = 1, 2
- removed_arg_value = 2011
- default_value = 3000
- result = self.evm.callSum4(a0, removed_arg_value, a1)
- self.assertEqual(result, (a0 - removed_arg_value + a1 + default_value) * self.evm.multiplier)
- self.assertTrue(self.evm.sum4_called)
-
- def testOverridenMethodResultModification(self):
- '''Injected code modifies the result of a call to a virtual
- method overridden in Python.'''
- orig_name = self.vm.callName()
- self.assertEqual(orig_name, 'VirtualMethods')
- name = self.evm.callName()
- self.assertEqual(name, 'PimpedExtendedVirtualMethods')
- self.assertEqual(name, Str('PimpedExtendedVirtualMethods'))
- self.assertTrue(self.evm.name_called)
-
- def testInjectCodeCallsPythonVirtualMethodOverride(self):
- '''When injected code calls the Python override by itself
- no code for the method call should be generated.'''
- self.evm.callCallMe()
- self.assertEqual(self.evm.callMe_called, 1)
-
- def testAllArgumentsRemoved(self):
- values = (10, 20, 30, 40)
- self.vm.setMargins(*values)
- self.assertEqual(self.vm.getMargins(), values)
-
- def testAllArgumentsRemovedCallVirtual(self):
- values = (10, 20, 30, 40)
- self.vm.setMargins(*values)
- self.assertEqual(self.vm.callGetMargins(), values)
-
- def testExtendedAllArgumentsRemoved(self):
- values = (10, 20, 30, 40)
- self.evm.setMargins(*values)
- double = tuple([m*2 for m in values])
- self.assertEqual(self.evm.getMargins(), double)
-
- def testExtendedAllArgumentsRemovedCallVirtual(self):
- values = (10, 20, 30, 40)
- self.evm.setMargins(*values)
- double = tuple([m*2 for m in values])
- self.assertEqual(self.evm.callGetMargins(), double)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/multi_cpp_inheritance_test.py b/sources/shiboken2/tests/samplebinding/multi_cpp_inheritance_test.py
deleted file mode 100644
index c64a29e8e..000000000
--- a/sources/shiboken2/tests/samplebinding/multi_cpp_inheritance_test.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for multiple inheritance'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class SimpleUseCase(ObjectType, Str):
- def __init__(self, name):
- ObjectType.__init__(self)
- Str.__init__(self, name)
-
-class SimpleUseCaseReverse(Str, ObjectType):
- def __init__(self, name):
- ObjectType.__init__(self)
- Str.__init__(self, name)
-
-class SimpleUseCase2(SimpleUseCase):
- def __init__(self, name):
- SimpleUseCase.__init__(self, name)
-
-class ComplexUseCase(SimpleUseCase2, Point):
- def __init__(self, name):
- SimpleUseCase2.__init__(self, name)
- Point.__init__(self)
-
-class ComplexUseCaseReverse(Point, SimpleUseCase2):
- def __init__(self, name):
- SimpleUseCase2.__init__(self, name)
- Point.__init__(self)
-
-class MultipleCppDerivedTest(unittest.TestCase):
- def testInstanciation(self):
- s = SimpleUseCase("Hi")
- self.assertEqual(s, "Hi")
- s.setObjectName(s)
- self.assertEqual(s.objectName(), "Hi")
-
- def testInstanciation2(self):
- s = SimpleUseCase2("Hi")
- self.assertEqual(s, "Hi")
- s.setObjectName(s)
- self.assertEqual(s.objectName(), "Hi")
-
- def testComplexInstanciation(self):
- c = ComplexUseCase("Hi")
- self.assertEqual(c, "Hi")
- c.setObjectName(c)
- self.assertEqual(c.objectName(), "Hi")
- c.setX(2);
- self.assertEqual(c.x(), 2)
-
-class MultipleCppDerivedReverseTest(unittest.TestCase):
- def testInstanciation(self):
- s = SimpleUseCaseReverse("Hi")
- self.assertEqual(s, "Hi")
- s.setObjectName(s)
- self.assertEqual(s.objectName(), "Hi")
-
- def testInstanciation2(self):
- s = SimpleUseCase2("Hi")
- self.assertEqual(s, "Hi")
- s.setObjectName(s)
- self.assertEqual(s.objectName(), "Hi")
-
- def testComplexInstanciation(self):
- c = ComplexUseCaseReverse("Hi")
- c.setObjectName(c)
- self.assertEqual(c.objectName(), "Hi")
- c.setX(2);
- self.assertEqual(c, Point(2, 0))
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/multiple_derived_test.py b/sources/shiboken2/tests/samplebinding/multiple_derived_test.py
deleted file mode 100644
index 650af8602..000000000
--- a/sources/shiboken2/tests/samplebinding/multiple_derived_test.py
+++ /dev/null
@@ -1,226 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for multiple inheritance'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Base1, Base2, Base3, Base4, Base5, Base6
-from sample import MDerived1, MDerived2, MDerived3, MDerived4, MDerived5, SonOfMDerived1
-
-class ExtMDerived1(MDerived1):
- def __init__(self):
- MDerived1.__init__(self)
- self.multiplier = 20
- self.base2Method_called = False
- def base2Method(self):
- return Base2.base2Method(self) * self.multiplier
-
-class MultipleDerivedTest(unittest.TestCase):
- '''Test cases for multiple inheritance'''
-
- def testIsInstance(self):
- '''MDerived1 is instance of its parents Base1 and Base2.'''
- a = MDerived1()
- self.assertTrue(isinstance(a, MDerived1))
- self.assertTrue(isinstance(a, Base1))
- self.assertTrue(isinstance(a, Base2))
-
- def testIsSubclass(self):
- '''MDerived1 is subclass of its parents Base1 and Base2.'''
- self.assertTrue(issubclass(MDerived1, Base1))
- self.assertTrue(issubclass(MDerived1, Base2))
-
- def testCallToFunctionWithBase1ArgumentThatCastsBackToMDerived1(self):
- '''MDerived1 is passed as an Base1 argument to a method that returns it casted back to MDerived1.'''
- a = MDerived1()
- b = MDerived1.transformFromBase1(a)
- self.assertEqual(a, b)
-
- def testCallToFunctionWithBase2ArgumentThatCastsBackToMDerived1(self):
- '''MDerived1 is passed as an Base2 argument to a method that returns it casted back to MDerived1.'''
- a = MDerived1()
- b = MDerived1.transformFromBase2(a)
- self.assertEqual(a, b)
-
- def testPythonClassIsInstance(self):
- '''Python defined class ExtMDerived1 is instance of its parents MDerived1, Base1 and Base2.'''
- a = ExtMDerived1()
- self.assertTrue(isinstance(a, ExtMDerived1))
- self.assertTrue(isinstance(a, MDerived1))
- self.assertTrue(isinstance(a, Base1))
- self.assertTrue(isinstance(a, Base2))
-
- def testPythonClassIsSubclass(self):
- '''Python defined class ExtMDerived1 is subclass of its parents MDerived1, Base1 and Base2.'''
- self.assertTrue(issubclass(ExtMDerived1, MDerived1))
- self.assertTrue(issubclass(ExtMDerived1, Base1))
- self.assertTrue(issubclass(ExtMDerived1, Base2))
-
- def testCastFromMDerived1ToBases(self):
- '''MDerived1 is casted by C++ to its parents and the binding must return the MDerived1 wrapper.'''
- a = MDerived1()
- refcnt = sys.getrefcount(a)
- b1 = a.castToBase1()
- b2 = a.castToBase2()
- self.assertTrue(isinstance(b1, MDerived1))
- self.assertTrue(isinstance(b2, MDerived1))
- self.assertEqual(a, b1)
- self.assertEqual(a, b2)
- self.assertEqual(sys.getrefcount(a), refcnt + 2)
-
- def testCastFromExtMDerived1ToMDerived1Bases(self):
- '''Python defined class ExtMDerived1 is casted by C++ to MDerived1 parents and the binding must return the correct ExtMDerived1 instance.'''
- a = ExtMDerived1()
- refcnt = sys.getrefcount(a)
- b1 = a.castToBase1()
- self.assertTrue(isinstance(b1, MDerived1))
- self.assertTrue(isinstance(b1, ExtMDerived1))
- b2 = a.castToBase2()
- self.assertTrue(isinstance(b2, MDerived1))
- self.assertTrue(isinstance(b2, ExtMDerived1))
- self.assertEqual(a, b1)
- self.assertEqual(a, b2)
- self.assertEqual(sys.getrefcount(a), refcnt + 2)
-
- def testCastFromSonOfMDerived1ToBases(self):
- '''SonOfMDerived1 is casted by C++ to its parents and the binding must return the SonOfMDerived1 wrapper.'''
- a = SonOfMDerived1()
- refcnt = sys.getrefcount(a)
- md1 = a.castToMDerived1()
- b1 = a.castToBase1()
- b2 = a.castToBase2()
- self.assertTrue(isinstance(md1, SonOfMDerived1))
- self.assertTrue(isinstance(b2, SonOfMDerived1))
- self.assertTrue(isinstance(b2, SonOfMDerived1))
- self.assertEqual(a, md1)
- self.assertEqual(a, b1)
- self.assertEqual(a, b2)
- self.assertEqual(sys.getrefcount(a), refcnt + 3)
-
- def testReimplementedBase2VirtualMethodOnClassInheritingFromMDerived1(self):
- a = ExtMDerived1()
- value = a.base2Method()
- self.assertTrue(value, Base2.base2Method(a) * a.multiplier)
-
- def testCastFromMDerived2ToBases(self):
- '''MDerived2 is casted by C++ to its parents and the binding must return the MDerived2 wrapper.'''
- a = MDerived2()
- refcnt = sys.getrefcount(a)
- b3 = a.castToBase3()
- b4 = a.castToBase4()
- b5 = a.castToBase5()
- b6 = a.castToBase6()
- self.assertTrue(isinstance(b3, MDerived2))
- self.assertTrue(isinstance(b4, MDerived2))
- self.assertTrue(isinstance(b5, MDerived2))
- self.assertTrue(isinstance(b6, MDerived2))
- self.assertEqual(a, b3)
- self.assertEqual(a, b4)
- self.assertEqual(a, b5)
- self.assertEqual(a, b6)
- self.assertEqual(sys.getrefcount(a), refcnt + 4)
-
- def testCastFromMDerived3ToBases(self):
- '''MDerived3 is casted by C++ to its parents and the binding must return the MDerived3 wrapper.'''
- a = MDerived3()
- refcnt = sys.getrefcount(a)
- md1 = a.castToMDerived1()
- md2 = a.castToMDerived2()
- b1 = a.castToBase1()
- b2 = a.castToBase2()
- b3 = a.castToBase3()
- b4 = a.castToBase4()
- b5 = a.castToBase5()
- b6 = a.castToBase6()
- self.assertTrue(isinstance(md1, MDerived3))
- self.assertTrue(isinstance(md2, MDerived3))
- self.assertTrue(isinstance(b1, MDerived3))
- self.assertTrue(isinstance(b2, MDerived3))
- self.assertTrue(isinstance(b3, MDerived3))
- self.assertTrue(isinstance(b4, MDerived3))
- self.assertTrue(isinstance(b5, MDerived3))
- self.assertTrue(isinstance(b6, MDerived3))
- self.assertEqual(a, md1)
- self.assertEqual(a, md2)
- self.assertEqual(a, b1)
- self.assertEqual(a, b2)
- self.assertEqual(a, b3)
- self.assertEqual(a, b4)
- self.assertEqual(a, b5)
- self.assertEqual(a, b6)
- self.assertEqual(sys.getrefcount(a), refcnt + 8)
-
- def testCastFromMDerived4ToBases(self):
- '''MDerived4 is casted by C++ to its parents and the binding must return the MDerived4 wrapper.'''
- a = MDerived4()
- refcnt = sys.getrefcount(a)
- b3 = a.castToBase3()
- b4 = a.castToBase4()
- self.assertTrue(isinstance(b3, MDerived4))
- self.assertTrue(isinstance(b4, MDerived4))
- self.assertEqual(a, b3)
- self.assertEqual(a, b4)
- self.assertEqual(sys.getrefcount(a), refcnt + 2)
-
- def testCastFromMDerived5ToBases(self):
- '''MDerived5 is casted by C++ to its parents and the binding must return the MDerived5 wrapper.'''
- a = MDerived5()
- refcnt = sys.getrefcount(a)
- b3 = a.castToBase3()
- b4 = a.castToBase4()
- self.assertTrue(isinstance(b3, MDerived5))
- self.assertTrue(isinstance(b4, MDerived5))
- self.assertEqual(a, b3)
- self.assertEqual(a, b4)
- self.assertEqual(sys.getrefcount(a), refcnt + 2)
-
- def testCastFromMDerived3ToBase3(self):
- '''MDerived3 is casted by C++ to Base3 grandparent using both the inherited and reimplement castToBase3 methods.'''
- a = MDerived3()
- refcnt = sys.getrefcount(a)
- b3_reimplemented = a.castToBase3()
- b3_inherited = MDerived2.castToBase3(a)
- self.assertTrue(isinstance(b3_reimplemented, MDerived3))
- self.assertTrue(isinstance(b3_inherited, MDerived3))
- self.assertEqual(a, b3_reimplemented)
- self.assertEqual(a, b3_inherited)
- self.assertEqual(sys.getrefcount(a), refcnt + 2)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/namespace_test.py b/sources/shiboken2/tests/samplebinding/namespace_test.py
deleted file mode 100644
index 23480d4c4..000000000
--- a/sources/shiboken2/tests/samplebinding/namespace_test.py
+++ /dev/null
@@ -1,95 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for std::map container conversions'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-from shiboken_test_helper import objectFullname
-
-
-class TestEnumUnderNamespace(unittest.TestCase):
- def testInvisibleNamespace(self):
- o1 = EnumOnNamespace.Option1
- self.assertEqual(o1, 1)
- def testTpNames(self):
- self.assertEqual(objectFullname(EnumOnNamespace), "sample.EnumOnNamespace")
- self.assertEqual(str(EnumOnNamespace.Option1),
- "sample.EnumOnNamespace.Option1")
-
-class TestClassesUnderNamespace(unittest.TestCase):
- def testIt(self):
- c1 = SampleNamespace.SomeClass()
- e1 = SampleNamespace.SomeClass.ProtectedEnum()
- c2 = SampleNamespace.SomeClass.SomeInnerClass()
- e2 = SampleNamespace.SomeClass.SomeInnerClass.ProtectedEnum()
- c3 = SampleNamespace.SomeClass.SomeInnerClass.OkThisIsRecursiveEnough()
- e3 = SampleNamespace.SomeClass.SomeInnerClass.OkThisIsRecursiveEnough.NiceEnum()
-
- def testFunctionAddedOnNamespace(self):
- res = SampleNamespace.ImInsideANamespace(2, 2)
- self.assertEqual(res, 4)
-
- def testTpNames(self):
- self.assertEqual(str(SampleNamespace.SomeClass),
- "<class 'sample.SampleNamespace.SomeClass'>")
- self.assertEqual(str(SampleNamespace.SomeClass.ProtectedEnum),
- "<class 'sample.SampleNamespace.SomeClass.ProtectedEnum'>")
- self.assertEqual(str(SampleNamespace.SomeClass.SomeInnerClass.ProtectedEnum),
- "<class 'sample.SampleNamespace.SomeClass.SomeInnerClass.ProtectedEnum'>")
- self.assertEqual(str(SampleNamespace.SomeClass.SomeInnerClass.OkThisIsRecursiveEnough),
- "<class 'sample.SampleNamespace.SomeClass.SomeInnerClass.OkThisIsRecursiveEnough'>")
- self.assertEqual(str(SampleNamespace.SomeClass.SomeInnerClass.OkThisIsRecursiveEnough.NiceEnum),
- "<class 'sample.SampleNamespace.SomeClass.SomeInnerClass.OkThisIsRecursiveEnough.NiceEnum'>")
-
- # Test if enum inside of class is correct represented
- self.assertEqual(objectFullname(SampleNamespace.enumInEnumOut.__signature__.parameters['in_'].annotation),
- "sample.SampleNamespace.InValue")
- self.assertEqual(objectFullname(SampleNamespace.enumAsInt.__signature__.parameters['value'].annotation),
- "sample.SampleNamespace.SomeClass.PublicScopedEnum")
- self.assertEqual(objectFullname(ObjectOnInvisibleNamespace.toInt.__signature__.parameters['e'].annotation),
- "sample.EnumOnNamespace")
-
- # Test if enum on namespace that was marked as not gerenated does not appear on type name
- self.assertEqual(objectFullname(ObjectOnInvisibleNamespace),
- "sample.ObjectOnInvisibleNamespace")
- self.assertEqual(objectFullname(ObjectOnInvisibleNamespace.consume.__signature__.parameters['other'].annotation),
- "sample.ObjectOnInvisibleNamespace")
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/newdivision_test.py b/sources/shiboken2/tests/samplebinding/newdivision_test.py
deleted file mode 100644
index d352c1b91..000000000
--- a/sources/shiboken2/tests/samplebinding/newdivision_test.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import division
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-
-class TestNewDivision(unittest.TestCase):
-
- def testIt(self):
- p = Point(4, 4)
- p2 = p/2
- self.assertEqual(p2, Point(2, 2))
-
-if __name__ == "__main__":
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/nondefaultctor_test.py b/sources/shiboken2/tests/samplebinding/nondefaultctor_test.py
deleted file mode 100644
index 68d083136..000000000
--- a/sources/shiboken2/tests/samplebinding/nondefaultctor_test.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for ...'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import NonDefaultCtor
-
-class DerivedNonDefaultCtor (NonDefaultCtor):
- def returnMyselfVirtual(self):
- return NonDefaultCtor(self.value()+1)
-
-class AnotherDerivedNonDefaultCtor (NonDefaultCtor):
- def __init__(self, some_string):
- pass
-
-class NonDefaultCtorTest(unittest.TestCase):
-
- def testNonDefaultCtor(self):
- c = NonDefaultCtor(2)
- # these functions returns NonDefaultCtor by value, so a PyObjecy is created every time
- self.assertNotEqual(c.returnMyself(), c)
- self.assertEqual(c.returnMyself().value(), 2)
- self.assertNotEqual(c.returnMyself(3), c)
- self.assertEqual(c.returnMyself(3).value(), 2)
- self.assertNotEqual(c.returnMyself(4, c), c)
- self.assertEqual(c.returnMyself(4, c).value(), 2)
-
- def testVirtuals(self):
- c = DerivedNonDefaultCtor(3)
- # these functions returns NonDefaultCtor by value, so a PyObjecy is created every time
- self.assertNotEqual(c.returnMyselfVirtual(), c)
- self.assertEqual(c.returnMyselfVirtual().value(), 4)
- self.assertEqual(c.callReturnMyselfVirtual().value(), 4)
-
- def testCtorOverload(self):
- c = AnotherDerivedNonDefaultCtor("testing")
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/nontypetemplate_test.py b/sources/shiboken2/tests/samplebinding/nontypetemplate_test.py
deleted file mode 100644
index 7c4729b4f..000000000
--- a/sources/shiboken2/tests/samplebinding/nontypetemplate_test.py
+++ /dev/null
@@ -1,65 +0,0 @@
-#!/usr/bin/env python
-#
-#############################################################################
-##
-## Copyright (C) 2018 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-hasNumPy = False
-
-try:
- import numpy
- hasNumPy = True
-except ImportError:
- pass
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import IntArray2, IntArray3
-
-class NonTypeTemplateTest(unittest.TestCase):
-
- def testNonTypeTemplate(self):
- array2 = IntArray2(3)
- self.assertEqual(array2.sum(), 6)
- array3 = IntArray3(5)
- self.assertEqual(array3.sum(), 15)
-
- def testArrayInitializer(self):
- if not hasNumPy:
- return
- array3 = IntArray3(numpy.array([1, 2, 3], dtype = 'int32'))
- self.assertEqual(array3.sum(), 6)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/nonzero_test.py b/sources/shiboken2/tests/samplebinding/nonzero_test.py
deleted file mode 100644
index 214b2f7bd..000000000
--- a/sources/shiboken2/tests/samplebinding/nonzero_test.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class TestNonZeroOperator(unittest.TestCase):
- def testIt(self):
- c = Color()
- self.assertFalse(c)
- c = Color(2)
- self.assertTrue(c)
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/numericaltypedef_test.py b/sources/shiboken2/tests/samplebinding/numericaltypedef_test.py
deleted file mode 100644
index de9128cbc..000000000
--- a/sources/shiboken2/tests/samplebinding/numericaltypedef_test.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import SizeF
-
-class NumericalTypedefTest(unittest.TestCase):
-
- def testNumericalTypedefExact(self):
- width, height = (1.1, 2.2)
- size = SizeF(width, height)
- self.assertEqual(size.width(), width)
- self.assertEqual(size.height(), height)
-
- def testNumericalTypedefConvertible(self):
- width, height = (1, 2)
- size = SizeF(width, height)
- self.assertEqual(size.width(), float(width))
- self.assertEqual(size.height(), float(height))
-
- def testNumericalTypedefOfUnsignedShort(self):
- self.assertEqual(SizeF.passTypedefOfUnsignedShort(123), 123)
- self.assertEqual(SizeF.passTypedefOfUnsignedShort(321), 321)
- self.assertNotEqual(SizeF.passTypedefOfUnsignedShort(123), 0)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/numpy_test.py b/sources/shiboken2/tests/samplebinding/numpy_test.py
deleted file mode 100644
index 3f67f59e4..000000000
--- a/sources/shiboken2/tests/samplebinding/numpy_test.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import sys
-
-try:
- from distutils import sysconfig
- if bool(sysconfig.get_config_var('Py_DEBUG')):
- sys.exit(0)
- import numpy
-except:
- sys.exit(0)
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import PointF
-
-class TestNumpyTypes(unittest.TestCase):
-
- def testNumpyConverted(self):
- x, y = (0.1, 0.2)
- p = PointF(float(numpy.float32(x)), float(numpy.float32(y)))
- self.assertAlmostEqual(p.x(), x)
- self.assertAlmostEqual(p.y(), y)
-
- def testNumpyAsIs(self):
- x, y = (0.1, 0.2)
- p = PointF(numpy.float32(x), numpy.float32(y))
- self.assertAlmostEqual(p.x(), x)
- self.assertAlmostEqual(p.y(), y)
-
-if __name__ == "__main__":
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/objecttype_test.py b/sources/shiboken2/tests/samplebinding/objecttype_test.py
deleted file mode 100644
index 1d7f70722..000000000
--- a/sources/shiboken2/tests/samplebinding/objecttype_test.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests ObjectType class of object-type with privates copy constructor and = operator.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import sys
-
-from sample import ObjectType, Str
-import shiboken2 as shiboken
-
-
-class ObjectTypeTest(unittest.TestCase):
- '''Test cases ObjectType class of object-type with privates copy constructor and = operator.'''
-
- def testObjectTypeSetObjectNameWithStrVariable(self):
- '''ObjectType.setObjectName with Str variable as argument.'''
- s = Str('object name')
- o = ObjectType()
- o.setObjectName(s)
- self.assertEqual(str(o.objectName()), str(s))
-
- def testObjectTypeSetObjectNameWithStrInstantiation(self):
- '''ObjectType.setObjectName with Str instantiation as argument.'''
- s = 'object name'
- o = ObjectType()
- o.setObjectName(Str(s))
- self.assertEqual(str(o.objectName()), s)
-
- def testObjectTypeSetObjectNameWithPythonString(self):
- '''ObjectType.setObjectName with Python string as argument.'''
- o = ObjectType()
- o.setObjectName('object name')
- self.assertEqual(str(o.objectName()), 'object name')
-
- def testNullOverload(self):
- o = ObjectType()
- o.setObject(None)
- self.assertEqual(o.callId(), 0)
- o.setNullObject(None)
- self.assertEqual(o.callId(), 1)
-
- def testParentFromCpp(self):
- o = ObjectType()
- self.assertEqual(sys.getrefcount(o), 2)
- o.getCppParent().setObjectName('parent')
- self.assertEqual(sys.getrefcount(o), 3)
- o.getCppParent().setObjectName('parent')
- self.assertEqual(sys.getrefcount(o), 3)
- o.getCppParent().setObjectName('parent')
- self.assertEqual(sys.getrefcount(o), 3)
- o.getCppParent().setObjectName('parent')
- self.assertEqual(sys.getrefcount(o), 3)
- o.getCppParent().setObjectName('parent')
- self.assertEqual(sys.getrefcount(o), 3)
- o.destroyCppParent()
- self.assertEqual(sys.getrefcount(o), 2)
-
- def testNextInFocusChainCycle(self):
- parent = ObjectType()
- child = ObjectType(parent)
- next_focus = child.nextInFocusChain()
-
- shiboken.invalidate(parent)
-
- def testNextInFocusChainCycleList(self):
- '''As above but in for a list of objects'''
- parents = []
- children = []
- focus_chains = []
- for i in range(10):
- parent = ObjectType()
- child = ObjectType(parent)
- next_focus = child.nextInFocusChain()
- parents.append(parent)
- children.append(child)
- focus_chains.append(next_focus)
-
- shiboken.invalidate(parents)
-
- def testClassDecref(self):
- # Bug was that class PyTypeObject wasn't decrefed when instance died
- before = sys.getrefcount(ObjectType)
-
- for i in range(1000):
- obj = ObjectType()
- shiboken.delete(obj)
-
- after = sys.getrefcount(ObjectType)
-
- self.assertLess(abs(before - after), 5)
-
- def testInvalidProperty(self):
- o = ObjectType()
- try:
- o.typo
- self.assertFail()
- except AttributeError as error:
- self.assertEqual(error.args[0], "'sample.ObjectType' object has no attribute 'typo'")
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/objecttype_with_named_args_test.py b/sources/shiboken2/tests/samplebinding/objecttype_with_named_args_test.py
deleted file mode 100644
index ce7874c23..000000000
--- a/sources/shiboken2/tests/samplebinding/objecttype_with_named_args_test.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType
-
-class NamedArgsTest(unittest.TestCase):
-
- def testOneArgument(self):
- p = ObjectType()
- o = ObjectType(parent=p)
- self.assertEqual(o.parent(), p)
-
- def testMoreArguments(self):
- o = ObjectType()
-
- o.setObjectSplittedName("", prefix="pys", suffix="ide")
- self.assertEqual(o.objectName(), "pyside")
-
- o.setObjectSplittedName("", suffix="ide", prefix="pys")
- self.assertEqual(o.objectName(), "pyside")
-
- o.setObjectNameWithSize(name="pyside", size=6)
- self.assertEqual(o.objectName(), "pyside")
-
- o.setObjectNameWithSize(size=6, name="pyside")
- self.assertEqual(o.objectName(), "pyside")
-
-
- def testUseDefaultValues(self):
- o = ObjectType()
-
- o.setObjectNameWithSize(size=3)
- self.assertEqual(o.objectName(), "<un") # use name='unknown' default argument
-
- o.setObjectSplittedName("")
- self.assertEqual(o.objectName(), "<unknown>") # user prefix='<unk' and suffix='nown>'
-
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/objecttypebyvalue_test.py b/sources/shiboken2/tests/samplebinding/objecttypebyvalue_test.py
deleted file mode 100644
index 080a51ce5..000000000
--- a/sources/shiboken2/tests/samplebinding/objecttypebyvalue_test.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-
-class ObjectTypeByValueTest (unittest.TestCase):
- def testIt(self):
- factory = ObjectTypeByValue()
- obj = factory.returnSomeKindOfMe()
- # This should crash!
- obj.prop.protectedValueTypeProperty.setX(1.0)
- # just to make sure it will segfault
- obj.prop.protectedValueTypeProperty.setY(2.0)
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/objecttypelayout_test.py b/sources/shiboken2/tests/samplebinding/objecttypelayout_test.py
deleted file mode 100644
index bcf30eb43..000000000
--- a/sources/shiboken2/tests/samplebinding/objecttypelayout_test.py
+++ /dev/null
@@ -1,307 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests cases for ObjectTypeLayout class.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-
-class ObjectTypeLayoutTest(unittest.TestCase):
- '''Test cases for ObjectTypeLayout class.'''
-
- def testOwnershipOverride(self):
- l = ObjectTypeLayout()
-
- o1 = ObjectType(l)
- o1.setObjectName('o1')
-
- self.assertEqual(sys.getrefcount(o1), 3)
- l.takeChild('o1')
- self.assertEqual(sys.getrefcount(o1), 2)
-
-
- def testSetNullLayout(self):
- '''ObjectType.setLayout(0).'''
- o2 = ObjectType()
- o2.setLayout(None)
-
- def testSetNullLayoutToObjectTypeCreatedInCpp(self):
- '''ObjectType.setLayout(0) to object created in C++.'''
- o1 = ObjectType.create()
- o1.setLayout(None)
-
- def testObjectTypeLayout(self):
- '''ObjectType.setLayout.'''
- p1 = ObjectType()
- c1 = ObjectType()
- c2 = ObjectType()
- c3 = ObjectType()
- layout = ObjectTypeLayout()
- layout.addObject(c1)
- layout.addObject(c2)
- layout.addObject(c3)
- self.assertEqual(c1.parent(), None)
- self.assertEqual(c2.parent(), None)
- self.assertEqual(c3.parent(), None)
-
- p1.setLayout(layout)
- del p1 # This must kill c1, c2 and c3
-
- self.assertRaises(RuntimeError, c1.objectName)
- self.assertRaises(RuntimeError, c2.objectName)
- self.assertRaises(RuntimeError, c3.objectName)
- self.assertRaises(RuntimeError, layout.objectName)
-
- def testObjectTypeLayoutWithObjectsCreatedInCpp(self):
- '''ObjectType.setLayout with objects created in C++.'''
- p1 = ObjectType.create()
- c1 = ObjectType.create()
- c2 = ObjectType.create()
- c3 = ObjectType.create()
- layout = ObjectTypeLayout()
- layout.addObject(c1)
- layout.addObject(c2)
- layout.addObject(c3)
- self.assertEqual(c1.parent(), None)
- self.assertEqual(c2.parent(), None)
- self.assertEqual(c3.parent(), None)
-
- p1.setLayout(layout)
- del p1 # This must kill c1, c2 and c3
-
- self.assertRaises(RuntimeError, c1.objectName)
- self.assertRaises(RuntimeError, c2.objectName)
- self.assertRaises(RuntimeError, c3.objectName)
- self.assertRaises(RuntimeError, layout.objectName)
-
- def testObjectTypeLayoutTransference(self):
- '''Transfer a layout from one ObjectType to another, so that all the items in the layout get reparented.'''
- p1 = ObjectType()
- p2 = ObjectType()
- c1 = ObjectType()
- c2 = ObjectType()
-
- layout = ObjectTypeLayout()
- layout.addObject(c1)
- layout.addObject(c2)
-
- p1.setLayout(layout)
-
- self.assertEqual(len(p2.children()), 0)
- self.assertEqual(c1.parent(), p1)
- self.assertEqual(c2.parent(), p1)
- self.assertEqual(set(p1.children()), set([c1, c2, layout]))
-
- p2.setLayout(layout)
-
- self.assertEqual(len(p1.children()), 0)
- self.assertEqual(c1.parent(), p2)
- self.assertEqual(c2.parent(), p2)
- self.assertEqual(set(p2.children()), set([c1, c2, layout]))
-
- def testObjectTypeLayoutInsideAnotherLayout(self):
- '''Adds one ObjectTypeLayout to another and sets the parent to an ObjectType.'''
- p1 = ObjectType()
-
- l1 = ObjectTypeLayout()
- c1 = ObjectType()
- l1.addObject(c1)
- c2 = ObjectType()
- l1.addObject(c2)
-
- l2 = ObjectTypeLayout()
- c3 = ObjectType()
- l2.addObject(c3)
- c4 = ObjectType()
- l2.addObject(c4)
-
- l1.addObject(l2)
-
- p1.setLayout(l1)
-
- self.assertEqual(c1.parent(), p1)
- self.assertEqual(c2.parent(), p1)
- self.assertEqual(c3.parent(), p1)
- self.assertEqual(c4.parent(), p1)
- self.assertEqual(l1.parent(), p1)
- self.assertEqual(l2.parent(), l1)
-
- del p1
-
- self.assertRaises(RuntimeError, c1.objectName)
- self.assertRaises(RuntimeError, c2.objectName)
- self.assertRaises(RuntimeError, c3.objectName)
- self.assertRaises(RuntimeError, c4.objectName)
- self.assertRaises(RuntimeError, l1.objectName)
- self.assertRaises(RuntimeError, l2.objectName)
-
- def testObjectTypeLayoutInsideAnotherLayoutAndEveryoneCreatedInCpp(self):
- '''Adds one ObjectTypeLayout to another and sets the parent to an ObjectType. All the objects are created in C++.'''
- p1 = ObjectType.create()
-
- l1 = ObjectTypeLayout.create()
- c1 = ObjectType.create()
- l1.addObject(c1)
- c2 = ObjectType.create()
- l1.addObject(c2)
-
- l2 = ObjectTypeLayout.create()
- c3 = ObjectType.create()
- l2.addObject(c3)
- c4 = ObjectType.create()
- l2.addObject(c4)
-
- l1.addObject(l2)
-
- p1.setLayout(l1)
-
- self.assertEqual(c1.parent(), p1)
- self.assertEqual(c2.parent(), p1)
- self.assertEqual(c3.parent(), p1)
- self.assertEqual(c4.parent(), p1)
- self.assertEqual(l1.parent(), p1)
- self.assertEqual(l2.parent(), l1)
-
- del p1
-
- self.assertRaises(RuntimeError, c1.objectName)
- self.assertRaises(RuntimeError, c2.objectName)
- self.assertRaises(RuntimeError, c3.objectName)
- self.assertRaises(RuntimeError, c4.objectName)
- self.assertRaises(RuntimeError, l1.objectName)
- self.assertRaises(RuntimeError, l2.objectName)
-
- def testTransferNestedLayoutsBetweenObjects(self):
- '''Adds one ObjectTypeLayout to another, sets the parent to an ObjectType and then transfer it to another object.'''
- p1 = ObjectType()
- p2 = ObjectType()
-
- l1 = ObjectTypeLayout()
- c1 = ObjectType()
- l1.addObject(c1)
- c2 = ObjectType()
- l1.addObject(c2)
-
- l2 = ObjectTypeLayout()
- c3 = ObjectType()
- l2.addObject(c3)
- c4 = ObjectType()
- l2.addObject(c4)
-
- l1.addObject(l2)
-
- p1.setLayout(l1)
-
- self.assertEqual(c1.parent(), p1)
- self.assertEqual(c2.parent(), p1)
- self.assertEqual(c3.parent(), p1)
- self.assertEqual(c4.parent(), p1)
- self.assertEqual(l1.parent(), p1)
- self.assertEqual(l2.parent(), l1)
-
- p2.setLayout(l1)
- del p1
-
- self.assertEqual(c1.parent(), p2)
- self.assertEqual(c2.parent(), p2)
- self.assertEqual(c3.parent(), p2)
- self.assertEqual(c4.parent(), p2)
- self.assertEqual(l1.parent(), p2)
- self.assertEqual(l2.parent(), l1)
-
- del p2
-
- self.assertRaises(RuntimeError, c1.objectName)
- self.assertRaises(RuntimeError, c2.objectName)
- self.assertRaises(RuntimeError, c3.objectName)
- self.assertRaises(RuntimeError, c4.objectName)
- self.assertRaises(RuntimeError, l1.objectName)
- self.assertRaises(RuntimeError, l2.objectName)
-
- def testTransferNestedLayoutsBetweenObjectsAndEveryoneCreatedInCpp(self):
- '''Adds one ObjectTypeLayout to another, sets the parent to an ObjectType and then transfer it to another object.
- All the objects are created in C++.'''
- p1 = ObjectType.create()
- p2 = ObjectType.create()
-
- l1 = ObjectTypeLayout.create()
- c1 = ObjectType.create()
- l1.addObject(c1)
- c2 = ObjectType.create()
- l1.addObject(c2)
-
- l2 = ObjectTypeLayout.create()
- c3 = ObjectType.create()
- l2.addObject(c3)
- c4 = ObjectType.create()
- l2.addObject(c4)
-
- l1.addObject(l2)
-
- p1.setLayout(l1)
-
- self.assertEqual(c1.parent(), p1)
- self.assertEqual(c2.parent(), p1)
- self.assertEqual(c3.parent(), p1)
- self.assertEqual(c4.parent(), p1)
- self.assertEqual(l1.parent(), p1)
- self.assertEqual(l2.parent(), l1)
-
- p2.setLayout(l1)
- del p1
-
- self.assertEqual(c1.parent(), p2)
- self.assertEqual(c2.parent(), p2)
- self.assertEqual(c3.parent(), p2)
- self.assertEqual(c4.parent(), p2)
- self.assertEqual(l1.parent(), p2)
- self.assertEqual(l2.parent(), l1)
-
- del p2
-
- self.assertRaises(RuntimeError, c1.objectName)
- self.assertRaises(RuntimeError, c2.objectName)
- self.assertRaises(RuntimeError, c3.objectName)
- self.assertRaises(RuntimeError, c4.objectName)
- self.assertRaises(RuntimeError, l1.objectName)
- self.assertRaises(RuntimeError, l2.objectName)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/objecttypeoperators_test.py b/sources/shiboken2/tests/samplebinding/objecttypeoperators_test.py
deleted file mode 100644
index fb0d52319..000000000
--- a/sources/shiboken2/tests/samplebinding/objecttypeoperators_test.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import *
-
-class ObjectTypeOperatorsTest(unittest.TestCase):
-
- def testIt(self):
- a = ObjectTypeOperators("a")
- b = ObjectTypeOperators("b")
- self.assertFalse(a == b)
- self.assertEqual(a, a < b)
-
- # this should change a.key() and return nothing.
- self.assertEqual(None, a > b)
- self.assertEqual(a.key(), "aoperator>")
-
- def testPointerOpeators(self):
- a = ObjectTypeOperators("a")
- b = ObjectTypeOperators("b")
- self.assertEqual(a + "bc", "abc")
- self.assertEqual("bc" + a, "bca")
- self.assertEqual("a", a)
- self.assertEqual(a, "a")
-
- def testOperatorInjection(self):
- a = ObjectTypeOperators("a")
- self.assertNotEqual(a, "b")
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/objecttypereferenceasvirtualmethodargument_test.py b/sources/shiboken2/tests/samplebinding/objecttypereferenceasvirtualmethodargument_test.py
deleted file mode 100644
index 40adb94ed..000000000
--- a/sources/shiboken2/tests/samplebinding/objecttypereferenceasvirtualmethodargument_test.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import ObjectTypeHolder
-
-class TestObjectTypeReferenceAsVirtualMethodArgument(unittest.TestCase):
-
- def testBasic(self):
- holder = ObjectTypeHolder('TheObjectFromC++')
- self.assertEqual(holder.callPassObjectTypeAsReference(), 'TheObjectFromC++')
-
- def testExtended(self):
- class Holder(ObjectTypeHolder):
- def passObjectTypeAsReference(self, objectType):
- return objectType.objectName().prepend(('ThisIs'))
- holder = Holder('TheObjectFromC++')
- self.assertEqual(holder.callPassObjectTypeAsReference(), 'ThisIsTheObjectFromC++')
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/oddbool_test.py b/sources/shiboken2/tests/samplebinding/oddbool_test.py
deleted file mode 100644
index de1429604..000000000
--- a/sources/shiboken2/tests/samplebinding/oddbool_test.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for OddBool user's primitive type conversion.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import OddBoolUser
-
-class DerivedOddBoolUser (OddBoolUser):
- def returnMyselfVirtual(self):
- return OddBoolUser()
- pass
-
-class OddBoolTest(unittest.TestCase):
-
- def testOddBoolUser(self):
- obuTrue = OddBoolUser()
- obuFalse = OddBoolUser()
- obuTrue.setOddBool(True)
- self.assertEqual(obuFalse.oddBool(), False)
- self.assertEqual(obuTrue.oddBool(), True)
- self.assertEqual(obuTrue.callInvertedOddBool(), False)
-
- self.assertEqual(obuTrue.oddBool() == True, True)
- self.assertEqual(False == obuFalse.oddBool(), True)
- self.assertEqual(obuTrue.oddBool() == obuFalse.oddBool(), False)
-
- self.assertEqual(obuFalse.oddBool() != True, True)
- self.assertEqual(True != obuFalse.oddBool(), True)
- self.assertEqual(obuTrue.oddBool() != obuFalse.oddBool(), True)
-
- def testVirtuals(self):
- dobu = DerivedOddBoolUser()
- self.assertEqual(dobu.invertedOddBool(), True)
-
- def testImplicitConversionWithUsersPrimitiveType(self):
- obu = OddBoolUser(True)
- self.assertTrue(obu.oddBool())
- obu = OddBoolUser(False)
- self.assertFalse(obu.oddBool())
- cpx = complex(1.0, 0.0)
- obu = OddBoolUser(cpx)
- self.assertTrue(obu.oddBool())
- cpx = complex(0.0, 0.0)
- obu = OddBoolUser(cpx)
- self.assertFalse(obu.oddBool())
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/oldstyleclass_as_number_test.py b/sources/shiboken2/tests/samplebinding/oldstyleclass_as_number_test.py
deleted file mode 100644
index e0f864636..000000000
--- a/sources/shiboken2/tests/samplebinding/oldstyleclass_as_number_test.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import sample
-from py3kcompat import IS_PY3K
-
-class OldStyle:
- pass
-
-class NewStyle(object):
- pass
-
-class OldStyleNumber:
- def __init__(self, value):
- self.value = value
- def __trunc__(self):
- return self.value
-
-class NewStyleNumber(object):
- def __init__(self, value):
- self.value = value
- def __int__(self):
- return int(self.value)
- def __trunc__(self):
- return self.value
-
-class TestOldStyleClassAsNumber(unittest.TestCase):
-
- def testBasic(self):
- '''For the sake of calibration...'''
- self.assertEqual(sample.acceptInt(123), 123)
-
- def testOldStyleClassPassedAsInteger(self):
- '''Old-style classes aren't numbers and shouldn't be accepted.'''
- obj = OldStyle()
- self.assertRaises(TypeError, sample.acceptInt, obj)
-
- def testNewStyleClassPassedAsInteger(self):
- '''New-style classes aren't numbers and shouldn't be accepted.'''
- obj = NewStyle()
- self.assertRaises(TypeError, sample.acceptInt, obj)
-
- def testOldStyleClassWithNumberProtocol(self):
- obj = OldStyleNumber(123)
- self.assertEqual(sample.acceptInt(obj), obj.value)
-
- def testNewStyleClassWithNumberProtocol(self):
- obj = NewStyleNumber(123)
- self.assertEqual(sample.acceptInt(obj), obj.value)
-
-if __name__ == "__main__" and not IS_PY3K:
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/onlycopyclass_test.py b/sources/shiboken2/tests/samplebinding/onlycopyclass_test.py
deleted file mode 100644
index ccf71f4f8..000000000
--- a/sources/shiboken2/tests/samplebinding/onlycopyclass_test.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import OnlyCopy, FriendOfOnlyCopy
-
-class ClassWithOnlyCopyCtorTest(unittest.TestCase):
- def testGetOne(self):
- obj = FriendOfOnlyCopy.createOnlyCopy(123)
- self.assertEqual(type(obj), OnlyCopy)
- self.assertEqual(obj.value(), 123)
-
- def testGetMany(self):
- objs = FriendOfOnlyCopy.createListOfOnlyCopy(3)
- self.assertEqual(type(objs), list)
- self.assertEqual(len(objs), 3)
- for value, obj in enumerate(objs):
- self.assertEqual(obj.value(), value)
-
- def testPassAsValue(self):
- obj = FriendOfOnlyCopy.createOnlyCopy(123)
- self.assertEqual(obj.value(), OnlyCopy.getValue(obj))
-
- def testPassAsReference(self):
- obj = FriendOfOnlyCopy.createOnlyCopy(123)
- self.assertEqual(obj.value(), OnlyCopy.getValueFromReference(obj))
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/overflow_test.py b/sources/shiboken2/tests/samplebinding/overflow_test.py
deleted file mode 100644
index 56a5d98c7..000000000
--- a/sources/shiboken2/tests/samplebinding/overflow_test.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for overflowing C++ numeric types.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-from py3kcompat import IS_PY3K, long
-
-class OverflowTest(unittest.TestCase):
- '''Test case for overflowing C++ numeric types.'''
-
- def testUnsignedInt(self):
- '''C++ function receives an unsigned int argument and raise OverflowError if the value is negative.'''
- val = 100
- self.assertEqual(doubleUnsignedInt(val), 2 * val)
- val *= -1
- self.assertRaises(OverflowError, doubleUnsignedInt, val)
-
- def testLongLong(self):
- '''C++ function receives an long long argument and raise OverflowError if the value is negative.'''
- val = 100
- self.assertEqual(doubleLongLong(val), 2 * val)
- val = long(100)
- self.assertEqual(doubleLongLong(val), 2 * val)
- val = (2 << 64) + 1
- self.assertRaises(OverflowError, doubleLongLong, val)
-
- def testUnsignedLongLong(self):
- '''C++ function receives an unsigned long long argument and raise OverflowError if the value is negative.'''
- val = 100
- self.assertEqual(doubleUnsignedLongLong(val), 2 * val)
- val = long(100)
- self.assertEqual(doubleUnsignedLongLong(val), 2 * val)
- val = -100
- self.assertRaises(OverflowError, doubleUnsignedLongLong, val)
- val = long(-200)
- self.assertRaises(OverflowError, doubleUnsignedLongLong, val)
-
- def testOverflow(self):
- '''Calls function with unsigned int parameter using an overflowing value.'''
- self.assertRaises(OverflowError, doubleUnsignedInt, 42415335332353253)
- doubleUnsignedInt(0xdeadbeef)
-
- def testShortOverflow(self):
- '''Calls function with short parameter using an overflowing value.'''
- doubleShort(-3)
- self.assertRaises(OverflowError, doubleShort, 0xFFFF*-1)
- self.assertRaises(OverflowError, doubleShort, 0xFFFF + 1)
-
- def testOverflowOnCtor(self):
- '''Calls object ctor with int parameter using overflowing values.'''
- self.assertRaises(OverflowError, Point, 42415335332353253, 42415335332353253)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/overload_sorting_test.py b/sources/shiboken2/tests/samplebinding/overload_sorting_test.py
deleted file mode 100644
index 8132e4e3d..000000000
--- a/sources/shiboken2/tests/samplebinding/overload_sorting_test.py
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for overload sorting'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class Dummy(object):
- pass
-
-class SimpleOverloadSorting(unittest.TestCase):
-
- def setUp(self):
- self.obj = SortedOverload()
-
- def testIntDouble(self):
- '''Overloads with int and double'''
- self.assertEqual(self.obj.overload(3), "int")
- self.assertEqual(self.obj.overload(3.14), "double")
-
- def testImplicitConvert(self):
- '''Overloads with implicit convertible types'''
- self.assertEqual(self.obj.overload(ImplicitTarget()), "ImplicitTarget")
- self.assertEqual(self.obj.overload(ImplicitBase()), "ImplicitBase")
-
- def testContainer(self):
- '''Overloads with containers arguments'''
- self.assertEqual(self.obj.overload([ImplicitBase()]), "list(ImplicitBase)")
-
- def testPyObject(self):
- '''Overloads with PyObject args'''
- self.assertEqual(self.obj.overload(Dummy()), "PyObject")
-
- def testImplicitOnly(self):
- '''Passing an implicit convertible object to an overload'''
- self.assertTrue(self.obj.implicit_overload(ImplicitTarget()))
-
- def testPyObjectSort(self):
- self.assertEqual(self.obj.pyObjOverload(1, 2), "int,int")
- self.assertEqual(self.obj.pyObjOverload(object(), 2), "PyObject,int")
-
-
-class DeepOverloadSorting(unittest.TestCase):
-
- def setUp(self):
- self.obj = SortedOverload()
-
- def testPyObject(self):
- '''Deep Overload - (int, PyObject *)'''
- self.assertEqual(self.obj.overloadDeep(1, Dummy()), "PyObject")
-
- def testImplicit(self):
- '''Deep Overload - (int, ImplicitBase *)'''
- self.assertEqual(self.obj.overloadDeep(1, ImplicitBase()), "ImplicitBase")
-
-class EnumOverIntSorting(unittest.TestCase):
- def testEnumOverInt(self):
- ic = ImplicitConv(ImplicitConv.CtorTwo)
- self.assertEqual(ic.ctorEnum(), ImplicitConv.CtorTwo)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/overload_test.py b/sources/shiboken2/tests/samplebinding/overload_test.py
deleted file mode 100644
index ab5230990..000000000
--- a/sources/shiboken2/tests/samplebinding/overload_test.py
+++ /dev/null
@@ -1,215 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for Overload class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import Echo, Overload, Point, PointF, Polygon, Rect, RectF, Size, Str
-
-
-def raisesWithErrorMessage(func, arguments, errorType, errorMsg):
- '''NOTE: Using 'try' because assertRaisesRegexp is not available
- to check the error message.'''
- try:
- func(*arguments)
- return False
- except Exception as err:
- if type(err) != TypeError:
- return False
- if not errorMsg in str(err):
- return False
- return True
-
-
-class OverloadTest(unittest.TestCase):
- '''Test case for Overload class'''
-
- def testOverloadMethod0(self):
- '''Check overloaded method call for signature "overloaded()".'''
- overload = Overload()
- self.assertEqual(overload.overloaded(), Overload.Function0)
-
- def testOverloadMethod1(self):
- '''Check overloaded method call for signature "overloaded(Size*)".'''
- overload = Overload()
- size = Size()
- self.assertEqual(overload.overloaded(size), Overload.Function1)
-
- def testOverloadMethod2(self):
- '''Check overloaded method call for signature "overloaded(Point*, ParamEnum)".'''
- overload = Overload()
- point = Point()
- self.assertEqual(overload.overloaded(point, Overload.Param1), Overload.Function2)
-
- def testOverloadMethod3(self):
- '''Check overloaded method call for signature "overloaded(const Point&)".'''
- overload = Overload()
- point = Point()
- self.assertEqual(overload.overloaded(point), Overload.Function3)
-
- def testDifferentReturnTypes(self):
- '''Check method calls for overloads with different return types.'''
- overload = Overload()
- self.assertEqual(overload.differentReturnTypes(), None)
- self.assertEqual(overload.differentReturnTypes(Overload.Param1), None)
- self.assertEqual(overload.differentReturnTypes(Overload.Param0, 13), 13)
-
- def testIntOverloads(self):
- overload = Overload()
- self.assertEqual(overload.intOverloads(2, 3), 2)
- self.assertEqual(overload.intOverloads(2, 4.5), 3)
- self.assertEqual(overload.intOverloads(Point(0, 0), 3), 1)
-
- def testIntDoubleOverloads(self):
- overload = Overload()
- self.assertEqual(overload.intDoubleOverloads(1, 2), Overload.Function0)
- self.assertEqual(overload.intDoubleOverloads(1, 2.0), Overload.Function0)
- self.assertEqual(overload.intDoubleOverloads(1.0, 2), Overload.Function1)
- self.assertEqual(overload.intDoubleOverloads(1.0, 2.0), Overload.Function1)
-
- def testWrapperIntIntOverloads(self):
- overload = Overload()
- self.assertEqual(overload.wrapperIntIntOverloads(Point(), 1, 2), Overload.Function0)
- self.assertEqual(overload.wrapperIntIntOverloads(Polygon(), 1, 2), Overload.Function1)
-
- def testDrawTextPointAndStr(self):
- overload = Overload()
- self.assertEqual(overload.drawText(Point(), Str()), Overload.Function0)
- self.assertEqual(overload.drawText(Point(), ''), Overload.Function0)
- self.assertEqual(overload.drawText(PointF(), Str()), Overload.Function1)
- self.assertEqual(overload.drawText(PointF(), ''), Overload.Function1)
-
- def testDrawTextRectIntStr(self):
- overload = Overload()
- self.assertEqual(overload.drawText(Rect(), 1, Str()), Overload.Function2)
- self.assertEqual(overload.drawText(Rect(), 1, ''), Overload.Function2)
- self.assertEqual(overload.drawText(RectF(), 1, Str()), Overload.Function3)
- self.assertEqual(overload.drawText(RectF(), 1, ''), Overload.Function3)
-
- def testDrawTextRectFStrEcho(self):
- overload = Overload()
- self.assertEqual(overload.drawText(RectF(), Str()), Overload.Function4)
- self.assertEqual(overload.drawText(RectF(), ''), Overload.Function4)
- self.assertEqual(overload.drawText(RectF(), Str(), Echo()), Overload.Function4)
- self.assertEqual(overload.drawText(RectF(), '', Echo()), Overload.Function4)
- self.assertEqual(overload.drawText(Rect(), Str()), Overload.Function4)
- self.assertEqual(overload.drawText(Rect(), ''), Overload.Function4)
- self.assertEqual(overload.drawText(Rect(), Str(), Echo()), Overload.Function4)
- self.assertEqual(overload.drawText(Rect(), '', Echo()), Overload.Function4)
-
- def testDrawTextIntIntStr(self):
- overload = Overload()
- self.assertEqual(overload.drawText(1, 2, Str()), Overload.Function5)
- self.assertEqual(overload.drawText(1, 2, ''), Overload.Function5)
-
- def testDrawTextIntIntIntIntStr(self):
- overload = Overload()
- self.assertEqual(overload.drawText(1, 2, 3, 4, 5, Str()), Overload.Function6)
- self.assertEqual(overload.drawText(1, 2, 3, 4, 5, ''), Overload.Function6)
-
- def testDrawText2IntIntIntIntStr(self):
- overload = Overload()
- self.assertEqual(overload.drawText2(1, 2, 3, 4, 5, Str()), Overload.Function6)
- self.assertEqual(overload.drawText2(1, 2, 3, 4, 5, ''), Overload.Function6)
- self.assertEqual(overload.drawText2(1, 2, 3, 4, 5), Overload.Function6)
- self.assertEqual(overload.drawText2(1, 2, 3, 4), Overload.Function6)
- self.assertEqual(overload.drawText2(1, 2, 3), Overload.Function6)
-
- def testDrawText3(self):
- overload = Overload()
- self.assertEqual(overload.drawText3(Str(), Str(), Str()), Overload.Function0)
- self.assertEqual(overload.drawText3('', '', ''), Overload.Function0)
- self.assertEqual(overload.drawText3(1, 2, 3, 4, 5), Overload.Function1)
- self.assertEqual(overload.drawText3(1, 2, 3, 4, 5), Overload.Function1)
-
- def testDrawText3Exception(self):
- overload = Overload()
- args = (Str(), Str(), Str(), 4, 5)
- result = raisesWithErrorMessage(overload.drawText3, args,
- TypeError, 'called with wrong argument types:')
- self.assertTrue(result)
-
- def testDrawText4(self):
- overload = Overload()
- self.assertEqual(overload.drawText4(1, 2, 3), Overload.Function0)
- self.assertEqual(overload.drawText4(1, 2, 3, 4, 5), Overload.Function1)
-
- def testAcceptSequence(self):
- # Overload.acceptSequence()
- overload = Overload()
- self.assertEqual(overload.acceptSequence(), Overload.Function0)
-
- def testAcceptSequenceIntInt(self):
- # Overload.acceptSequence(int,int)
- overload = Overload()
- self.assertEqual(overload.acceptSequence(1, 2), Overload.Function1)
-
- def testAcceptSequenceStrParamEnum(self):
- # Overload.acceptSequence(Str,Overload::ParamEnum)
- overload = Overload()
- self.assertEqual(overload.acceptSequence(''), Overload.Function2)
- self.assertEqual(overload.acceptSequence('', Overload.Param0), Overload.Function2)
- self.assertEqual(overload.acceptSequence(Str('')), Overload.Function2)
- self.assertEqual(overload.acceptSequence(Str(''), Overload.Param0), Overload.Function2)
-
- def testAcceptSequenceSize(self):
- # Overload.acceptSequence(Size)
- overload = Overload()
- self.assertEqual(overload.acceptSequence(Size()), Overload.Function3)
-
- def testAcceptSequenceStringList(self):
- # Overload.acceptSequence(const char**)
- overload = Overload()
- strings = ['line 1', 'line 2']
- self.assertEqual(overload.acceptSequence(strings), Overload.Function4)
- args = (['line 1', 2], )
- result = raisesWithErrorMessage(overload.acceptSequence, args,
- TypeError, 'The argument must be a sequence of strings.')
- self.assertTrue(result)
-
- def testAcceptSequencePyObject(self):
- # Overload.acceptSequence(void*)
- overload = Overload()
- class Foo(object):
- pass
- foo = Foo()
- self.assertEqual(overload.acceptSequence(foo), Overload.Function5)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/overloadwithdefault_test.py b/sources/shiboken2/tests/samplebinding/overloadwithdefault_test.py
deleted file mode 100644
index dbd318091..000000000
--- a/sources/shiboken2/tests/samplebinding/overloadwithdefault_test.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Overload, Str
-from py3kcompat import b
-
-class OverloadTest(unittest.TestCase):
-
- def testNoArgument(self):
- overload = Overload()
- self.assertEqual(overload.strBufferOverloads(), Overload.Function2)
-
- def testStrArgument(self):
- overload = Overload()
- self.assertEqual(overload.strBufferOverloads(Str('')), Overload.Function0)
- self.assertEqual(overload.strBufferOverloads(Str(''), ''), Overload.Function0)
- self.assertEqual(overload.strBufferOverloads(Str(''), '', False), Overload.Function0)
-
- def testStringArgumentAsStr(self):
- overload = Overload()
- self.assertEqual(overload.strBufferOverloads('', ''), Overload.Function0)
- self.assertEqual(overload.strBufferOverloads('', '', False), Overload.Function0)
-
- def testStringArgumentAsBuffer(self):
- overload = Overload()
- self.assertEqual(overload.strBufferOverloads(b'', 0), Overload.Function1)
-
- def testBufferArgument(self):
- overload = Overload()
- self.assertEqual(overload.strBufferOverloads(b(''), 0), Overload.Function1)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ownership_argument_invalidation_test.py b/sources/shiboken2/tests/samplebinding/ownership_argument_invalidation_test.py
deleted file mode 100644
index d96236c2c..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_argument_invalidation_test.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Wrapper validity tests for arguments.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Polygon, Point
-
-class WrapperValidityOfArgumentsTest(unittest.TestCase):
- '''Wrapper validity tests for arguments.'''
-
- def testInvalidArgumentToMethod(self):
- '''Call to method using invalidated Python wrapper as argument should raise RuntimeError.'''
- poly = Polygon()
- Polygon.stealOwnershipFromPython(poly)
- self.assertRaises(RuntimeError, Polygon.doublePolygonScale, poly)
-
- def testInvalidArgumentToConstructor(self):
- '''Call to constructor using invalidated Python wrapper as argument should raise RuntimeError.'''
- pt = Point(1, 2)
- Polygon.stealOwnershipFromPython(pt)
- self.assertRaises(RuntimeError, Polygon, pt)
-
- def testInvalidArgumentWithImplicitConversion(self):
- '''Call to method using invalidated Python wrapper to be implicitly converted should raise RuntimeError.'''
- pt = Point(1, 2)
- Polygon.stealOwnershipFromPython(pt)
- self.assertRaises(RuntimeError, Polygon.doublePolygonScale, pt)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ownership_delete_child_in_cpp_test.py b/sources/shiboken2/tests/samplebinding/ownership_delete_child_in_cpp_test.py
deleted file mode 100644
index 255f1fdb1..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_delete_child_in_cpp_test.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests for destroy a child object in C++'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType
-
-
-class DeleteChildInCpp(unittest.TestCase):
- '''Test case for destroying a child in c++'''
-
- def testDeleteChild(self):
- '''Delete child in C++ should invalidate child - using C++ wrapper'''
- parent = ObjectType()
- parent.setObjectName('parent')
- child = ObjectType(parent)
- child.setObjectName('child')
-
- parent.killChild('child')
- self.assertRaises(RuntimeError, child.objectName)
- self.assertEqual(parent.objectName(), 'parent')
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/ownership_delete_child_in_python_test.py b/sources/shiboken2/tests/samplebinding/ownership_delete_child_in_python_test.py
deleted file mode 100644
index 206a65ce9..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_delete_child_in_python_test.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests for deleting a child object in python'''
-
-import os
-import random
-import string
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType
-from py3kcompat import IS_PY3K
-
-if IS_PY3K:
- string.letters = string.ascii_letters
-
-
-class DeleteChildInPython(unittest.TestCase):
- '''Test case for deleting (unref) a child in python'''
-
- def testDeleteChild(self):
- '''Delete child in python should not invalidate child'''
- parent = ObjectType()
- child = ObjectType(parent)
- name = ''.join(random.sample(string.letters, 5))
- child.setObjectName(name)
-
- del child
- new_child = parent.children()[0]
- self.assertEqual(new_child.objectName(), name)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/ownership_delete_parent_test.py b/sources/shiboken2/tests/samplebinding/ownership_delete_parent_test.py
deleted file mode 100644
index 1b7de5f2f..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_delete_parent_test.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests for destroying the parent'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType
-
-
-class DeleteParentTest(unittest.TestCase):
- '''Test case for deleting a parent object'''
-
- def testParentDestructor(self):
- '''Delete parent object should invalidate child'''
- parent = ObjectType()
- child = ObjectType()
- child.setParent(parent)
-
- refcount_before = sys.getrefcount(child)
-
- del parent
- self.assertRaises(RuntimeError, child.objectName)
- self.assertEqual(sys.getrefcount(child), refcount_before-1)
-
- def testParentDestructorMultipleChildren(self):
- '''Delete parent object should invalidate all children'''
- parent = ObjectType()
- children = [ObjectType() for _ in range(10)]
-
- for child in children:
- child.setParent(parent)
-
- del parent
- for i, child in enumerate(children):
- self.assertRaises(RuntimeError, child.objectName)
- self.assertEqual(sys.getrefcount(child), 4)
-
- def testRecursiveParentDelete(self):
- '''Delete parent should invalidate grandchildren'''
- parent = ObjectType()
- child = ObjectType(parent)
- grandchild = ObjectType(child)
-
- del parent
- self.assertRaises(RuntimeError, child.objectName)
- self.assertEqual(sys.getrefcount(child), 2)
- self.assertRaises(RuntimeError, grandchild.objectName)
- self.assertEqual(sys.getrefcount(grandchild), 2)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/ownership_invalidate_after_use_test.py b/sources/shiboken2/tests/samplebinding/ownership_invalidate_after_use_test.py
deleted file mode 100644
index 10f1cf9ee..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_invalidate_after_use_test.py
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Ownership tests for cases of invalidation of Python wrapper after use.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType, ObjectTypeDerived, Event
-
-
-class ExtObjectType(ObjectType):
- def __init__(self):
- ObjectType.__init__(self)
- self.type_of_last_event = None
- self.last_event = None
- def event(self, event):
- self.last_event = event
- self.type_of_last_event = event.eventType()
- return True
-
-class MyObjectType (ObjectType):
- def __init__(self):
- super(MyObjectType, self).__init__()
- self.fail = False
-
- def event(self, ev):
- self.callInvalidateEvent(ev)
- try:
- ev.eventType()
- except:
- self.fail = True
- raise
- return True
-
- def invalidateEvent(self, ev):
- pass
-
-class ExtObjectTypeDerived(ObjectTypeDerived):
- def __init__(self):
- ObjectTypeDerived.__init__(self)
- self.type_of_last_event = None
- self.last_event = None
- def event(self, event):
- self.last_event = event
- self.type_of_last_event = event.eventType()
- return True
-
-class OwnershipInvalidateAfterUseTest(unittest.TestCase):
- '''Ownership tests for cases of invalidation of Python wrapper after use.'''
-
- def testInvalidateAfterUse(self):
- '''In ObjectType.event(Event*) the wrapper object created for Event must me marked as invalid after the method is called.'''
- eot = ExtObjectType()
- eot.causeEvent(Event.SOME_EVENT)
- self.assertEqual(eot.type_of_last_event, Event.SOME_EVENT)
- self.assertRaises(RuntimeError, eot.last_event.eventType)
-
- def testObjectInvalidatedAfterUseAsParameter(self):
- '''Tries to use wrapper invalidated after use as a parameter to another method.'''
- eot = ExtObjectType()
- ot = ObjectType()
- eot.causeEvent(Event.ANY_EVENT)
- self.assertEqual(eot.type_of_last_event, Event.ANY_EVENT)
- self.assertRaises(RuntimeError, ot.event, eot.last_event)
-
- def testit(self):
- obj = MyObjectType()
- obj.causeEvent(Event.BASIC_EVENT)
- self.assertFalse(obj.fail)
-
- def testInvalidateAfterUseInDerived(self):
- '''Invalidate was failing in a derived C++ class that also inherited
- other base classes'''
- eot = ExtObjectTypeDerived()
- eot.causeEvent(Event.SOME_EVENT)
- self.assertEqual(eot.type_of_last_event, Event.SOME_EVENT)
- self.assertRaises(RuntimeError, eot.last_event.eventType)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ownership_invalidate_child_test.py b/sources/shiboken2/tests/samplebinding/ownership_invalidate_child_test.py
deleted file mode 100644
index 9e6423e50..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_invalidate_child_test.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests for invalidating a C++ created child that was already on the care of a parent.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType, BlackBox
-
-
-class InvalidateChildTest(unittest.TestCase):
- '''Tests for invalidating a C++ created child that was already on the care of a parent.'''
-
- def testInvalidateChild(self):
- '''Invalidating method call should remove child from the care of a parent if it has one.'''
- parent = ObjectType()
- child1 = ObjectType(parent)
- child1.setObjectName('child1')
- child2 = ObjectType.create()
- child2.setParent(parent)
- child2.setObjectName('child2')
-
- self.assertEqual(parent.children(), [child1, child2])
-
- bbox = BlackBox()
-
- # This method steals ownership from Python to C++.
- bbox.keepObjectType(child1)
- self.assertEqual(parent.children(), [child2])
-
- bbox.keepObjectType(child2)
- self.assertEqual(parent.children(), [])
-
- del parent
-
- self.assertEqual(child1.objectName(), 'child1')
- self.assertRaises(RuntimeError, child2.objectName)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ownership_invalidate_nonpolymorphic_test.py b/sources/shiboken2/tests/samplebinding/ownership_invalidate_nonpolymorphic_test.py
deleted file mode 100644
index 18fce3809..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_invalidate_nonpolymorphic_test.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''The BlackBox class has cases of ownership transference between Python and C++.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Point, BlackBox
-
-class OwnershipInvalidateNonPolymorphicTest(unittest.TestCase):
- '''The BlackBox class has cases of ownership transference between Python and C++.'''
-
- def testOwnershipTransference(self):
- '''Ownership transference from Python to C++ and back again.'''
- p1 = Point(10, 20)
- bb = BlackBox()
- p1_ticket = bb.keepPoint(p1)
- self.assertRaises(RuntimeError, p1.x)
- p1_ret = bb.retrievePoint(p1_ticket)
- self.assertEqual(p1_ret, Point(10, 20))
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ownership_invalidate_parent_test.py b/sources/shiboken2/tests/samplebinding/ownership_invalidate_parent_test.py
deleted file mode 100644
index 2d7e67deb..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_invalidate_parent_test.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests for invalidating a parent of other objects.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType, BlackBox
-
-
-class InvalidateParentTest(unittest.TestCase):
- '''Tests for invalidating a parent of other objects.'''
-
- def testInvalidateParent(self):
- '''Invalidate parent should invalidate children'''
- parent = ObjectType.create()
- child1 = ObjectType(parent)
- child1.setObjectName("child1")
- child2 = ObjectType.create()
- child2.setObjectName("child2")
- child2.setParent(parent)
- grandchild1 = ObjectType(child1)
- grandchild1.setObjectName("grandchild1")
- grandchild2 = ObjectType.create()
- grandchild2.setObjectName("grandchild2")
- grandchild2.setParent(child2)
- bbox = BlackBox()
-
- bbox.keepObjectType(parent) # Should invalidate the parent
-
- self.assertRaises(RuntimeError, parent.objectName)
- # some children still valid they are wrapper classes
- self.assertEqual(child1.objectName(), "child1")
- self.assertRaises(RuntimeError, child2.objectName)
- self.assertEqual(grandchild1.objectName(), "grandchild1")
- self.assertRaises(RuntimeError, grandchild2.objectName)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ownership_reparenting_test.py b/sources/shiboken2/tests/samplebinding/ownership_reparenting_test.py
deleted file mode 100644
index 217566996..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_reparenting_test.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests for object reparenting.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import sys
-
-from sample import ObjectType
-
-class ExtObjectType(ObjectType):
- def __init__(self):
- ObjectType.__init__(self)
-
-
-class ReparentingTest(unittest.TestCase):
- '''Tests for object reparenting.'''
-
- def testReparentedObjectTypeIdentity(self):
- '''Reparent children from one parent to another.'''
- object_list = []
- old_parent = ObjectType()
- new_parent = ObjectType()
- for i in range(3):
- obj = ObjectType()
- object_list.append(obj)
- obj.setParent(old_parent)
- for obj in object_list:
- obj.setParent(new_parent)
- for child in new_parent.children():
- self.assertTrue(child in object_list)
-
- def testReparentWithTheSameParent(self):
- '''Set the same parent twice to check if the ref continue the same'''
- obj = ObjectType()
- parent = ObjectType()
- self.assertEqual(sys.getrefcount(obj), 2)
- obj.setParent(parent)
- self.assertEqual(sys.getrefcount(obj), 3)
- obj.setParent(parent)
- self.assertEqual(sys.getrefcount(obj), 3)
-
- def testReparentedExtObjectType(self):
- '''Reparent children from one extended parent to another.'''
- object_list = []
- old_parent = ExtObjectType()
- new_parent = ExtObjectType()
- for i in range(3):
- obj = ExtObjectType()
- object_list.append(obj)
- obj.setParent(old_parent)
- for obj in object_list:
- obj.setParent(new_parent)
- for orig, child in zip(object_list, new_parent.children()):
- self.assertEqual(type(orig), type(child))
-
- def testReparentedObjectTypeIdentityWithParentsCreatedInCpp(self):
- '''Reparent children from one parent to another, both created in C++.'''
- object_list = []
- old_parent = ObjectType.create()
- new_parent = ObjectType.create()
- for i in range(3):
- obj = ObjectType()
- object_list.append(obj)
- obj.setParent(old_parent)
- for obj in object_list:
- obj.setParent(new_parent)
- for child in new_parent.children():
- self.assertTrue(child in object_list)
-
- def testReparentedObjectTypeIdentityWithChildrenCreatedInCpp(self):
- '''Reparent children created in C++ from one parent to another.'''
- object_list = []
- old_parent = ObjectType()
- new_parent = ObjectType()
- for i in range(3):
- obj = ObjectType.create()
- object_list.append(obj)
- obj.setParent(old_parent)
- for obj in object_list:
- obj.setParent(new_parent)
- for child in new_parent.children():
- self.assertTrue(child in object_list)
-
- def testReparentedObjectTypeIdentityWithParentsAndChildrenCreatedInCpp(self):
- '''Reparent children from one parent to another. Parents and children are created in C++.'''
- object_list = []
- old_parent = ObjectType.create()
- new_parent = ObjectType.create()
- for i in range(3):
- obj = ObjectType.create()
- object_list.append(obj)
- obj.setParent(old_parent)
- for obj in object_list:
- obj.setParent(new_parent)
- for child in new_parent.children():
- self.assertTrue(child in object_list)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/ownership_transference_test.py b/sources/shiboken2/tests/samplebinding/ownership_transference_test.py
deleted file mode 100644
index 1a783458e..000000000
--- a/sources/shiboken2/tests/samplebinding/ownership_transference_test.py
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''The BlackBox class has cases of ownership transference between C++ and Python.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType, BlackBox
-
-class BlackBoxTest(unittest.TestCase):
- '''The BlackBox class has cases of ownership transference between C++ and Python.'''
-
- def testOwnershipTransference(self):
- '''Ownership transference from Python to C++ and back again.'''
- o1 = ObjectType()
- o1.setObjectName('object1')
- o1_refcnt = sys.getrefcount(o1)
- o2 = ObjectType()
- o2.setObjectName('object2')
- o2_refcnt = sys.getrefcount(o2)
- bb = BlackBox()
- o1_ticket = bb.keepObjectType(o1)
- o2_ticket = bb.keepObjectType(o2)
- self.assertEqual(set(bb.objects()), set([o1, o2]))
- self.assertEqual(str(o1.objectName()), 'object1')
- self.assertEqual(str(o2.objectName()), 'object2')
- self.assertEqual(sys.getrefcount(o1), o1_refcnt + 1) # PySide give +1 ref to object with c++ ownership
- self.assertEqual(sys.getrefcount(o2), o2_refcnt + 1)
- o2 = bb.retrieveObjectType(o2_ticket)
- self.assertEqual(sys.getrefcount(o2), o2_refcnt)
- del bb
- self.assertRaises(RuntimeError, o1.objectName)
- self.assertEqual(str(o2.objectName()), 'object2')
- self.assertEqual(sys.getrefcount(o2), o2_refcnt)
-
- def testBlackBoxReleasingUnknownObjectType(self):
- '''Asks BlackBox to release an unknown ObjectType.'''
- o1 = ObjectType()
- o2 = ObjectType()
- bb = BlackBox()
- o1_ticket = bb.keepObjectType(o1)
- o3 = bb.retrieveObjectType(-5)
- self.assertEqual(o3, None)
-
- def testOwnershipTransferenceCppCreated(self):
- '''Ownership transference using a C++ created object.'''
- o1 = ObjectType.create()
- o1.setObjectName('object1')
- o1_refcnt = sys.getrefcount(o1)
- bb = BlackBox()
- o1_ticket = bb.keepObjectType(o1)
- self.assertRaises(RuntimeError, o1.objectName)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/pair_test.py b/sources/shiboken2/tests/samplebinding/pair_test.py
deleted file mode 100644
index 65fd9b99c..000000000
--- a/sources/shiboken2/tests/samplebinding/pair_test.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for std::pair container conversions'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import PairUser
-
-class ExtendedPairUser(PairUser):
- def __init__(self):
- PairUser.__init__(self)
- self.create_pair_called = False
-
- def createPair(self):
- self.create_pair_called = True
- return (7, 13)
-
-class PairConversionTest(unittest.TestCase):
- '''Test case for std::pair container conversions'''
-
- def testReimplementedVirtualMethodCall(self):
- '''Test if a Python override of a virtual method is correctly called from C++.'''
- pu = ExtendedPairUser()
- pair = pu.callCreatePair()
- self.assertTrue(pu.create_pair_called)
- self.assertEqual(type(pair), tuple)
- self.assertEqual(type(pair[0]), int)
- self.assertEqual(type(pair[1]), int)
- self.assertEqual(pair, (7, 13))
-
- def testPrimitiveConversionInsideContainer(self):
- '''Test primitive type conversion inside conversible std::pair container.'''
- cpx0 = complex(1.2, 3.4)
- cpx1 = complex(5.6, 7.8)
- cp = PairUser.createComplexPair(cpx0, cpx1)
- self.assertEqual(type(cp), tuple)
- self.assertEqual(type(cp[0]), complex)
- self.assertEqual(type(cp[1]), complex)
- self.assertEqual(cp, (cpx0, cpx1))
-
- def testSumPair(self):
- '''Test method that sums the items of a pair using values of the types expected by C++ (int and double)'''
- pu = PairUser()
- pair = (3, 7.13)
- result = pu.sumPair(pair)
- self.assertEqual(result, sum(pair))
-
- def testSumPairDifferentTypes(self):
- '''Test method that sums the items of a pair using values of types different from the ones expected by C++ (int and double)'''
- pu = PairUser()
- pair = (3.3, 7)
- result = pu.sumPair(pair)
- self.assertNotEqual(result, sum(pair))
- self.assertEqual(result, int(pair[0]) + pair[1])
-
- def testConversionInBothDirections(self):
- '''Test converting a pair from Python to C++ and the other way around.'''
- pu = PairUser()
- pair = (3, 5)
- pu.setPair(pair)
- result = pu.getPair()
- self.assertEqual(result, pair)
-
- def testConversionInBothDirectionsWithSimilarContainer(self):
- '''Test converting a list, instead of the expected tuple, from Python to C++ and the other way around.'''
- pu = PairUser()
- pair = [3, 5]
- pu.setPair(pair)
- result = pu.getPair()
- self.assertNotEqual(result, pair)
- self.assertEqual(result, tuple(pair))
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/pen_test.py b/sources/shiboken2/tests/samplebinding/pen_test.py
deleted file mode 100644
index 408871bb3..000000000
--- a/sources/shiboken2/tests/samplebinding/pen_test.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for <add-function> with const char* as argument'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Color, Pen, SampleNamespace
-
-class TestPen(unittest.TestCase):
- '''Simple test case for Pen.'''
-
- def testPenWithEmptyConstructor(self):
- pen = Pen()
- self.assertEqual(pen.ctorType(), Pen.EmptyCtor)
-
- def testPenWithEnumConstructor(self):
- pen = Pen(SampleNamespace.RandomNumber)
- self.assertEqual(pen.ctorType(), Pen.EnumCtor)
-
- def testPenWithColorConstructor(self):
- pen = Pen(Color())
- self.assertEqual(pen.ctorType(), Pen.ColorCtor)
-
- def testPenWithCopyConstructor(self):
- pen = Pen(Pen())
- self.assertEqual(pen.ctorType(), Pen.CopyCtor)
-
- def testPenWithIntConvertedToColor(self):
- pen = Pen(1)
- self.assertEqual(pen.ctorType(), Pen.ColorCtor)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/point_test.py b/sources/shiboken2/tests/samplebinding/point_test.py
deleted file mode 100644
index e2beb78ae..000000000
--- a/sources/shiboken2/tests/samplebinding/point_test.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for Point class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Point
-from py3kcompat import unicode
-
-class PointTest(unittest.TestCase):
- '''Test case for Point class, including operator overloads.'''
-
- def testConstructor(self):
- '''Test Point class constructor.'''
- pt = Point(5.0, 2.3)
- self.assertEqual(pt.x(), 5.0)
- self.assertEqual(pt.y(), 2.3)
-
- def testPlusOperator(self):
- '''Test Point class + operator.'''
- pt1 = Point(5.0, 2.3)
- pt2 = Point(0.5, 3.2)
- self.assertEqual(pt1 + pt2, Point(5.0 + 0.5, 2.3 + 3.2))
-
- def testEqualOperator(self):
- '''Test Point class == operator.'''
- pt1 = Point(5.0, 2.3)
- pt2 = Point(5.0, 2.3)
- pt3 = Point(0.5, 3.2)
- self.assertTrue(pt1 == pt1)
- self.assertTrue(pt1 == pt2)
- self.assertFalse(pt1 == pt3)
- self.assertFalse(pt1 == object())
-
- def testNotEqualOperator(self):
- '''Test Point class != operator.'''
- pt1 = Point(5.0, 2.3)
- pt2 = Point(5.0, 2.3)
- self.assertRaises(NotImplementedError, pt1.__ne__, pt2)
-
- def testReturnNewCopy(self):
- '''Point returns a copy of itself.'''
- pt1 = Point(1.1, 2.3)
- pt2 = pt1.copy()
- self.assertEqual(pt1, pt2)
- pt2 += pt1
- self.assertFalse(pt1 == pt2)
-
- def testReturnConstPointer(self):
- '''Point returns a const pointer for itself.'''
- pt1 = Point(5.0, 2.3)
- refcount1 = sys.getrefcount(pt1)
- pt2 = pt1.getSelf()
- self.assertEqual(pt1, pt2)
- self.assertEqual(sys.getrefcount(pt1), refcount1 + 1)
- self.assertEqual(sys.getrefcount(pt1), sys.getrefcount(pt2))
-
- def testUintOverflow(self):
- pt1 = Point(0.0, 0.0)
- self.assertRaises(OverflowError, pt1.setXAsUint, 840835495615213080)
- self.assertEqual(pt1.x(), 0.0)
-
- def testAddedOperator(self):
- p = Point(0.0, 0.0)
- r = p - unicode('Hi')
- self.assertEqual(r, unicode('Hi'))
-
- # now the reverse op.
- r = unicode('Hi') - p
- self.assertEqual(r, unicode('Hi'))
-
- def testModifiedMethod(self):
- pt1 = Point(0.0, 0.0)
- pt2 = Point(10.0, 10.0)
- expected = Point((pt1.x() + pt2.x()) / 2.0, (pt1.y() + pt2.y()) / 2.0)
- self.assertEqual(pt1.midpoint(pt2), expected)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/pointerholder_test.py b/sources/shiboken2/tests/samplebinding/pointerholder_test.py
deleted file mode 100644
index b79eaa33a..000000000
--- a/sources/shiboken2/tests/samplebinding/pointerholder_test.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for a class that holds an arbitraty pointer and is modified to hold an PyObject.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import PointerHolder
-
-class TestPointerHolder(unittest.TestCase):
- '''Test cases for a class that holds an arbitraty pointer and is modified to hold an PyObject.'''
-
- def testStoringAndRetrievingPointer(self):
- ph = PointerHolder('Hello')
- self.assertEqual(ph.pointer(), 'Hello')
- a = (1, 2, 3)
- ph = PointerHolder(a)
- self.assertEqual(ph.pointer(), a)
-
- def testReferenceCounting(self):
- '''Test reference counting when retrieving data with PointerHolder.pointer().'''
- a = (1, 2, 3)
- refcnt = sys.getrefcount(a)
- ph = PointerHolder(a)
- ptr = ph.pointer()
- self.assertEqual(sys.getrefcount(a), refcnt + 1)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/pointerprimitivetype_test.py b/sources/shiboken2/tests/samplebinding/pointerprimitivetype_test.py
deleted file mode 100644
index 532f2226c..000000000
--- a/sources/shiboken2/tests/samplebinding/pointerprimitivetype_test.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-"""
-pointerprimitivetype_test.py
-
-check that the primitive types are correctly mapped by the signature module.
-
-Mapping
--------
-IntArray2(const int*) -- <Signature (self, data: typing.Sequence)>
-getMargins(int*,int*,int*,int*)const -- <Signature (self) -> typing.Tuple[int, int, int, int]>
-
-We explicitly check only against typing.Iterable in the first test,
-because typing.Sequence is a subclass, but we will generalize this
-to typing.Iterable in the future.
-"""
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import IntArray2, VirtualMethods
-
-import shiboken2
-type.__signature__ # trigger init, which does not happen in tests
-from shibokensupport.signature import typing
-
-
-class PointerPrimitiveTypeTest(unittest.TestCase):
-
- def testArraySignature(self):
- # signature="IntArray2(const int*)"
- found = False
- for sig in IntArray2.__signature__:
- if "data" in sig.parameters:
- found = True
- break
- self.assertTrue(found)
- ann = sig.parameters["data"].annotation
- self.assertEqual(ann.__args__, (int,))
- # un-specify this class (forget "int") by setting the _special
- # flag, so we can check using issubclass (undocumented feature).
- ann._special = True
- self.assertTrue(issubclass(ann, typing.Iterable))
-
- def testReturnVarSignature(self):
- # signature="getMargins(int*,int*,int*,int*)const">
- ann = VirtualMethods.getMargins.__signature__.return_annotation
- self.assertEqual(ann, typing.Tuple[int, int, int, int])
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/pointf_test.py b/sources/shiboken2/tests/samplebinding/pointf_test.py
deleted file mode 100644
index e9630fe40..000000000
--- a/sources/shiboken2/tests/samplebinding/pointf_test.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for PointF class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import PointF
-
-class PointFTest(unittest.TestCase):
- '''Test case for PointF class, including operator overloads.'''
-
- def testConstructor(self):
- '''Test PointF class constructor.'''
- pt = PointF(5.0, 2.3)
- self.assertEqual(pt.x(), 5.0)
- self.assertEqual(pt.y(), 2.3)
-
- def testPlusOperator(self):
- '''Test PointF class + operator.'''
- pt1 = PointF(5.0, 2.3)
- pt2 = PointF(0.5, 3.2)
- self.assertEqual(pt1 + pt2, PointF(5.0 + 0.5, 2.3 + 3.2))
-
- def testEqualOperator(self):
- '''Test PointF class == operator.'''
- pt1 = PointF(5.0, 2.3)
- pt2 = PointF(5.0, 2.3)
- pt3 = PointF(0.5, 3.2)
- self.assertTrue(pt1 == pt1)
- self.assertTrue(pt1 == pt2)
- self.assertFalse(pt1 == pt3)
-
- def testModifiedMethod(self):
- pt1 = PointF(0.0, 0.0)
- pt2 = PointF(10.0, 10.0)
- expected = PointF((pt1.x() + pt2.x()) / 2.0, (pt1.y() + pt2.y()) / 2.0)
- self.assertEqual(pt1.midpoint(pt2), expected)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/primitivereferenceargument_test.py b/sources/shiboken2/tests/samplebinding/primitivereferenceargument_test.py
deleted file mode 100644
index 95c210b23..000000000
--- a/sources/shiboken2/tests/samplebinding/primitivereferenceargument_test.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import sample
-
-class PrimitiveReferenceArgumentTest(unittest.TestCase):
-
- def testIntReferenceArgument(self):
- '''C++ signature: int acceptIntReference(int&)'''
- self.assertEqual(sample.acceptIntReference(123), 123)
-
- def testOddBoolReferenceArgument(self):
- '''C++ signature: OddBool acceptOddBoolReference(OddBool&)'''
- self.assertEqual(sample.acceptOddBoolReference(True), True)
- self.assertEqual(sample.acceptOddBoolReference(False), False)
- self.assertNotEqual(sample.acceptOddBoolReference(True), False)
- self.assertNotEqual(sample.acceptOddBoolReference(False), True)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/privatector_test.py b/sources/shiboken2/tests/samplebinding/privatector_test.py
deleted file mode 100644
index 7dc3d6651..000000000
--- a/sources/shiboken2/tests/samplebinding/privatector_test.py
+++ /dev/null
@@ -1,89 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for a class with only a private constructor.'''
-
-import gc
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import PrivateCtor
-
-
-class PrivateCtorTest(unittest.TestCase):
- '''Test case for PrivateCtor class'''
-
- def testPrivateCtorInstanciation(self):
- '''Test if instanciation of class with a private constructor raises an exception.'''
- self.assertRaises(TypeError, PrivateCtor)
-
- def testPrivateCtorInheritance(self):
- '''Test if inheriting from PrivateCtor raises an exception.'''
- def inherit():
- class Foo(PrivateCtor):
- pass
- self.assertRaises(TypeError, inherit)
-
- def testPrivateCtorInstanceMethod(self):
- '''Test if PrivateCtor.instance() method return the proper singleton.'''
- pd1 = PrivateCtor.instance()
- calls = pd1.instanceCalls()
- self.assertEqual(type(pd1), PrivateCtor)
- pd2 = PrivateCtor.instance()
- self.assertEqual(pd2, pd1)
- self.assertEqual(pd2.instanceCalls(), calls + 1)
-
- def testPrivateCtorRefCounting(self):
- '''Test refcounting of the singleton returned by PrivateCtor.instance().'''
- pd1 = PrivateCtor.instance()
- calls = pd1.instanceCalls()
- refcnt = sys.getrefcount(pd1)
- pd2 = PrivateCtor.instance()
- self.assertEqual(pd2.instanceCalls(), calls + 1)
- self.assertEqual(sys.getrefcount(pd2), sys.getrefcount(pd1))
- self.assertEqual(sys.getrefcount(pd2), refcnt + 1)
- del pd1
- self.assertEqual(sys.getrefcount(pd2), refcnt)
- del pd2
- gc.collect()
- pd3 = PrivateCtor.instance()
- self.assertEqual(type(pd3), PrivateCtor)
- self.assertEqual(pd3.instanceCalls(), calls + 2)
- self.assertEqual(sys.getrefcount(pd3), refcnt)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/privatedtor_test.py b/sources/shiboken2/tests/samplebinding/privatedtor_test.py
deleted file mode 100644
index 97d034729..000000000
--- a/sources/shiboken2/tests/samplebinding/privatedtor_test.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for a class with a private destructor.'''
-
-import gc
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import shiboken2 as shiboken
-from sample import PrivateDtor
-
-
-class PrivateDtorTest(unittest.TestCase):
- '''Test case for PrivateDtor class'''
-
- def testPrivateDtorInstanciation(self):
- '''Test if instanciation of class with a private destructor raises an exception.'''
- self.assertRaises(TypeError, PrivateDtor)
-
- def testPrivateDtorInheritance(self):
- '''Test if inheriting from PrivateDtor raises an exception.'''
- def inherit():
- class Foo(PrivateDtor):
- pass
- self.assertRaises(TypeError, inherit)
-
- def testPrivateDtorInstanceMethod(self):
- '''Test if PrivateDtor.instance() method return the proper singleton.'''
- pd1 = PrivateDtor.instance()
- calls = pd1.instanceCalls()
- self.assertEqual(type(pd1), PrivateDtor)
- pd2 = PrivateDtor.instance()
- self.assertEqual(pd2, pd1)
- self.assertEqual(pd2.instanceCalls(), calls + 1)
-
- def testPrivateDtorRefCounting(self):
- '''Test refcounting of the singleton returned by PrivateDtor.instance().'''
- pd1 = PrivateDtor.instance()
- calls = pd1.instanceCalls()
- refcnt = sys.getrefcount(pd1)
- pd2 = PrivateDtor.instance()
- self.assertEqual(pd2.instanceCalls(), calls + 1)
- self.assertEqual(sys.getrefcount(pd2), sys.getrefcount(pd1))
- self.assertEqual(sys.getrefcount(pd2), refcnt + 1)
- del pd1
- self.assertEqual(sys.getrefcount(pd2), refcnt)
- del pd2
- gc.collect()
- pd3 = PrivateDtor.instance()
- self.assertEqual(type(pd3), PrivateDtor)
- self.assertEqual(pd3.instanceCalls(), calls + 2)
- self.assertEqual(sys.getrefcount(pd3), refcnt)
-
- def testClassDecref(self):
- # Bug was that class PyTypeObject wasn't decrefed when instance
- # was invalidated
-
- before = sys.getrefcount(PrivateDtor)
-
- for i in range(1000):
- obj = PrivateDtor.instance()
- shiboken.invalidate(obj)
-
- after = sys.getrefcount(PrivateDtor)
-
- self.assertLess(abs(before - after), 5)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/protected_test.py b/sources/shiboken2/tests/samplebinding/protected_test.py
deleted file mode 100644
index 0cfc69b12..000000000
--- a/sources/shiboken2/tests/samplebinding/protected_test.py
+++ /dev/null
@@ -1,363 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for protected methods.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import cacheSize
-from sample import ProtectedNonPolymorphic, ProtectedVirtualDestructor
-from sample import ProtectedPolymorphic, ProtectedPolymorphicDaughter, ProtectedPolymorphicGrandDaughter
-from sample import createProtectedProperty, ProtectedProperty, ProtectedEnumClass
-from sample import PrivateDtor
-from sample import Event, ObjectType, Point
-
-class ExtendedProtectedPolymorphic(ProtectedPolymorphic):
- def __init__(self, name):
- ProtectedPolymorphic.__init__(self, name)
- self.protectedName_called = False
- def protectedName(self):
- self.protectedName_called = True
- self._name = 'Extended' + ProtectedPolymorphic.protectedName(self)
- return self._name
-
-class ExtendedProtectedPolymorphicDaughter(ProtectedPolymorphicDaughter):
- def __init__(self, name):
- self.protectedName_called = False
- ProtectedPolymorphicDaughter.__init__(self, name)
- def protectedName(self):
- self.protectedName_called = True
- self._name = 'ExtendedDaughter' + ProtectedPolymorphicDaughter.protectedName(self)
- return self._name
-
-class ExtendedProtectedPolymorphicGrandDaughter(ProtectedPolymorphicGrandDaughter):
- def __init__(self, name):
- self.protectedName_called = False
- ProtectedPolymorphicGrandDaughter.__init__(self, name)
- def protectedName(self):
- self.protectedName_called = True
- self._name = 'ExtendedGrandDaughter' + ProtectedPolymorphicGrandDaughter.protectedName(self)
- return self._name
-
-class ExtendedProtectedVirtualDestructor(ProtectedVirtualDestructor):
- def __init__(self):
- ProtectedVirtualDestructor.__init__(self)
-
-class ProtectedNonPolymorphicTest(unittest.TestCase):
- '''Test cases for protected method in a class without virtual methods.'''
-
- def tearDown(self):
- self.assertEqual(cacheSize(), 0)
-
- def testProtectedCall(self):
- '''Calls a non-virtual protected method.'''
- p = ProtectedNonPolymorphic('NonPoly')
- self.assertEqual(p.publicName(), p.protectedName())
- a0, a1 = 1, 2
- self.assertEqual(p.protectedSum(a0, a1), a0 + a1)
-
- def testProtectedCallWithInstanceCreatedOnCpp(self):
- '''Calls a non-virtual protected method on an instance created in C++.'''
- p = ProtectedNonPolymorphic.create()
- self.assertEqual(p.publicName(), p.protectedName())
- a0, a1 = 1, 2
- self.assertEqual(p.protectedSum(a0, a1), a0 + a1)
-
- def testModifiedProtectedCall(self):
- '''Calls a non-virtual protected method modified with code injection.'''
- p = ProtectedNonPolymorphic('NonPoly')
- self.assertEqual(p.dataTypeName(), 'integer')
- self.assertEqual(p.dataTypeName(1), 'integer')
- self.assertEqual(p.dataTypeName(Point(1, 2)), 'pointer')
-
-class ProtectedPolymorphicTest(unittest.TestCase):
- '''Test cases for protected method in a class with virtual methods.'''
-
- def tearDown(self):
- self.assertEqual(cacheSize(), 0)
-
- def testProtectedCall(self):
- '''Calls a virtual protected method.'''
- p = ProtectedNonPolymorphic('Poly')
- self.assertEqual(p.publicName(), p.protectedName())
- a0, a1 = 1, 2
- self.assertEqual(p.protectedSum(a0, a1), a0 + a1)
-
- def testProtectedCallWithInstanceCreatedOnCpp(self):
- '''Calls a virtual protected method on an instance created in C++.'''
- p = ProtectedPolymorphic.create()
- self.assertEqual(p.publicName(), p.protectedName())
- self.assertEqual(p.callProtectedName(), p.protectedName())
-
- def testReimplementedProtectedCall(self):
- '''Calls a reimplemented virtual protected method.'''
- original_name = 'Poly'
- p = ExtendedProtectedPolymorphic(original_name)
- name = p.callProtectedName()
- self.assertTrue(p.protectedName_called)
- self.assertEqual(p.protectedName(), name)
- self.assertEqual(ProtectedPolymorphic.protectedName(p), original_name)
-class ProtectedPolymorphicDaugherTest(unittest.TestCase):
- '''Test cases for protected method in a class inheriting for a class with virtual methods.'''
-
- def testProtectedCallWithInstanceCreatedOnCpp(self):
- '''Calls a virtual protected method from parent class on an instance created in C++.'''
- p = ProtectedPolymorphicDaughter.create()
- self.assertEqual(p.publicName(), p.protectedName())
- self.assertEqual(p.callProtectedName(), p.protectedName())
-
- def testReimplementedProtectedCall(self):
- '''Calls a reimplemented virtual protected method from parent class.'''
- original_name = 'Poly'
- p = ExtendedProtectedPolymorphicDaughter(original_name)
- name = p.callProtectedName()
- self.assertTrue(p.protectedName_called)
- self.assertEqual(p.protectedName(), name)
- self.assertEqual(ProtectedPolymorphicDaughter.protectedName(p), original_name)
-
-
-class ProtectedPolymorphicGrandDaugherTest(unittest.TestCase):
- '''Test cases for protected method in a class inheriting for a class that inherits from
- another with protected virtual methods.'''
-
- def tearDown(self):
- self.assertEqual(cacheSize(), 0)
-
- def testProtectedCallWithInstanceCreatedOnCpp(self):
- '''Calls a virtual protected method from parent class on an instance created in C++.'''
- p = ProtectedPolymorphicGrandDaughter.create()
- self.assertEqual(p.publicName(), p.protectedName())
- self.assertEqual(p.callProtectedName(), p.protectedName())
-
- def testReimplementedProtectedCall(self):
- '''Calls a reimplemented virtual protected method from parent class.'''
- original_name = 'Poly'
- p = ExtendedProtectedPolymorphicGrandDaughter(original_name)
- name = p.callProtectedName()
- self.assertTrue(p.protectedName_called)
- self.assertEqual(p.protectedName(), name)
- self.assertEqual(ProtectedPolymorphicGrandDaughter.protectedName(p), original_name)
-
-class ProtectedVirtualDtorTest(unittest.TestCase):
- '''Test cases for protected virtual destructor.'''
-
- def setUp(self):
- ProtectedVirtualDestructor.resetDtorCounter()
-
- def tearDown(self):
- self.assertEqual(cacheSize(), 0)
-
- def testVirtualProtectedDtor(self):
- '''Original protected virtual destructor is being called.'''
- dtor_called = ProtectedVirtualDestructor.dtorCalled()
- for i in range(1, 10):
- pvd = ProtectedVirtualDestructor()
- del pvd
- self.assertEqual(ProtectedVirtualDestructor.dtorCalled(), dtor_called + i)
-
- def testVirtualProtectedDtorOnCppCreatedObject(self):
- '''Original protected virtual destructor is being called for a C++ created object.'''
- dtor_called = ProtectedVirtualDestructor.dtorCalled()
- for i in range(1, 10):
- pvd = ProtectedVirtualDestructor.create()
- del pvd
- self.assertEqual(ProtectedVirtualDestructor.dtorCalled(), dtor_called + i)
-
- def testProtectedDtorOnDerivedClass(self):
- '''Original protected virtual destructor is being called for a derived class.'''
- dtor_called = ExtendedProtectedVirtualDestructor.dtorCalled()
- for i in range(1, 10):
- pvd = ExtendedProtectedVirtualDestructor()
- del pvd
- self.assertEqual(ExtendedProtectedVirtualDestructor.dtorCalled(), dtor_called + i)
-
-
-class ExtendedProtectedEnumClass(ProtectedEnumClass):
- def __init__(self):
- ProtectedEnumClass.__init__(self)
- def protectedEnumMethod(self, value):
- if value == ProtectedEnumClass.ProtectedItem0:
- return ProtectedEnumClass.ProtectedItem1
- return ProtectedEnumClass.ProtectedItem0
- def publicEnumMethod(self, value):
- if value == ProtectedEnumClass.PublicItem0:
- return ProtectedEnumClass.PublicItem1
- return ProtectedEnumClass.PublicItem0
-
-class ProtectedEnumTest(unittest.TestCase):
- '''Test cases for protected enum.'''
-
- def tearDown(self):
- self.assertEqual(cacheSize(), 0)
-
- def testProtectedMethodWithProtectedEnumArgument(self):
- '''Calls protected method with protected enum argument.'''
- obj = ProtectedEnumClass()
-
- self.assertEqual(type(ProtectedEnumClass.ProtectedItem0), ProtectedEnumClass.ProtectedEnum)
-
- self.assertEqual(obj.protectedEnumMethod(ProtectedEnumClass.ProtectedItem0), ProtectedEnumClass.ProtectedItem0)
- self.assertEqual(obj.protectedEnumMethod(ProtectedEnumClass.ProtectedItem1), ProtectedEnumClass.ProtectedItem1)
-
- self.assertEqual(obj.callProtectedEnumMethod(ProtectedEnumClass.ProtectedItem0), ProtectedEnumClass.ProtectedItem0)
- self.assertEqual(obj.callProtectedEnumMethod(ProtectedEnumClass.ProtectedItem1), ProtectedEnumClass.ProtectedItem1)
-
- def testProtectedMethodWithPublicEnumArgument(self):
- '''Calls protected method with public enum argument.'''
- obj = ProtectedEnumClass()
-
- self.assertEqual(obj.publicEnumMethod(ProtectedEnumClass.PublicItem0), ProtectedEnumClass.PublicItem0)
- self.assertEqual(obj.publicEnumMethod(ProtectedEnumClass.PublicItem1), ProtectedEnumClass.PublicItem1)
-
- self.assertEqual(obj.callPublicEnumMethod(ProtectedEnumClass.PublicItem0), ProtectedEnumClass.PublicItem0)
- self.assertEqual(obj.callPublicEnumMethod(ProtectedEnumClass.PublicItem1), ProtectedEnumClass.PublicItem1)
-
- def testOverriddenProtectedMethodWithProtectedEnumArgument(self):
- '''Calls overridden protected method with protected enum argument.'''
- obj = ExtendedProtectedEnumClass()
-
- self.assertEqual(obj.protectedEnumMethod(ProtectedEnumClass.ProtectedItem0), ProtectedEnumClass.ProtectedItem1)
- self.assertEqual(obj.protectedEnumMethod(ProtectedEnumClass.ProtectedItem1), ProtectedEnumClass.ProtectedItem0)
-
- self.assertEqual(ProtectedEnumClass.protectedEnumMethod(obj, ProtectedEnumClass.ProtectedItem0), ProtectedEnumClass.ProtectedItem0)
- self.assertEqual(ProtectedEnumClass.protectedEnumMethod(obj, ProtectedEnumClass.ProtectedItem1), ProtectedEnumClass.ProtectedItem1)
-
- self.assertEqual(obj.callProtectedEnumMethod(ProtectedEnumClass.ProtectedItem0), ProtectedEnumClass.ProtectedItem1)
- self.assertEqual(obj.callProtectedEnumMethod(ProtectedEnumClass.ProtectedItem1), ProtectedEnumClass.ProtectedItem0)
-
- def testOverriddenProtectedMethodWithPublicEnumArgument(self):
- '''Calls overridden protected method with public enum argument.'''
- obj = ExtendedProtectedEnumClass()
-
- self.assertEqual(obj.publicEnumMethod(ProtectedEnumClass.PublicItem0), ProtectedEnumClass.PublicItem1)
- self.assertEqual(obj.publicEnumMethod(ProtectedEnumClass.PublicItem1), ProtectedEnumClass.PublicItem0)
-
- self.assertEqual(ProtectedEnumClass.publicEnumMethod(obj, ProtectedEnumClass.PublicItem0), ProtectedEnumClass.PublicItem0)
- self.assertEqual(ProtectedEnumClass.publicEnumMethod(obj, ProtectedEnumClass.PublicItem1), ProtectedEnumClass.PublicItem1)
-
- self.assertEqual(obj.callPublicEnumMethod(ProtectedEnumClass.PublicItem0), ProtectedEnumClass.PublicItem1)
- self.assertEqual(obj.callPublicEnumMethod(ProtectedEnumClass.PublicItem1), ProtectedEnumClass.PublicItem0)
-
-
-class ProtectedPropertyTest(unittest.TestCase):
- '''Test cases for a class with a protected property (or field in C++).'''
-
- def setUp(self):
- self.obj = ProtectedProperty()
-
- def tearDown(self):
- del self.obj
- self.assertEqual(cacheSize(), 0)
-
- def testProtectedProperty(self):
- '''Writes and reads a protected integer property.'''
- self.obj.protectedProperty = 3
- self.assertEqual(self.obj.protectedProperty, 3)
-
- def testProtectedContainerProperty(self):
- '''Writes and reads a protected list of integers property.'''
- lst = [1, 2, 3, 4]
- self.obj.protectedContainerProperty = lst
- self.assertEqual(self.obj.protectedContainerProperty, lst)
-
- def testProtectedEnumProperty(self):
- '''Writes and reads a protected enum property.'''
- self.obj.protectedEnumProperty = Event.SOME_EVENT
- self.assertEqual(self.obj.protectedEnumProperty, Event.SOME_EVENT)
-
- def testProtectedValueTypeProperty(self):
- '''Writes and reads a protected value type property.'''
- point = Point(12, 34)
- self.obj.protectedValueTypeProperty = point
- self.assertEqual(self.obj.protectedValueTypeProperty, point)
- self.assertFalse(self.obj.protectedValueTypeProperty is point)
- pointProperty = self.obj.protectedValueTypeProperty
- self.assertTrue(self.obj.protectedValueTypeProperty is pointProperty)
-
- def testProtectedValueTypePropertyWrapperRegistration(self):
- '''Access colocated protected value type property.'''
- cache_size = cacheSize()
- point = Point(12, 34)
- obj = createProtectedProperty()
- obj.protectedValueTypeProperty
- self.assertEqual(obj.protectedValueTypeProperty.copy(),
- obj.protectedValueTypeProperty)
- obj.protectedValueTypeProperty = point
- self.assertEqual(obj.protectedValueTypeProperty, point)
- self.assertFalse(obj.protectedValueTypeProperty is point)
- pointProperty = obj.protectedValueTypeProperty
- self.assertTrue(obj.protectedValueTypeProperty is pointProperty)
- del obj, point, pointProperty
- self.assertEqual(cacheSize(), cache_size)
-
- def testProtectedValueTypePointerProperty(self):
- '''Writes and reads a protected value type pointer property.'''
- pt1 = Point(12, 34)
- pt2 = Point(12, 34)
- self.obj.protectedValueTypePointerProperty = pt1
- self.assertEqual(self.obj.protectedValueTypePointerProperty, pt1)
- self.assertEqual(self.obj.protectedValueTypePointerProperty, pt2)
- self.assertTrue(self.obj.protectedValueTypePointerProperty is pt1)
- self.assertFalse(self.obj.protectedValueTypePointerProperty is pt2)
-
- def testProtectedObjectTypeProperty(self):
- '''Writes and reads a protected object type property.'''
- obj = ObjectType()
- self.obj.protectedObjectTypeProperty = obj
- self.assertEqual(self.obj.protectedObjectTypeProperty, obj)
-
-
-class PrivateDtorProtectedMethodTest(unittest.TestCase):
- '''Test cases for classes with private destructors and protected methods.'''
-
- def tearDown(self):
- self.assertEqual(cacheSize(), 0)
-
- def testProtectedMethod(self):
- '''Calls protected method of a class with a private destructor.'''
- obj = PrivateDtor.instance()
-
- self.assertEqual(type(obj), PrivateDtor)
- self.assertEqual(obj.instanceCalls(), 1)
- self.assertEqual(obj.instanceCalls(), obj.protectedInstanceCalls())
- obj = PrivateDtor.instance()
- self.assertEqual(obj.instanceCalls(), 2)
- self.assertEqual(obj.instanceCalls(), obj.protectedInstanceCalls())
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/pstrlist_test.py b/sources/shiboken2/tests/samplebinding/pstrlist_test.py
deleted file mode 100644
index 04492de33..000000000
--- a/sources/shiboken2/tests/samplebinding/pstrlist_test.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import sample
-
-class PStrListTest(unittest.TestCase):
-
- def testPStrList(self):
- a = 'str0'
- b = 'str1'
- lst = sample.createPStrList(a, b)
- self.assertEqual(lst, [a, b])
-
- def testListOfPStr(self):
- a = 'str0'
- b = 'str1'
- lst = sample.createListOfPStr(a, b)
- self.assertEqual(lst, [a, b])
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/pystr_test.py b/sources/shiboken2/tests/samplebinding/pystr_test.py
deleted file mode 100644
index b69cf369e..000000000
--- a/sources/shiboken2/tests/samplebinding/pystr_test.py
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for definition of __str__ method.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Point
-
-class PyStrTest(unittest.TestCase):
- '''Test case for definition of __str__ method.'''
-
- def testPyStr(self):
- '''Test case for defined __str__ method.'''
- pt = Point(5, 2)
- self.assertEqual(str(pt), 'Point(5.0, 2.0)')
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/python_thread_test.py b/sources/shiboken2/tests/samplebinding/python_thread_test.py
deleted file mode 100644
index 56b927367..000000000
--- a/sources/shiboken2/tests/samplebinding/python_thread_test.py
+++ /dev/null
@@ -1,122 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-#!/usr/bin/env python
-
-'''Tests for using Shiboken-based bindings with python threads'''
-
-import logging
-import os
-from random import random
-import sys
-import threading
-import time
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import sample
-
-#logging.basicConfig(level=logging.DEBUG)
-
-
-class Producer(threading.Thread):
- '''Producer thread'''
-
- def __init__(self, bucket, max_runs, *args):
- #Constructor. Receives the bucket
- super(Producer, self).__init__(*args)
- self.runs = 0
- self.bucket = bucket
- self.max_runs = max_runs
- self.production_list = []
-
- def run(self):
- while self.runs < self.max_runs:
- value = int(random()*10) % 10
- self.bucket.push(value)
- self.production_list.append(value)
- logging.debug('PRODUCER - pushed %d' % value)
- self.runs += 1
- #self.msleep(5)
- time.sleep(0.01)
-
-
-class Consumer(threading.Thread):
- '''Consumer thread'''
- def __init__(self, bucket, max_runs, *args):
- #Constructor. Receives the bucket
- super(Consumer, self).__init__(*args)
- self.runs = 0
- self.bucket = bucket
- self.max_runs = max_runs
- self.consumption_list = []
-
- def run(self):
- while self.runs < self.max_runs:
- if not self.bucket.empty():
- value = self.bucket.pop()
- self.consumption_list.append(value)
- logging.debug('CONSUMER - got %d' % value)
- self.runs += 1
- else:
- logging.debug('CONSUMER - empty bucket')
- time.sleep(0.01)
-
-class ProducerConsumer(unittest.TestCase):
- '''Basic test case for producer-consumer QThread'''
-
- def finishCb(self):
- #Quits the application
- self.app.exit(0)
-
- def testProdCon(self):
- #QThread producer-consumer example
- bucket = sample.Bucket()
- prod = Producer(bucket, 10)
- cons = Consumer(bucket, 10)
-
- prod.start()
- cons.start()
-
- #QObject.connect(prod, SIGNAL('finished()'), self.finishCb)
- #QObject.connect(cons, SIGNAL('finished()'), self.finishCb)
-
- prod.join()
- cons.join()
-
- self.assertEqual(prod.production_list, cons.consumption_list)
-
-
-
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/receive_null_cstring_test.py b/sources/shiboken2/tests/samplebinding/receive_null_cstring_test.py
deleted file mode 100644
index 8023aead0..000000000
--- a/sources/shiboken2/tests/samplebinding/receive_null_cstring_test.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for a function that could receive a NULL pointer in a '[const] char*' parameter.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import countCharacters
-
-class ReceiveNullCStringTest(unittest.TestCase):
- '''Test case for a function that could receive a NULL pointer in a '[const] char*' parameter.'''
-
- def testBasic(self):
- '''The test function should be working for the basic cases.'''
- a = ''
- b = 'abc'
- self.assertEqual(countCharacters(a), len(a))
- self.assertEqual(countCharacters(b), len(b))
-
- def testReceiveNull(self):
- '''The test function returns '-1' when receives a None value instead of a string.'''
- self.assertEqual(countCharacters(None), -1)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/reference_test.py b/sources/shiboken2/tests/samplebinding/reference_test.py
deleted file mode 100644
index 7ff806692..000000000
--- a/sources/shiboken2/tests/samplebinding/reference_test.py
+++ /dev/null
@@ -1,127 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for methods that receive references to objects.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class ExtendedReference(Reference):
- def __init__(self):
- Reference.__init__(self)
- self.uses_reference_virtual_called = False
- self.uses_const_reference_virtual_called = False
- self.reference_inc = 1
- self.const_reference_inc = 2
- self.multiplier = 333
-
- def usesReferenceVirtual(self, ref, inc):
- self.uses_reference_virtual_called = True
- return ref.objId() + inc + self.reference_inc
-
- def usesConstReferenceVirtual(self, ref, inc):
- self.uses_const_reference_virtual_called = True
- return ref.objId() + inc + self.const_reference_inc
-
- def alterReferenceIdVirtual(self, ref):
- ref.setObjId(ref.objId() * self.multiplier)
-
-
-class ReferenceTest(unittest.TestCase):
- '''Test case for methods that receive references to objects.'''
-
- def testMethodThatReceivesReference(self):
- '''Test a method that receives a reference to an object as argument.'''
- objId = 123
- r = Reference(objId)
- self.assertEqual(Reference.usesReference(r), objId)
-
- def testCantSegFaultWhenReceiveNone(self):
- '''do not segfault when receiving None as argument.'''
- s = Str()
- self.assertTrue(None == s)
-
- def testMethodThatReceivesConstReference(self):
- '''Test a method that receives a const reference to an object as argument.'''
- objId = 123
- r = Reference(objId)
- self.assertEqual(Reference.usesConstReference(r), objId)
-
- def testModificationOfReference(self):
- '''Tests if the identity of a reference argument is preserved when passing it to be altered in C++.'''
- objId = 123
- r1 = Reference(objId)
- r1.alterReferenceIdVirtual(r1)
- self.assertEqual(r1.objId(), objId * Reference.multiplier())
-
- def testModificationOfReferenceCallingAVirtualIndirectly(self):
- '''Tests if the identity of a reference argument is preserved when passing it to be altered in C++ through a method that calls a virtual method.'''
- objId = 123
- r1 = Reference(objId)
- r1.callAlterReferenceIdVirtual(r1)
- self.assertEqual(r1.objId(), objId * Reference.multiplier())
-
- def testModificationOfReferenceCallingAReimplementedVirtualIndirectly(self):
- '''Test if a Python override of a virtual method with a reference parameter called from C++ alters the argument properly.'''
- objId = 123
- r = Reference(objId)
- er = ExtendedReference()
- result = er.callAlterReferenceIdVirtual(r)
- self.assertEqual(r.objId(), objId * er.multiplier)
-
- def testReimplementedVirtualMethodCallWithReferenceParameter(self):
- '''Test if a Python override of a virtual method with a reference parameter is correctly called from C++.'''
- inc = 9
- objId = 123
- r = Reference(objId)
- er = ExtendedReference()
- result = er.callUsesReferenceVirtual(r, inc)
- self.assertEqual(result, objId + inc + er.reference_inc)
-
- def testReimplementedVirtualMethodCallWithConstReferenceParameter(self):
- '''Test if a Python override of a virtual method with a const reference parameter is correctly called from C++.'''
- inc = 9
- objId = 123
- r = Reference(objId)
- er = ExtendedReference()
- result = er.callUsesConstReferenceVirtual(r, inc)
- self.assertEqual(result, objId + inc + er.const_reference_inc)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/referencetopointer_test.py b/sources/shiboken2/tests/samplebinding/referencetopointer_test.py
deleted file mode 100644
index 240719e4b..000000000
--- a/sources/shiboken2/tests/samplebinding/referencetopointer_test.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for a reference to pointer argument type.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import VirtualMethods, Str
-
-class ExtendedVirtualMethods(VirtualMethods):
- def __init__(self):
- VirtualMethods.__init__(self)
- self.prefix = 'Ext'
-
- def createStr(self, text):
- ext_text = text
- if text is not None:
- ext_text = self.prefix + text
- return VirtualMethods.createStr(self, ext_text)
-
-
-class ReferenceToPointerTest(unittest.TestCase):
- '''Test cases for a reference to pointer argument type.'''
-
- def testSimpleCallWithNone(self):
- '''Simple call to createStr method with a None argument.'''
- obj = VirtualMethods()
- ok, string = obj.createStr(None)
- self.assertFalse(ok)
- self.assertEqual(string, None)
-
- def testSimpleCallWithString(self):
- '''Simple call to createStr method with a Python string argument.'''
- obj = VirtualMethods()
- ok, string = obj.createStr('foo')
- self.assertTrue(ok)
- self.assertEqual(string, Str('foo'))
-
- def testCallNonReimplementedMethodWithNone(self):
- '''Calls createStr method from C++ with a None argument.'''
- obj = VirtualMethods()
- ok, string = obj.callCreateStr(None)
- self.assertFalse(ok)
- self.assertEqual(string, None)
-
- def testCallNonReimplementedMethodWithString(self):
- '''Calls createStr method from C++ with a Python string argument.'''
- obj = VirtualMethods()
- ok, string = obj.callCreateStr('foo')
- self.assertTrue(ok)
- self.assertEqual(string, Str('foo'))
-
- def testCallReimplementedMethodWithNone(self):
- '''Calls reimplemented createStr method from C++ with a None argument.'''
- obj = ExtendedVirtualMethods()
- ok, string = obj.callCreateStr(None)
- self.assertFalse(ok)
- self.assertEqual(string, None)
-
- def testCallReimplementedMethodWithString(self):
- '''Calls reimplemented createStr method from C++ with a Python string argument.'''
- obj = ExtendedVirtualMethods()
- ok, string = obj.callCreateStr('foo')
- self.assertTrue(ok)
- self.assertEqual(string, Str(obj.prefix + 'foo'))
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/renaming_test.py b/sources/shiboken2/tests/samplebinding/renaming_test.py
deleted file mode 100644
index cb59dce3a..000000000
--- a/sources/shiboken2/tests/samplebinding/renaming_test.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for renaming using target-lang-name attribute.'''
-
-import os
-import re
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import RenamedValue, RenamedUser
-
-class RenamingTest(unittest.TestCase):
- def test(self):
- '''Tests whether the C++ class ToBeRenamedValue renamed via attribute
- target-lang-name to RenamedValue shows up in consuming function
- signature strings correctly.
- '''
- renamed_value = RenamedValue()
- self.assertEqual(str(type(renamed_value)),
- "<class 'sample.RenamedValue'>")
- rename_user = RenamedUser()
- rename_user.useRenamedValue(renamed_value)
- actual_signature = str(rename_user.useRenamedValue.__signature__)
- self.assertTrue(re.match(r"^\(self,\s*v:\s*sample.RenamedValue\)$",
- actual_signature))
-
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/return_null_test.py b/sources/shiboken2/tests/samplebinding/return_null_test.py
deleted file mode 100644
index 85764679b..000000000
--- a/sources/shiboken2/tests/samplebinding/return_null_test.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for functions that could return a NULL pointer.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import returnNullPrimitivePointer, returnNullValueTypePointer, returnNullObjectTypePointer
-
-class ReturnNullTest(unittest.TestCase):
- '''Test case for functions that could return a NULL pointer.'''
-
- def testReturnNull(self):
- '''Function returns a NULL pointer to a primitive type.'''
- o = returnNullPrimitivePointer()
- self.assertEqual(o, None)
-
- def testReturnNullObjectType(self):
- '''Function returns a NULL pointer to an object-type.'''
- o = returnNullObjectTypePointer()
- self.assertEqual(o, None)
-
- def testReturnNullValueType(self):
- '''Function returns a NULL pointer to a value-type.'''
- o = returnNullValueTypePointer()
- self.assertEqual(o, None)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/richcompare_test.py b/sources/shiboken2/tests/samplebinding/richcompare_test.py
deleted file mode 100644
index bcda390c3..000000000
--- a/sources/shiboken2/tests/samplebinding/richcompare_test.py
+++ /dev/null
@@ -1,52 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class TestRichCompare(unittest.TestCase):
-
- def testIt(self):
- a = Expression(2)
- b = Expression(3)
- c = a + b
- d = a + c < b + a
- self.assertEqual(d.toString(), "((2+(2+3))<(3+2))")
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/sample-binding.txt.in b/sources/shiboken2/tests/samplebinding/sample-binding.txt.in
deleted file mode 100644
index 317f76f09..000000000
--- a/sources/shiboken2/tests/samplebinding/sample-binding.txt.in
+++ /dev/null
@@ -1,15 +0,0 @@
-[generator-project]
-
-generator-set = shiboken
-
-header-file = @CMAKE_CURRENT_SOURCE_DIR@/global.h
-typesystem-file = @sample_TYPESYSTEM@
-
-output-directory = @CMAKE_CURRENT_BINARY_DIR@
-
-include-path = @libsample_SOURCE_DIR@
-
-typesystem-path = @CMAKE_CURRENT_SOURCE_DIR@
-
-enable-parent-ctor-heuristic
-use-isnull-as-nb_nonzero
diff --git a/sources/shiboken2/tests/samplebinding/sample_test.py b/sources/shiboken2/tests/samplebinding/sample_test.py
deleted file mode 100644
index d6cf82f9a..000000000
--- a/sources/shiboken2/tests/samplebinding/sample_test.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for libsample bindings module'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import sample
-
-class ModuleTest(unittest.TestCase):
- '''Test case for module and global functions'''
-
- def testModuleMembers(self):
- '''Test availability of classes, global functions and other members on binding'''
- expected_members = set(['Abstract', 'Derived', 'Point',
- 'ListUser', 'PairUser', 'MapUser',
- 'gimmeComplexList', 'gimmeDouble', 'gimmeInt',
- 'makeCString', 'multiplyPair', 'returnCString',
- 'SampleNamespace', 'transmuteComplexIntoPoint',
- 'transmutePointIntoComplex', 'sumComplexPair',
- 'FirstThing', 'SecondThing', 'ThirdThing',
- 'GlobalEnum', 'NoThing'])
- self.assertTrue(expected_members.issubset(dir(sample)))
-
- def testAbstractPrintFormatEnum(self):
- '''Test availability of PrintFormat enum from Abstract class'''
- enum_members = set(['PrintFormat', 'Short', 'Verbose',
- 'OnlyId', 'ClassNameAndId'])
- self.assertTrue(enum_members.issubset(dir(sample.Abstract)))
-
- def testSampleNamespaceOptionEnum(self):
- '''Test availability of Option enum from SampleNamespace namespace'''
- enum_members = set(['Option', 'None_', 'RandomNumber', 'UnixTime'])
- self.assertTrue(enum_members.issubset(dir(sample.SampleNamespace)))
-
- def testAddedFunctionAtModuleLevel(self):
- '''Calls function added to module from type system description.'''
- str1 = 'Foo'
- self.assertEqual(sample.multiplyString(str1, 3), str1 * 3)
- self.assertEqual(sample.multiplyString(str1, 0), str1 * 0)
-
- def testAddedFunctionWithVarargs(self):
- '''Calls function that receives varargs added to module from type system description.'''
- self.assertEqual(sample.countVarargs(1), 0)
- self.assertEqual(sample.countVarargs(1, 2), 1)
- self.assertEqual(sample.countVarargs(1, 2, 3, 'a', 'b', 4, (5, 6)), 6)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/simplefile_glue.cpp b/sources/shiboken2/tests/samplebinding/simplefile_glue.cpp
deleted file mode 100644
index bccd51534..000000000
--- a/sources/shiboken2/tests/samplebinding/simplefile_glue.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-if (!%CPPSELF.%FUNCTION_NAME()) {
- PyObject* error_msg = PyBytes_FromFormat(
- "Could not open file: \"%s\"", %CPPSELF->filename());
- PyErr_SetObject(PyExc_IOError, error_msg);
- return 0;
-}
diff --git a/sources/shiboken2/tests/samplebinding/simplefile_test.py b/sources/shiboken2/tests/samplebinding/simplefile_test.py
deleted file mode 100644
index 4a841be80..000000000
--- a/sources/shiboken2/tests/samplebinding/simplefile_test.py
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for SimpleFile class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import SimpleFile
-
-class SimpleFileTest(unittest.TestCase):
- '''Test cases for SimpleFile class.'''
-
- def setUp(self):
- filename = 'simplefile%d.txt' % os.getpid()
- self.existing_filename = os.path.join(os.path.curdir, filename)
- self.delete_file = False
- if not os.path.exists(self.existing_filename):
- f = open(self.existing_filename, 'w')
- for line in range(10):
- f.write('sbrubbles\n')
- f.close()
- self.delete_file = True
-
- self.non_existing_filename = os.path.join(os.path.curdir, 'inexistingfile.txt')
- i = 0
- while os.path.exists(self.non_existing_filename):
- i += 1
- filename = 'inexistingfile-%d.txt' % i
- self.non_existing_filename = os.path.join(os.path.curdir, filename)
-
- def tearDown(self):
- if self.delete_file:
- os.remove(self.existing_filename)
-
- def testExistingFile(self):
- '''Test SimpleFile class with existing file.'''
- f = SimpleFile(self.existing_filename)
- self.assertEqual(f.filename(), self.existing_filename)
- f.open()
- self.assertNotEqual(f.size(), 0)
- f.close()
-
- def testNonExistingFile(self):
- '''Test SimpleFile class with non-existing file.'''
- f = SimpleFile(self.non_existing_filename)
- self.assertEqual(f.filename(), self.non_existing_filename)
- self.assertRaises(IOError, f.open)
- self.assertEqual(f.size(), 0)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/size_test.py b/sources/shiboken2/tests/samplebinding/size_test.py
deleted file mode 100644
index 53626c961..000000000
--- a/sources/shiboken2/tests/samplebinding/size_test.py
+++ /dev/null
@@ -1,125 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for operator overloads on Size class'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Size
-
-class PointTest(unittest.TestCase):
- '''Test case for Size class, including operator overloads.'''
-
- def testConstructor(self):
- '''Test Size class constructor.'''
- width, height = (5.0, 2.3)
- size = Size(width, height)
- self.assertEqual(size.width(), width)
- self.assertEqual(size.height(), height)
- self.assertEqual(size.calculateArea(), width * height)
-
- def testCopyConstructor(self):
- '''Test Size class copy constructor.'''
- width, height = (5.0, 2.3)
- s1 = Size(width, height)
- s2 = Size(s1)
- self.assertFalse(s1 is s2)
- self.assertEqual(s1, s2)
-
- def testPlusOperator(self):
- '''Test Size class + operator.'''
- s1 = Size(5.0, 2.3)
- s2 = Size(0.5, 3.2)
- self.assertEqual(s1 + s2, Size(5.0 + 0.5, 2.3 + 3.2))
-
- def testEqualOperator(self):
- '''Test Size class == operator.'''
- s1 = Size(5.0, 2.3)
- s2 = Size(5.0, 2.3)
- s3 = Size(0.5, 3.2)
- self.assertTrue(s1 == s1)
- self.assertTrue(s1 == s2)
- self.assertFalse(s1 == s3)
-
- def testNotEqualOperator(self):
- '''Test Size class != operator.'''
- s1 = Size(5.0, 2.3)
- s2 = Size(5.0, 2.3)
- s3 = Size(0.5, 3.2)
- self.assertFalse(s1 != s1)
- self.assertFalse(s1 != s2)
- self.assertTrue(s1 != s3)
-
- def testMinorEqualOperator(self):
- '''Test Size class <= operator.'''
- s1 = Size(5.0, 2.3)
- s2 = Size(5.0, 2.3)
- s3 = Size(0.5, 3.2)
- self.assertTrue(s1 <= s1)
- self.assertTrue(s1 <= s2)
- self.assertTrue(s3 <= s1)
- self.assertFalse(s1 <= s3)
-
- def testMinorOperator(self):
- '''Test Size class < operator.'''
- s1 = Size(5.0, 2.3)
- s2 = Size(0.5, 3.2)
- self.assertFalse(s1 < s1)
- self.assertFalse(s1 < s2)
- self.assertTrue(s2 < s1)
-
- def testMajorEqualOperator(self):
- '''Test Size class >= operator.'''
- s1 = Size(5.0, 2.3)
- s2 = Size(5.0, 2.3)
- s3 = Size(0.5, 3.2)
- self.assertTrue(s1 >= s1)
- self.assertTrue(s1 >= s2)
- self.assertTrue(s1 >= s3)
- self.assertFalse(s3 >= s1)
-
- def testMajorOperator(self):
- '''Test Size class > operator.'''
- s1 = Size(5.0, 2.3)
- s2 = Size(0.5, 3.2)
- self.assertFalse(s1 > s1)
- self.assertTrue(s1 > s2)
- self.assertFalse(s2 > s1)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/static_nonstatic_methods_test.py b/sources/shiboken2/tests/samplebinding/static_nonstatic_methods_test.py
deleted file mode 100644
index cd1a8a4f0..000000000
--- a/sources/shiboken2/tests/samplebinding/static_nonstatic_methods_test.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for overloads involving static and non-static versions of a method.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import SimpleFile
-
-class SimpleFile2 (SimpleFile):
- def exists(self):
- return "Mooo"
-
-class SimpleFile3 (SimpleFile):
- pass
-
-class SimpleFile4 (SimpleFile):
- exists = 5
-
-class StaticNonStaticMethodsTest(unittest.TestCase):
- '''Test cases for overloads involving static and non-static versions of a method.'''
-
- def setUp(self):
- filename = 'simplefile%d.txt' % os.getpid()
- self.existing_filename = os.path.join(os.path.curdir, filename)
- self.delete_file = False
- if not os.path.exists(self.existing_filename):
- f = open(self.existing_filename, 'w')
- for line in range(10):
- f.write('sbrubbles\n')
- f.close()
- self.delete_file = True
-
- self.non_existing_filename = os.path.join(os.path.curdir, 'inexistingfile.txt')
- i = 0
- while os.path.exists(self.non_existing_filename):
- i += 1
- filename = 'inexistingfile-%d.txt' % i
- self.non_existing_filename = os.path.join(os.path.curdir, filename)
-
- def tearDown(self):
- if self.delete_file:
- os.remove(self.existing_filename)
-
- def testCallingStaticMethodWithClass(self):
- '''Call static method using class.'''
- self.assertTrue(SimpleFile.exists(self.existing_filename))
- self.assertFalse(SimpleFile.exists(self.non_existing_filename))
-
- def testCallingStaticMethodWithInstance(self):
- '''Call static method using instance of class.'''
- f = SimpleFile(self.non_existing_filename)
- self.assertTrue(f.exists(self.existing_filename))
- self.assertFalse(f.exists(self.non_existing_filename))
-
- def testCallingInstanceMethod(self):
- '''Call instance method.'''
- f1 = SimpleFile(self.non_existing_filename)
- self.assertFalse(f1.exists())
- f2 = SimpleFile(self.existing_filename)
- self.assertTrue(f2.exists())
-
- def testOverridingStaticNonStaticMethod(self):
- f = SimpleFile2(self.existing_filename)
- self.assertEqual(f.exists(), "Mooo")
-
- f = SimpleFile3(self.existing_filename)
- self.assertTrue(f.exists())
-
- f = SimpleFile4(self.existing_filename)
- self.assertEqual(f.exists, 5)
-
- def testDuckPunchingStaticNonStaticMethod(self):
- f = SimpleFile(self.existing_filename)
- f.exists = lambda : "Meee"
- self.assertEqual(f.exists(), "Meee")
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/str_test.py b/sources/shiboken2/tests/samplebinding/str_test.py
deleted file mode 100644
index 15df1f55a..000000000
--- a/sources/shiboken2/tests/samplebinding/str_test.py
+++ /dev/null
@@ -1,121 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for a method that receives a reference to class that is implicitly convertible from a Python native type.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Str
-
-class StrTest(unittest.TestCase):
- '''Test cases for thr Str class.'''
-
- def test__str__Method(self):
- '''Test if the binding correcly implements the Python __str__ method.'''
- s1 = 'original string'
- s2 = Str(s1)
- self.assertEqual(s1, s2)
- self.assertEqual(s1, str(s2))
-
- def testPassExactClassAsReferenceToArgument(self):
- '''Test passing the expected class as an argument to a method that expects a reference.'''
- s1 = Str('This is %VAR!').arg(Str('Sparta'))
- self.assertEqual(str(s1), 'This is Sparta!')
-
- def testPassPythonTypeImplictlyConvertibleToAClassUsedAsReference(self):
- '''Test passing a Python class implicitly convertible to a wrapped class that is expected to be passed as reference.'''
- s1 = Str('This is %VAR!').arg('Athens')
- self.assertEqual(str(s1), 'This is Athens!')
-
- def testSequenceOperators(self):
- s1 = Str("abcdef")
- self.assertEqual(len(s1), 6);
- self.assertEqual(len(Str()), 0);
-
- # getitem
- self.assertEqual(s1[0], "a");
- self.assertEqual(s1[1], "b");
- self.assertEqual(s1[2], "c");
- self.assertEqual(s1[3], "d");
- self.assertEqual(s1[4], "e");
- self.assertEqual(s1[5], "f");
- self.assertEqual(s1[-1], "f");
- self.assertEqual(s1[-2], "e");
-
- self.assertRaises(TypeError, s1.__getitem__, 6)
-
- # setitem
- s1[0] = 'A'
- s1[1] = 'B'
- self.assertEqual(s1[0], 'A');
- self.assertEqual(s1[1], 'B');
- self.assertRaises(TypeError, s1.__setitem__(6, 67))
-
- def testReverseOperator(self):
- s1 = Str("hello")
- n1 = 2
- self.assertEqual(s1+2, "hello2")
- self.assertEqual(2+s1, "2hello")
-
- def testToIntError(self):
- self.assertEqual(Str('Z').toInt(), (0, False))
-
- def testToIntWithDecimal(self):
- decimal = Str('37')
- val, ok = decimal.toInt()
- self.assertEqual(type(val), int)
- self.assertEqual(type(ok), bool)
- self.assertEqual(val, int(str(decimal)))
-
- def testToIntWithOctal(self):
- octal = Str('52')
- val, ok = octal.toInt(8)
- self.assertEqual(type(val), int)
- self.assertEqual(type(ok), bool)
- self.assertEqual(val, int(str(octal), 8))
-
- def testToIntWithHexadecimal(self):
- hexa = Str('2A')
- val, ok = hexa.toInt(16)
- self.assertEqual(type(val), int)
- self.assertEqual(type(ok), bool)
- self.assertEqual(val, int(str(hexa), 16))
- self.assertEqual(hexa.toInt(), (0, False))
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/strlist_test.py b/sources/shiboken2/tests/samplebinding/strlist_test.py
deleted file mode 100644
index 57537f061..000000000
--- a/sources/shiboken2/tests/samplebinding/strlist_test.py
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for StrList class that inherits from std::list<Str>.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Str, StrList
-
-class StrListTest(unittest.TestCase):
- '''Test cases for StrList class that inherits from std::list<Str>.'''
-
- def testStrListCtor_NoParams(self):
- '''StrList constructor receives no parameter.'''
- sl = StrList()
- self.assertEqual(len(sl), 0)
- self.assertEqual(sl.constructorUsed(), StrList.NoParamsCtor)
-
- def testStrListCtor_Str(self):
- '''StrList constructor receives a Str object.'''
- s = Str('Foo')
- sl = StrList(s)
- self.assertEqual(len(sl), 1)
- self.assertEqual(sl[0], s)
- self.assertEqual(sl.constructorUsed(), StrList.StrCtor)
-
- def testStrListCtor_PythonString(self):
- '''StrList constructor receives a Python string.'''
- s = 'Foo'
- sl = StrList(s)
- self.assertEqual(len(sl), 1)
- self.assertEqual(sl[0], s)
- self.assertEqual(sl.constructorUsed(), StrList.StrCtor)
-
- def testStrListCtor_StrList(self):
- '''StrList constructor receives a StrList object.'''
- sl1 = StrList(Str('Foo'))
- sl2 = StrList(sl1)
- #self.assertEqual(len(sl1), len(sl2))
- #self.assertEqual(sl1, sl2)
- self.assertEqual(sl2.constructorUsed(), StrList.CopyCtor)
-
- def testStrListCtor_ListOfStrs(self):
- '''StrList constructor receives a Python list of Str objects.'''
- strs = [Str('Foo'), Str('Bar')]
- sl = StrList(strs)
- self.assertEqual(len(sl), len(strs))
- self.assertEqual(sl, strs)
- self.assertEqual(sl.constructorUsed(), StrList.ListOfStrCtor)
-
- def testStrListCtor_MixedListOfStrsAndPythonStrings(self):
- '''StrList constructor receives a Python list of mixed Str objects and Python strings.'''
- strs = [Str('Foo'), 'Bar']
- sl = StrList(strs)
- self.assertEqual(len(sl), len(strs))
- self.assertEqual(sl, strs)
- self.assertEqual(sl.constructorUsed(), StrList.ListOfStrCtor)
-
- def testCompareStrListWithTupleOfStrs(self):
- '''Compares StrList with a Python tuple of Str objects.'''
- sl = StrList()
- sl.append(Str('Foo'))
- sl.append(Str('Bar'))
- self.assertEqual(len(sl), 2)
- self.assertEqual(sl, (Str('Foo'), Str('Bar')))
-
- def testCompareStrListWithTupleOfPythonStrings(self):
- '''Compares StrList with a Python tuple of Python strings.'''
- sl = StrList()
- sl.append(Str('Foo'))
- sl.append(Str('Bar'))
- self.assertEqual(len(sl), 2)
- self.assertEqual(sl, ('Foo', 'Bar'))
-
- def testCompareStrListWithTupleOfStrAndPythonString(self):
- '''Compares StrList with a Python tuple of mixed Str objects and Python strings.'''
- sl = StrList()
- sl.append(Str('Foo'))
- sl.append(Str('Bar'))
- self.assertEqual(len(sl), 2)
- self.assertEqual(sl, (Str('Foo'), 'Bar'))
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/templateinheritingclass_test.py b/sources/shiboken2/tests/samplebinding/templateinheritingclass_test.py
deleted file mode 100644
index bc66b208f..000000000
--- a/sources/shiboken2/tests/samplebinding/templateinheritingclass_test.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Photon
-
-'''This tests classes that inherit from template classes,
-simulating a situation found in Qt's phonon module.'''
-
-class TemplateInheritingClassTest(unittest.TestCase):
- def testClassBasics(self):
- self.assertEqual(Photon.ValueIdentity.classType(), Photon.IdentityType)
- self.assertEqual(Photon.ValueDuplicator.classType(), Photon.DuplicatorType)
-
- def testInstanceBasics(self):
- value = 123
- samer = Photon.ValueIdentity(value)
- self.assertEqual(samer.multiplicator(), 1)
- doubler = Photon.ValueDuplicator(value)
- self.assertEqual(doubler.multiplicator(), 2)
- self.assertEqual(samer.value(), doubler.value())
- self.assertEqual(samer.calculate() * 2, doubler.calculate())
-
- def testPassToFunctionAsPointer(self):
- obj = Photon.ValueDuplicator(123)
- self.assertEqual(Photon.callCalculateForValueDuplicatorPointer(obj), obj.calculate())
-
- def testPassToFunctionAsReference(self):
- obj = Photon.ValueDuplicator(321)
- self.assertEqual(Photon.callCalculateForValueDuplicatorReference(obj), obj.calculate())
-
- def testPassToMethodAsValue(self):
- value1, value2 = 123, 321
- one = Photon.ValueIdentity(value1)
- other = Photon.ValueIdentity(value2)
- self.assertEqual(one.sumValueUsingPointer(other), value1 + value2)
-
- def testPassToMethodAsReference(self):
- value1, value2 = 123, 321
- one = Photon.ValueDuplicator(value1)
- other = Photon.ValueDuplicator(value2)
- self.assertEqual(one.sumValueUsingReference(other), value1 + value2)
-
- def testPassPointerThrough(self):
- obj1 = Photon.ValueIdentity(123)
- self.assertEqual(obj1, obj1.passPointerThrough(obj1))
- obj2 = Photon.ValueDuplicator(321)
- self.assertEqual(obj2, obj2.passPointerThrough(obj2))
- self.assertRaises(TypeError, obj1.passPointerThrough, obj2)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/time_test.py b/sources/shiboken2/tests/samplebinding/time_test.py
deleted file mode 100644
index f8b35e7b7..000000000
--- a/sources/shiboken2/tests/samplebinding/time_test.py
+++ /dev/null
@@ -1,145 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for constructor and method signature decisor on Time class.'''
-
-import sys
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-import datetime
-
-from sample import Time, ImplicitConv, ObjectType
-
-class TimeTest(unittest.TestCase):
- '''Test cases for constructor and method signature decisor on Time class.
- The constructor and one method have these signatures: CTORMETHOD() and
- CTORMETHOD(int h, int m, int s = 0, int ms = 0); there another method
- with a more complex signature METH(int, int, ImplicitConv=DEFVALUE, ObjectType=0),
- to produce an even worse scenario.
- '''
-
- def testConstructorWithoutParamers(self):
- '''Constructor without parameters: Time()'''
- time = Time()
- self.assertTrue(time.isNull())
-
- def testConstructorWithAllParamers(self):
- '''Constructor with all parameters: Time(int h, int m, int s = 0, int ms = 0)'''
- time = Time(1, 2, 3, 4)
- self.assertTrue(time.toString(), '01:02:03.004')
-
- def testConstructorWithThreeParamers(self):
- '''Constructor with 3 parameters: Time(int h, int m, int s = 0, int ms = 0)'''
- time = Time(1, 2, 3)
- self.assertTrue(time.toString(), '01:02:03.000')
-
- def testConstructorWithTwoParamers(self):
- '''Constructor with 2 parameters: Time(int h, int m, int s = 0, int ms = 0)'''
- time = Time(1, 2)
- self.assertTrue(time.toString(), '01:02:00.000')
-
- def testSimpleMethodWithoutParamers(self):
- '''Constructor without parameters: Time.setTime()'''
- time = Time(1, 2, 3, 4)
- time.setTime()
- self.assertTrue(time.isNull())
-
- def testSimpleMethodWithAllParamers(self):
- '''Simple method with all parameters: Time.setTime(int h, int m, int s = 0, int ms = 0)'''
- time = Time()
- time.setTime(1, 2, 3, 4)
- self.assertTrue(time.toString(), '01:02:03.004')
-
- def testSimpleMethodWithThreeParamers(self):
- '''Simple method with 3 parameters: Time.setTime(int h, int m, int s = 0, int ms = 0)'''
- time = Time()
- time.setTime(1, 2, 3)
- self.assertTrue(time.toString(), '01:02:03.000')
-
- def testSimpleMethodWithTwoParamers(self):
- '''Simple method with 2 parameters: Time.setTime(int h, int m, int s = 0, int ms = 0)'''
- time = Time()
- time.setTime(1, 2)
- self.assertTrue(time.toString(), '01:02:00.000')
-
- def testMethodWithoutParamers(self):
- '''Method without parameters: Time.somethingCompletelyDifferent()'''
- time = Time()
- result = time.somethingCompletelyDifferent()
- self.assertEqual(result, Time.ZeroArgs)
-
- def testMethodWithAllParamers(self):
- '''Method with all parameters:
- Time.somethingCompletelyDifferent(
- int h, int m, ImplicitConv ic = ImplicitConv::CtorThree, ObjectType* type = 0
- );
- '''
- time = Time()
- obj = ObjectType()
- result = time.somethingCompletelyDifferent(1, 2, ImplicitConv(2), obj)
- self.assertEqual(result, Time.FourArgs)
-
- def testMethodWithThreeParamers(self):
- '''Method with 3 parameters: Time.somethingCompletelyDifferent(...)'''
- time = Time()
- result = time.somethingCompletelyDifferent(1, 2, ImplicitConv(ImplicitConv.CtorOne))
- self.assertEqual(result, Time.ThreeArgs)
-
- def testMethodWithTwoParamers(self):
- '''Method with 2 parameters: Time.somethingCompletelyDifferent(...)'''
- time = Time()
- result = time.somethingCompletelyDifferent(1, 2)
- self.assertEqual(result, Time.TwoArgs)
-
- def testMethodWithThreeParamersAndImplicitConversion(self):
- '''Method with 3 parameters, the last one triggers an implicit conversion.'''
- time = Time()
- result = time.somethingCompletelyDifferent(1, 2, ImplicitConv.CtorOne)
- self.assertEqual(result, Time.ThreeArgs)
-
- def testCompareWithPythonTime(self):
- time = Time(12, 32, 5)
- py = datetime.time(12, 32, 5)
- self.assertEqual(time, py)
-
- def testNotEqual(self):
- time = Time(12, 32, 6)
- py = datetime.time(12, 32, 5)
- self.assertNotEqual(time, py)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/transform_test.py b/sources/shiboken2/tests/samplebinding/transform_test.py
deleted file mode 100644
index 5369ec466..000000000
--- a/sources/shiboken2/tests/samplebinding/transform_test.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for argument modification with more than nine arguments.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Point, applyHomogeneousTransform
-
-class TransformTest(unittest.TestCase):
- '''Test cases for modifying a function with > 9 arguments.'''
-
- def testTransform_ValidMatrix(self):
- '''Transform applies successfully.'''
- p = Point(3, 4)
- r = applyHomogeneousTransform(p, 0, 1, 0, -1, 0, 0, 0, 0, 1)
- self.assertTrue(type(r) is Point)
- self.assertEqual(r.x(), 4)
- self.assertEqual(r.y(), -3)
-
- def testTransform_InvalidMatrix(self):
- '''Transform does not apply successfully.'''
- p = Point(3, 4)
- r = applyHomogeneousTransform(p, 1, 0, 0, 0, 1, 0, 0, 0, 0)
- self.assertTrue(r is None)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/typeconverters_test.py b/sources/shiboken2/tests/samplebinding/typeconverters_test.py
deleted file mode 100644
index 33f3b62e5..000000000
--- a/sources/shiboken2/tests/samplebinding/typeconverters_test.py
+++ /dev/null
@@ -1,196 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Tests various usages of the type converters.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import sample
-
-class GetPythonTypeByNameTest(unittest.TestCase):
-
- '''Uses an added function with inject code that uses the libshiboken
- function "Shiboken::Conversions::getPythonTypeObject(typeName)".'''
-
- def testGetObjectType(self):
- pyType1 = sample.getPythonType('ObjectType')
- self.assertEqual(pyType1, sample.ObjectType)
- pyType2 = sample.getPythonType('ObjectType*')
- self.assertEqual(pyType2, sample.ObjectType)
- self.assertEqual(pyType1, pyType2)
-
- def testGetValueType(self):
- pyType1 = sample.getPythonType('Point')
- self.assertEqual(pyType1, sample.Point)
- pyType2 = sample.getPythonType('Point*')
- self.assertEqual(pyType2, sample.Point)
- self.assertEqual(pyType1, pyType2)
-
- def testGetUsersPrimitiveType(self):
- pyType = sample.getPythonType('OddBool')
- self.assertEqual(pyType, bool)
-
- def testGetUsersPrimitiveTypeWithoutTargetLangApiName(self):
- '''If the primitive type attribute "target-lang-api-name" is not set
- there'll be no Python type associated with the C++ type.'''
- pyType = sample.getPythonType('PStr')
- self.assertEqual(pyType, None)
-
- def testPrimitiveTypeAndTypedef(self):
- pyType = sample.getPythonType('double')
- self.assertEqual(pyType, float)
- pyTypedef = sample.getPythonType('real')
- self.assertEqual(pyType, pyTypedef)
-
- def testPairContainerType(self):
- pyType = sample.getPythonType('std::pair<Complex,int>')
- self.assertEqual(pyType, list)
-
- def testListContainerType(self):
- pyType = sample.getPythonType('std::list<int>')
- self.assertEqual(pyType, list)
-
- def testMapContainerType(self):
- pyType = sample.getPythonType('std::map<std::string,int>')
- self.assertEqual(pyType, dict)
-
- def testGlobalEnumType(self):
- pyType = sample.getPythonType('GlobalEnum')
- self.assertEqual(pyType, sample.GlobalEnum)
-
- def testScopedEnumType(self):
- pyType = sample.getPythonType('Abstract::Type')
- self.assertEqual(pyType, sample.Abstract.Type)
-
-
-class CheckValueAndObjectTypeByNameTest(unittest.TestCase):
-
- '''Uses an added function with inject code that uses the libshiboken
- functions that check if a type is Object or Value, based on its converter.'''
-
- def testErrors(self):
- '''not existent type'''
- self.assertRaises(ValueError, sample.cppTypeIsValueType, 'NotExistentType')
- self.assertRaises(ValueError, sample.cppTypeIsObjectType, 'NotExistentType')
-
- def testObjectType1(self):
- self.assertTrue(sample.cppTypeIsObjectType('ObjectType'))
- self.assertFalse(sample.cppTypeIsValueType('ObjectType'))
-
- def testObjectType2(self):
- self.assertTrue(sample.cppTypeIsObjectType('ObjectType*'))
- self.assertFalse(sample.cppTypeIsValueType('ObjectType*'))
-
- def testValueType1(self):
- self.assertTrue(sample.cppTypeIsValueType('Point'))
- self.assertFalse(sample.cppTypeIsObjectType('Point'))
-
- def testValueType2(self):
- self.assertTrue(sample.cppTypeIsValueType('Point*'))
- self.assertFalse(sample.cppTypeIsObjectType('Point*'))
-
- def testUsersPrimitiveType(self):
- self.assertFalse(sample.cppTypeIsValueType('Complex'))
- self.assertFalse(sample.cppTypeIsObjectType('Complex'))
-
- def testContainerType(self):
- self.assertFalse(sample.cppTypeIsValueType('std::list<int>'))
- self.assertFalse(sample.cppTypeIsObjectType('std::list<int>'))
-
-
-class SpecificConverterTest(unittest.TestCase):
-
- '''Uses an added function with inject code that uses the libshiboken
- adapter class "Shiboken::Conversions::SpecificConverter".'''
-
- def testNotExistentType(self):
- conversion = sample.getConversionTypeString('NotExistentType')
- self.assertEqual(conversion, 'Invalid conversion')
-
- def testObjectType(self):
- conversion = sample.getConversionTypeString('ObjectType')
- self.assertEqual(conversion, 'Pointer conversion')
- conversion = sample.getConversionTypeString('ObjectType*')
- self.assertEqual(conversion, 'Pointer conversion')
- conversion = sample.getConversionTypeString('ObjectType&')
- self.assertEqual(conversion, 'Reference conversion')
-
- def testValueType(self):
- conversion = sample.getConversionTypeString('Point')
- self.assertEqual(conversion, 'Copy conversion')
- conversion = sample.getConversionTypeString('Point*')
- self.assertEqual(conversion, 'Pointer conversion')
- conversion = sample.getConversionTypeString('Point&')
- self.assertEqual(conversion, 'Reference conversion')
-
-
-class StringBasedConversionTest(unittest.TestCase):
-
- def testValueType(self):
- pts = (sample.Point(1, 1), sample.Point(2, 2), sample.Point(3, 3))
- result = sample.convertValueTypeToCppAndThenToPython(pts[0], pts[1], pts[2])
- for orig, new in zip(pts, result):
- self.assertEqual(orig, new)
- self.assertFalse(pts[0] is result[0])
- self.assertTrue(pts[1] is result[1])
- self.assertTrue(pts[2] is result[2])
-
- def testObjectType(self):
- objs = (sample.ObjectType(), sample.ObjectType())
- objs[0].setObjectName('obj0')
- objs[1].setObjectName('obj1')
- result = sample.convertObjectTypeToCppAndThenToPython(objs[0], objs[1])
- for orig, new in zip(objs, result):
- self.assertEqual(orig, new)
- self.assertEqual(orig.objectName(), new.objectName())
- self.assertTrue(orig is new)
-
- def testContainerType(self):
- lst = range(4)
- result = sample.convertListOfIntegersToCppAndThenToPython(lst)
- self.assertTrue(len(result), 1)
- self.assertTrue(lst, result[0])
-
- def testCppPrimitiveType(self):
- integers = (12, 34)
- result = sample.convertIntegersToCppAndThenToPython(integers[0], integers[1])
- for orig, new in zip(integers, result):
- self.assertEqual(orig, new)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/typedealloc_test.py b/sources/shiboken2/tests/samplebinding/typedealloc_test.py
deleted file mode 100644
index b79b6de0e..000000000
--- a/sources/shiboken2/tests/samplebinding/typedealloc_test.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test deallocation of type extended in Python.'''
-
-import gc
-import os
-import sys
-import unittest
-import weakref
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Point
-
-
-class TypeDeallocTest(unittest.TestCase):
-
- def setUp(self):
- self.called = False
-
- def tearDown(self):
- del self.called
-
- def callback(self, *args):
- self.called = True
-
- def testScopeEnd(self):
- ref = None
- def scope():
- class Ext(Point):
- pass
- o = Ext()
- global ref
- ref = weakref.ref(Ext, self.callback)
- scope()
- gc.collect()
- self.assertTrue(self.called)
-
- def testDeleteType(self):
- class Ext(Point):
- pass
- ref = weakref.ref(Ext, self.callback)
- del Ext
- gc.collect()
- self.assertTrue(self.called)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/typedtordoublefree_test.py b/sources/shiboken2/tests/samplebinding/typedtordoublefree_test.py
deleted file mode 100644
index 8cf93866f..000000000
--- a/sources/shiboken2/tests/samplebinding/typedtordoublefree_test.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import ObjectType
-
-class TestTypeDestructorDoubleFree(unittest.TestCase):
- def testTypeDestructorDoubleFree(self):
- '''Causes the type destructors of two derived classes to be called.'''
- def scope():
- class ExtObj1(ObjectType):
- def __init__(self):
- ObjectType.__init__(self)
- obj = ExtObj1()
- child = ObjectType(parent=obj)
- self.assertEqual(obj.takeChild(child), child)
- class ExtObj2(ObjectType):
- def __init__(self):
- ObjectType.__init__(self)
- obj = ExtObj2()
- child = ObjectType(parent=obj)
- self.assertEqual(obj.takeChild(child), child)
- scope()
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/typesystem_sample.xml b/sources/shiboken2/tests/samplebinding/typesystem_sample.xml
deleted file mode 100644
index 32df8fd7b..000000000
--- a/sources/shiboken2/tests/samplebinding/typesystem_sample.xml
+++ /dev/null
@@ -1,2465 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<typesystem package="sample">
- <suppress-warning text="Duplicate type entry: 'sample'" />
- <suppress-warning text="Duplicate type entry: 'SampleNamespace'" />
-
- <custom-type name="str"/>
- <custom-type name="PyBytes"/>
- <custom-type name="PyDate"/>
- <custom-type name="PyObject"/>
- <custom-type name="PyUnicode"/>
-
- <primitive-type name="bool"/>
- <primitive-type name="double"/>
- <primitive-type name="real"/>
- <primitive-type name="int"/>
- <primitive-type name="short"/>
- <primitive-type name="unsigned short"/>
- <primitive-type name="ushort"/>
- <primitive-type name="unsigned int" />
- <primitive-type name="signed int" />
- <primitive-type name="char"/>
- <primitive-type name="unsigned char"/>
- <primitive-type name="long"/>
- <primitive-type name="unsigned long"/>
- <primitive-type name="long long"/>
- <primitive-type name="unsigned long long"/>
- <primitive-type name="std::string"/>
- <primitive-type name="ObjectType::Identifier"/>
-
- <primitive-type name="Foo::HANDLE" target-lang-api-name="PyLong"/>
-
- <primitive-type name="std::size_t" target-lang-api-name="PyLong">
- <conversion-rule>
- <native-to-target>
- return PyLong_FromSize_t(%in);
- </native-to-target>
- <target-to-native>
- <add-conversion type="PyLong">
- %out = %OUTTYPE(PyLong_AsSsize_t(%in));
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <inject-code class="native" position="beginning">
- static bool Check2TupleOfNumbers(PyObject* pyIn) {
- if (!PySequence_Check(pyIn) || !(PySequence_Size(pyIn) == 2))
- return false;
- Shiboken::AutoDecRef pyReal(PySequence_GetItem(pyIn, 0));
- if (!SbkNumber_Check(pyReal))
- return false;
- Shiboken::AutoDecRef pyImag(PySequence_GetItem(pyIn, 1));
- if (!SbkNumber_Check(pyImag))
- return false;
- return true;
- }
- </inject-code>
- <primitive-type name="Complex" target-lang-api-name="PyComplex">
- <include file-name="complex.h" location="global"/>
- <conversion-rule>
- <native-to-target>
- return PyComplex_FromDoubles(%in.real(), %in.imag());
- </native-to-target>
- <target-to-native>
- <!-- The 'check' attribute can be derived from the 'type' attribute,
- it is defined here to test the CHECKTYPE type system variable. -->
- <add-conversion type="PyComplex" check="%CHECKTYPE[Complex](%in)">
- double real = PyComplex_RealAsDouble(%in);
- double imag = PyComplex_ImagAsDouble(%in);
- %out = %OUTTYPE(real, imag);
- </add-conversion>
- <add-conversion type="PySequence" check="Check2TupleOfNumbers(%in)">
- Shiboken::AutoDecRef pyReal(PySequence_GetItem(%in, 0));
- Shiboken::AutoDecRef pyImag(PySequence_GetItem(%in, 1));
- double real = %CONVERTTOCPP[double](pyReal);
- double imag = %CONVERTTOCPP[double](pyImag);
- %out = %OUTTYPE(real, imag);
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <primitive-type name="Null">
- <include file-name="null.h" location="global"/>
- <conversion-rule>
- <native-to-target>
- SBK_UNUSED(%in);
- Py_RETURN_NONE;
- </native-to-target>
- <target-to-native>
- <add-conversion type="PyObject" check="%in == 0 || %in == Py_None">
- %out = %OUTTYPE(%in == 0);
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <primitive-type name="HANDLE" target-lang-api-name="PyComplex">
- <include file-name="handle.h" location="local"/>
- <conversion-rule>
- <native-to-target>
- if (!%in)
- Py_RETURN_NONE;
- #ifdef IS_PY3K
- return PyCapsule_New(%in, 0, 0);
- #else
- return PyCObject_FromVoidPtr(%in, 0);
- #endif
- </native-to-target>
- <target-to-native>
- <add-conversion type="PyNone">
- %out = 0;
- </add-conversion>
- <add-conversion check="checkPyCapsuleOrPyCObject(%in)" type="PyObject">
- void* ptr;
- #ifdef IS_PY3K
- ptr = PyCapsule_GetPointer(%in, 0);
- #else
- ptr = PyCObject_AsVoidPtr(%in);
- #endif
- %out = (%OUTTYPE)ptr;
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <inject-code class="native" position="beginning">
- static bool checkPyCapsuleOrPyCObject(PyObject* pyObj)
- {
- #ifdef IS_PY3K
- return PyCapsule_CheckExact(pyObj);
- #else
- return PyCObject_Check(pyObj);
- #endif
- }
- </inject-code>
-
- <primitive-type name="PrimitiveStructPtr">
- <include file-name="handle.h" location="local"/>
- <conversion-rule>
- <native-to-target>
- #ifdef IS_PY3K
- return PyCapsule_New(&amp;%in, 0, 0);
- #else
- return PyCObject_FromVoidPtr(&amp;%in, 0);
- #endif
- </native-to-target>
- <target-to-native>
- <add-conversion check="checkPyCapsuleOrPyCObject(%in)" type="PyObject">
- void* ptr;
- #ifdef IS_PY3K
- ptr = PyCapsule_GetPointer(%in, 0);
- #else
- ptr = PyCObject_AsVoidPtr(%in);
- #endif
- %out = *((%OUTTYPE*)ptr);
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <primitive-type name="OddBool" target-lang-api-name="PyBool" default-constructor="OddBool(false)">
- <include file-name="oddbool.h" location="global"/>
- <include file-name="complex.h" location="global"/>
- <conversion-rule>
- <native-to-target>
- return PyBool_FromLong(%in.value());
- </native-to-target>
- <target-to-native>
- <add-conversion type="PyBool">
- // Tests CONVERTTOCPP macro with C++ primitive type.
- bool b = %CONVERTTOCPP[bool](%in);
- %out = %OUTTYPE(b);
- </add-conversion>
- <add-conversion type="PyComplex">
- // Tests CONVERTTOCPP macro with user's primitive type.
- Complex cpx = %CONVERTTOCPP[Complex](%in);
- %out = %OUTTYPE(cpx.real() != 0.0 || cpx.imag() != 0.0);
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <primitive-type name="PStr">
- <include file-name="str.h" location="global"/>
- <conversion-rule>
- <native-to-target>
- return Shiboken::String::fromCString(%in.cstring(), %in.size());
- </native-to-target>
- <target-to-native>
- <add-conversion type="PyUnicode" check="Shiboken::String::check(%in)">
- const char* str = %CONVERTTOCPP[const char*](%in);
- %out = %OUTTYPE(str);
- </add-conversion>
- <add-conversion type="Py_None">
- %out = %OUTTYPE();
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <function signature="changePStr(PStr*, const char*)">
- <!--
- Comment out these modifications and the Shiboken generator
- will issue a fatal error, because it can't handle a pointer
- to a primitive type (PStr*) without help from the binding
- developer.
- -->
- <modify-function signature="changePStr(PStr*, const char*)">
- <modify-argument index="1">
- <replace-type modified-type="PStr"/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- %FUNCTION_NAME(&amp;%1, %2);
- %PYARG_0 = %CONVERTTOPYTHON[PStr](%1);
- </inject-code>
- </modify-function>
- </function>
-
- <function signature="duplicatePStr(PStr*)">
- <modify-function signature="duplicatePStr(PStr*)">
- <modify-argument index="return">
- <replace-type modified-type="PyObject"/>
- </modify-argument>
- <modify-argument index="1">
- <replace-type modified-type="PStr"/>
- <replace-default-expression with="PStr()"/>
- </modify-argument>
- <inject-code class="target" position="end">
- %FUNCTION_NAME(&amp;%1);
- %PYARG_0 = %CONVERTTOPYTHON[PStr](%1);
- </inject-code>
- </modify-function>
- </function>
-
- <primitive-type name="PStrList">
- <include file-name="strlist.h" location="global"/>
- <conversion-rule>
- <native-to-target>
- PyObject* %out = PyList_New((int) %in.size());
- PStrList::const_iterator it = %in.begin();
- for (int idx = 0; it != %in.end(); ++it, ++idx) {
- PStr cppItem(*it);
- PyList_SET_ITEM(%out, idx, %CONVERTTOPYTHON[PStr](cppItem));
- }
- return %out;
- </native-to-target>
- <target-to-native>
- <add-conversion type="PySequence">
- %OUTTYPE&amp; list = %out;
- Shiboken::AutoDecRef seq(PySequence_Fast(%in, 0));
- for (int i = 0; i &lt; PySequence_Fast_GET_SIZE(seq.object()); i++) {
- PyObject* pyItem = PySequence_Fast_GET_ITEM(seq.object(), i);
- PStr cppItem = %CONVERTTOCPP[PStr](pyItem);
- list.push_back(cppItem);
- }
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </primitive-type>
-
- <add-function signature="createPStrList(PStr, PStr)" return-type="PyObject">
- <inject-code class="target">
- PStrList %0;
- %0.push_back(%1);
- %0.push_back(%2);
- %PYARG_0 = %CONVERTTOPYTHON[PStrList](%0);
- </inject-code>
- </add-function>
- <add-function signature="createListOfPStr(PStr, PStr)" return-type="PyObject">
- <inject-code class="target">
- std::list&lt;PStr&gt; %0;
- %0.push_back(%1);
- %0.push_back(%2);
- %PYARG_0 = %CONVERTTOPYTHON[std::list&lt;PStr&gt;](%0);
- </inject-code>
- </add-function>
-
- <add-function signature="getPythonType(const char*)" return-type="PyObject">
- <inject-code class="target" position="beginning">
- %PYARG_0 = (PyObject*) Shiboken::Conversions::getPythonTypeObject(%1);
- if (!%PYARG_0)
- %PYARG_0 = Py_None;
- Py_INCREF(%PYARG_0);
- </inject-code>
- </add-function>
-
- <template name="cpp_type_is_object_or_value_type">
- SbkConverter* converter = Shiboken::Conversions::getConverter(%1);
- if (converter) {
- if (Shiboken::Conversions::pythonTypeIs$TYPEType(converter))
- %PYARG_0 = Py_True;
- else
- %PYARG_0 = Py_False;
- Py_INCREF(%PYARG_0);
- } else {
- PyErr_Format(PyExc_ValueError, "Type '%s' has no converter associated to it", %1);
- }
- </template>
- <add-function signature="cppTypeIsObjectType(const char*)" return-type="bool">
- <inject-code class="target" position="beginning">
- <insert-template name="cpp_type_is_object_or_value_type">
- <replace from="$TYPE" to="Object" />
- </insert-template>
- </inject-code>
- </add-function>
- <add-function signature="cppTypeIsValueType(const char*)" return-type="bool">
- <inject-code class="target" position="beginning">
- <insert-template name="cpp_type_is_object_or_value_type">
- <replace from="$TYPE" to="Value" />
- </insert-template>
- </inject-code>
- </add-function>
-
- <add-function signature="getConversionTypeString(const char*)" return-type="PyObject">
- <inject-code class="target" position="beginning">
- Shiboken::Conversions::SpecificConverter converter(%1);
- const char* %0 = 0;
- switch (converter.conversionType()) {
- case Shiboken::Conversions::SpecificConverter::CopyConversion:
- %0 = "Copy conversion";
- break;
- case Shiboken::Conversions::SpecificConverter::PointerConversion:
- %0 = "Pointer conversion";
- break;
- case Shiboken::Conversions::SpecificConverter::ReferenceConversion:
- %0 = "Reference conversion";
- break;
- default:
- %0 = "Invalid conversion";
- }
- %PYARG_0 = %CONVERTTOPYTHON[const char*](%0);
- </inject-code>
- </add-function>
-
- <inject-code class="native" position="beginning">
- static PyObject* __convertCppValuesToPython(const char** typeName, void** values, int size)
- {
- PyObject* result = PyTuple_New(size);
- for (int i = 0; i &lt; size; ++i) {
- Shiboken::Conversions::SpecificConverter converter(typeName[i]);
- PyTuple_SET_ITEM(result, i, converter.toPython(values[i]));
- }
- return result;
- }
- </inject-code>
- <add-function signature="convertValueTypeToCppAndThenToPython(Point,Point*,Point&amp;)" return-type="PyObject">
- <inject-code class="target" position="beginning">
- const char* typeNames[] = { "Point", "Point*", "Point&amp;" };
- void* values[] = { &amp;%1, &amp;%2, &amp;(%3) };
- %PYARG_0 = __convertCppValuesToPython(typeNames, values, 3);
- </inject-code>
- </add-function>
- <add-function signature="convertObjectTypeToCppAndThenToPython(ObjectType*,ObjectType&amp;)" return-type="PyObject">
- <inject-code class="target" position="beginning">
- const char* typeNames[] = { "ObjectType*", "ObjectType&amp;" };
- void* values[] = { &amp;%1, &amp;(%2) };
- %PYARG_0 = __convertCppValuesToPython(typeNames, values, 2);
- </inject-code>
- </add-function>
- <add-function signature="convertListOfIntegersToCppAndThenToPython(std::list&lt;int&gt;)" return-type="PyObject">
- <inject-code class="target" position="beginning">
- const char* typeNames[] = { "std::list&lt;int&gt;" };
- void* values[] = { &amp;%1 };
- %PYARG_0 = __convertCppValuesToPython(typeNames, values, 1);
- </inject-code>
- </add-function>
- <add-function signature="convertIntegersToCppAndThenToPython(int,int)" return-type="PyObject">
- <inject-code class="target" position="beginning">
- const char* typeNames[] = { "int", "int" };
- void* values[] = { &amp;%1, &amp;%2 };
- %PYARG_0 = __convertCppValuesToPython(typeNames, values, 2);
- </inject-code>
- </add-function>
-
- <container-type name="std::pair" type="pair">
- <include file-name="utility" location="global"/>
- <conversion-rule>
- <native-to-target>
- PyObject* %out = PyTuple_New(2);
- PyTuple_SET_ITEM(%out, 0, %CONVERTTOPYTHON[%INTYPE_0](%in.first));
- PyTuple_SET_ITEM(%out, 1, %CONVERTTOPYTHON[%INTYPE_1](%in.second));
- return %out;
- </native-to-target>
- <target-to-native>
- <add-conversion type="PySequence">
- %out.first = %CONVERTTOCPP[%OUTTYPE_0](PySequence_Fast_GET_ITEM(%in, 0));
- %out.second = %CONVERTTOCPP[%OUTTYPE_1](PySequence_Fast_GET_ITEM(%in, 1));
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </container-type>
- <template name="cpplist_to_pylist_convertion">
- PyObject* %out = PyList_New((int) %in.size());
- %INTYPE::const_iterator it = %in.begin();
- for (int idx = 0; it != %in.end(); ++it, ++idx) {
- %INTYPE_0 cppItem(*it);
- PyList_SET_ITEM(%out, idx, %CONVERTTOPYTHON[%INTYPE_0](cppItem));
- }
- return %out;
- </template>
- <template name="pyseq_to_cpplist_convertion">
- Shiboken::AutoDecRef seq(PySequence_Fast(%in, 0));
- for (int i = 0; i &lt; PySequence_Fast_GET_SIZE(seq.object()); i++) {
- PyObject* pyItem = PySequence_Fast_GET_ITEM(seq.object(), i);
- %OUTTYPE_0 cppItem = %CONVERTTOCPP[%OUTTYPE_0](pyItem);
- %out.push_back(cppItem);
- }
- </template>
- <container-type name="std::list" type="list">
- <include file-name="list" location="global"/>
- <conversion-rule>
- <native-to-target>
- <insert-template name="cpplist_to_pylist_convertion"/>
- </native-to-target>
- <target-to-native>
- <add-conversion type="PySequence">
- <insert-template name="pyseq_to_cpplist_convertion"/>
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </container-type>
- <container-type name="List" type="list">
- <include file-name="list" location="global"/>
- <conversion-rule>
- <native-to-target>
- <insert-template name="cpplist_to_pylist_convertion"/>
- </native-to-target>
- <target-to-native>
- <add-conversion type="PySequence">
- <insert-template name="pyseq_to_cpplist_convertion"/>
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </container-type>
- <container-type name="std::map" type="map">
- <include file-name="map" location="global"/>
- <conversion-rule>
- <native-to-target>
- PyObject* %out = PyDict_New();
- %INTYPE::const_iterator it = %in.begin();
- for (; it != %in.end(); ++it) {
- %INTYPE_0 key = it->first;
- %INTYPE_1 value = it->second;
- PyDict_SetItem(%out,
- %CONVERTTOPYTHON[%INTYPE_0](key),
- %CONVERTTOPYTHON[%INTYPE_1](value));
- }
- return %out;
- </native-to-target>
- <target-to-native>
- <add-conversion type="PyDict">
- PyObject* key;
- PyObject* value;
- Py_ssize_t pos = 0;
- while (PyDict_Next(%in, &amp;pos, &amp;key, &amp;value)) {
- %OUTTYPE_0 cppKey = %CONVERTTOCPP[%OUTTYPE_0](key);
- %OUTTYPE_1 cppValue = %CONVERTTOCPP[%OUTTYPE_1](value);
- %out.insert(%OUTTYPE::value_type(cppKey, cppValue));
- }
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </container-type>
-
- <add-function signature="cacheSize()" return-type="int">
- <inject-code class="target">
- %RETURN_TYPE %0 = Shiboken::BindingManager::instance().getAllPyObjects().size();
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
-
- <namespace-type name="sample">
- <value-type name="sample" />
- </namespace-type>
-
- <function signature="sumComplexPair(std::pair&lt;Complex, Complex>)" />
- <function signature="gimmeComplexList()" />
- <function signature="transmuteComplexIntoPoint(const Complex&amp;)" />
- <function signature="transmutePointIntoComplex(const Point&amp;)" />
- <function signature="sumComplexPair(std::pair&lt;Complex, Complex>)" />
- <function signature="doubleUnsignedInt(unsigned int)" />
- <function signature="doubleLongLong(long long)" />
- <function signature="doubleUnsignedLongLong(unsigned long long)" />
- <function signature="doubleShort(short)" />
- <function signature="returnNullPrimitivePointer()" />
- <function signature="returnNullValueTypePointer()" />
- <function signature="returnNullObjectTypePointer()" />
- <function signature="acceptInt(int)" />
- <function signature="acceptUInt(unsigned int)" />
- <function signature="acceptLong(long)" />
- <function signature="acceptULong(unsigned long)" />
- <function signature="acceptDouble(double)" />
- <function signature="acceptIntReference(int&amp;)" />
- <function signature="acceptOddBoolReference(OddBool&amp;)" />
- <function signature="countCharacters(const char*)" />
- <function signature="gimmeInt()" />
- <function signature="gimmeDouble()" />
- <function signature="makeCString()" />
- <function signature="sumIntArray(int[4])"/>
- <function signature="sumDoubleArray(double[4])"/>
- <function signature="sumIntMatrix(int[2][3])"/>
- <function signature="sumDoubleMatrix(double[2][3])"/>
- <function signature="multiplyPair(std::pair&lt;double, double>)" />
- <function signature="returnCString()" />
- <function signature="overloadedFunc(double)" />
- <function signature="overloadedFunc(int)" />
-
- <value-type name="ArrayModifyTest">
- <modify-function signature="sumIntArray(int, int*)">
- <modify-argument index="2"><array/></modify-argument>
- </modify-function>
- </value-type>
-
- <value-type name="ClassWithFunctionPointer">
- <suppress-warning text="skipping function 'ClassWithFunctionPointer::callFunctionPointer', unmatched parameter type 'void (*)(void*)'" />
- </value-type>
-
- <value-type name="IntArray" generate="no"/>
- <value-type name="IntArray2">
- <modify-function signature="IntArray2(const int*)">
- <modify-argument index="1"><array/></modify-argument>
- </modify-function>
- </value-type>
-
- <value-type name="IntArray3">
- <modify-function signature="IntArray3(const int*)">
- <modify-argument index="1"><array/></modify-argument>
- </modify-function>
- </value-type>
-
- <enum-type name="OverloadedFuncEnum"/>
- <!-- BUG:
- renaming the ICOverloadedFuncEnum to the same name
- of a global enum causes the generator to confuse the
- two types.
- -->
- <enum-type name="GlobalEnum"/>
- <enum-type name="GlobalOverloadFuncEnum"/>
-
- <enum-type identified-by-value="AnonymousGlobalEnum_Value0"/>
-
- <namespace-type name="Invisible" visible="no">
- <enum-type name="EnumOnNamespace" />
- <value-type name="ObjectOnInvisibleNamespace" />
- </namespace-type>
-
- <namespace-type name="SampleNamespace">
- <enum-type name="Option"/>
- <enum-type name="InValue"/>
- <enum-type name="OutValue"/>
- <enum-type identified-by-value="AnonymousClassEnum_Value1"/>
-
- <object-type name="DerivedFromNamespace">
- <enum-type name="SampleNamespace"/>
- </object-type>
- <value-type name="SomeClass">
- <enum-type name="PublicScopedEnum"/>
- <value-type name="SomeInnerClass">
- <object-type name="OkThisIsRecursiveEnough">
- <enum-type name="NiceEnum" />
- <enum-type name="NiceEnumClass" />
- </object-type>
- <enum-type name="ProtectedEnum"/>
- </value-type>
- <value-type name="SomeOtherInnerClass"/>
- <enum-type name="ProtectedEnum"/>
- </value-type>
-
- <modify-function signature="doSomethingWithArray(const unsigned char*, unsigned int, const char*)">
- <modify-argument index="1">
- <replace-type modified-type="const char*"/>
- <conversion-rule class="native">
- const unsigned char* %out = reinterpret_cast&lt;const unsigned char*>(Shiboken::String::toCString(%PYARG_1));
- </conversion-rule>
- </modify-argument>
- <modify-argument index="2">
- <remove-argument/>
- <conversion-rule class="native">
- unsigned int %out = static_cast&lt;unsigned int>(Shiboken::String::len(%PYARG_1));
- </conversion-rule>
- </modify-argument>
- </modify-function>
- <add-function signature="ImInsideANamespace(int, int)" return-type="int">
- <inject-code class="target">
- %RETURN_TYPE %0 = %1 + %2;
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
- <add-function signature="passReferenceToValueType(Point&amp;)" return-type="double">
- <inject-code>
- %RETURN_TYPE %0 = %1.x() + %1.y();
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
-
- <!-- Do change the argument from pointer to reference to comply with the C++ overload
- of this function. The generator must be able to deal with this for Object Types. -->
- <add-function signature="passReferenceToObjectType(ObjectType*)" return-type="int">
- <inject-code>
- // The dot in "%1." must be replaced with a "->" by the generator.
- %RETURN_TYPE %0 = %1.objectName().size();
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
- </namespace-type>
-
- <namespace-type name="RemovedNamespace1" generate='no'>
- <enum-type name="RemovedNamespace1_Enum" />
- <namespace-type name="RemovedNamespace2" generate='no'>
- <enum-type name="RemovedNamespace2_Enum" />
- </namespace-type>
- <enum-type identified-by-value="RemovedNamespace1_AnonymousEnum_Value0" />
- </namespace-type>
-
- <namespace-type name="UnremovedNamespace">
- <namespace-type name="RemovedNamespace3" generate='no'>
- <enum-type name="RemovedNamespace3_Enum" />
- <enum-type identified-by-value="RemovedNamespace3_AnonymousEnum_Value0" />
- </namespace-type>
- </namespace-type>
-
- <namespace-type name="Photon">
- <enum-type name="ClassType"/>
- <value-type name="Base"/>
- <value-type name="TemplateBase" generate="no"/>
- <value-type name="ValueIdentity"/>
- <value-type name="ValueDuplicator"/>
- </namespace-type>
-
- <value-type name="CVValueType"/>
- <value-type name="CVListUser"/>
-
- <value-type name="IntList">
- <enum-type name="CtorEnum"/>
- </value-type>
- <value-type name="PointValueList">
- <enum-type name="CtorEnum"/>
- </value-type>
- <value-type name="ObjectTypePtrList">
- <enum-type name="CtorEnum"/>
- </value-type>
-
- <object-type name="Abstract">
- <enum-type name="Type"/>
- <enum-type name="PrintFormat"/>
- <modify-function signature="id()" rename="id_"/>
- <modify-function signature="hideFunction(HideType*)" remove="all"/>
- </object-type>
-
- <object-type name="Derived" polymorphic-id-expression="%1->type() == Derived::TpDerived">
- <enum-type name="OtherOverloadedFuncEnum"/>
- <value-type name="SomeInnerClass" />
- </object-type>
-
- <object-type name="ModifiedConstructor">
- <modify-function signature="ModifiedConstructor(int)">
- <modify-argument index="1">
- <replace-type modified-type="str"/>
- </modify-argument>
- <inject-code class='target' position='beginning'>
- const char* tmpArg = %CONVERTTOCPP[const char*](%PYARG_1);
- %0 = new %FUNCTION_NAME(atoi(tmpArg));
- </inject-code>
- </modify-function>
- </object-type>
-
- <object-type name="ObjectType" hash-function="objectTypeHash">
- <modify-function signature="deprecatedFunction()" deprecated="yes" />
- <!-- rename function to avoid Python signature conflit -->
- <modify-function signature="setObject(const Null&amp;)" rename="setNullObject" />
-
- <modify-function signature="getCppParent()">
- <modify-argument index="this">
- <parent index="return" action="add" />
- </modify-argument>
- <modify-argument index="return">
- <define-ownership class="target" owner="default"/>
- </modify-argument>
- </modify-function>
-
- <modify-function signature="event(Event*)">
- <modify-argument index="1" invalidate-after-use="yes"/>
- </modify-function>
- <modify-function signature="invalidateEvent(Event*)">
- <modify-argument index="1" invalidate-after-use="yes"/>
- </modify-function>
- <modify-function signature="create()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="createWithChild()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="setParent(ObjectType*)">
- <modify-argument index="this">
- <parent index="1" action="add"/>
- </modify-argument>
- </modify-function>
- <inject-code class="native" position="beginning">
- static void reparent_layout_items(PyObject* parent, PyObject* layout)
- {
- // CHECKTYPE and ISCONVERTIBLE are used here for test purposes, don't change them.
- if (!%CHECKTYPE[ObjectTypeLayout*](layout) &amp;&amp; !%ISCONVERTIBLE[ObjectTypeLayout*](layout))
- return;
- // %CHECKTYPE[ObjectTypeLayout*](layout)
- // %ISCONVERTIBLE[ObjectTypeLayout*](layout)
- ObjectTypeLayout* var;
- var = %CONVERTTOCPP[ObjectTypeLayout*](layout);
- // TODO-CONVERTER: erase this
- /*
- ObjectTypeLayout* var2 = %CONVERTTOCPP[ObjectTypeLayout*](layout);
- */
- const ObjectTypeList&amp; objChildren = var->objects();
- ObjectTypeList::const_iterator it = objChildren.begin();
- for (; it != objChildren.end(); ++it) {
- if ((*it)->isLayoutType()) {
- ObjectTypeLayout* l = reinterpret_cast&lt;ObjectTypeLayout*>(*it);
- reparent_layout_items(parent, %CONVERTTOPYTHON[ObjectTypeLayout*](l));
- Shiboken::Object::setParent(layout, %CONVERTTOPYTHON[ObjectTypeLayout*](l));
- } else {
- Shiboken::Object::setParent(parent, %CONVERTTOPYTHON[ObjectType*](*it));
- }
- }
- }
- </inject-code>
- <modify-function signature="setLayout(ObjectTypeLayout*)">
- <modify-argument index="1">
- <parent index="this" action="add"/>
- </modify-argument>
- <inject-code class="target" position="end">
- if (%PYARG_1 != Py_None)
- reparent_layout_items(%PYSELF, %PYARG_1);
- </inject-code>
- </modify-function>
- <modify-function signature="takeChild(ObjectType*)">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- <parent index="this" action="remove"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="takeChild(const Str&amp;)">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- <parent index="this" action="remove"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="findChild(const Str&amp;)">
- <modify-argument index="return">
- <parent index="this" action="add"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="children()const">
- <modify-argument index="return">
- <parent index="this" action="add"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="createChild(ObjectType*)">
- <modify-argument index="return">
- <define-ownership owner="c++" />
- </modify-argument>
- </modify-function>
- <modify-function signature="nextInFocusChain()">
- <modify-argument index="return">
- <parent index="this" action="add"/>
- </modify-argument>
- </modify-function>
- </object-type>
-
- <object-type name="OtherBase" />
- <object-type name="ObjectTypeDerived" />
-
- <object-type name="ObjectTypeLayout">
- <modify-function signature="create()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- </object-type>
-
- <object-type name="ObjectView">
- <modify-function signature="ObjectView(ObjectModel*, ObjectType*)">
- <modify-argument index="1">
- <reference-count action="set" variable-name="setModel(ObjectModel*)1"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="setModel(ObjectModel*)">
- <modify-argument index="1">
- <reference-count action="set"/>
- </modify-argument>
- </modify-function>
- </object-type>
-
- <value-type name="ObjectTypeHolder"/>
- <value-type name="OnlyCopy"/>
- <value-type name="FriendOfOnlyCopy"/>
-
- <object-type name="ObjectModel">
- <enum-type name="MethodCalled" />
- <modify-function signature="data() const">
- <modify-argument index="return">
- <define-ownership class="native" owner="c++"/>
- </modify-argument>
- </modify-function>
- </object-type>
-
- <value-type name="Event">
- <enum-type name="EventType"/>
- <enum-type name="EventTypeClass"/>
- </value-type>
-
- <value-type name="BlackBox">
- <modify-function signature="keepObjectType(ObjectType*)">
- <modify-argument index="1">
- <define-ownership owner="c++"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="retrieveObjectType(int)">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="keepPoint(Point*)">
- <modify-argument index="1">
- <define-ownership owner="c++"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="retrievePoint(int)">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- </value-type>
-
- <value-type name="ProtectedNonPolymorphic">
- <modify-function signature="create()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="modifiedProtectedSum(int, int)">
- <inject-code class="target" position="beginning">
- %RETURN_TYPE %0 = %CPPSELF.%TYPE::%FUNCTION_NAME(%1, %2) * 10;
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </modify-function>
- <modify-function signature="dataTypeName(void*) const" remove="all"/>
- <modify-function signature="dataTypeName(int) const">
- <modify-argument index="1">
- <replace-default-expression with="0"/>
- </modify-argument>
- </modify-function>
- <add-function signature="dataTypeName(PyObject*)const" return-type="const char*">
- <inject-code class="target" position="beginning">
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(%PYARG_1);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
- </value-type>
-
- <value-type name="ProtectedPolymorphic">
- <modify-function signature="create()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- </value-type>
-
- <value-type name="ProtectedPolymorphicDaughter">
- <modify-function signature="create()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- </value-type>
-
- <value-type name="ProtectedPolymorphicGrandDaughter">
- <modify-function signature="create()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- </value-type>
-
- <object-type name="ProtectedVirtualDestructor">
- <modify-function signature="create()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- </object-type>
-
-
- <object-type name="ProtectedEnumClass">
- <enum-type name="ProtectedEnum" />
- <enum-type name="PublicEnum" />
- </object-type>
-
- <value-type name="ProtectedProperty" />
-
- <function signature="createProtectedProperty()" />
-
- <template name="boolptr_at_end_fix_beginning">
- bool __ok__;
- %RETURN_TYPE %0 = %CPPSELF.%TYPE::%FUNCTION_NAME(%ARGUMENT_NAMES, &amp;__ok__);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </template>
-
- <template name="boolptr_at_start_fix_beginning">
- bool __ok__;
- %RETURN_TYPE %0 = %CPPSELF.%TYPE::%FUNCTION_NAME(&amp;__ok__, %ARGUMENT_NAMES);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </template>
-
- <template name="boolptr_at_start_and_one_arg_fix_beginning">
- bool __ok__;
- %RETURN_TYPE %0 = %CPPSELF.%TYPE::%FUNCTION_NAME(&amp;__ok__, %2);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </template>
-
- <template name="boolptr_fix_end">
- PyObject* _tuple_ = PyTuple_New(2);
- PyTuple_SET_ITEM(_tuple_, 0, %PYARG_0);
- PyObject* _item_ = %CONVERTTOPYTHON[bool](__ok__);
- PyTuple_SET_ITEM(_tuple_, 1, _item_);
- %PYARG_0 = _tuple_;
- </template>
-
- <template name="return_4_arguments_as_tuple">
- %PYARG_0 = PyTuple_New(4);
- PyTuple_SET_ITEM(%PYARG_0, 0, %CONVERTTOPYTHON[%ARG1_TYPE](%1));
- PyTuple_SET_ITEM(%PYARG_0, 1, %CONVERTTOPYTHON[%ARG2_TYPE](%2));
- PyTuple_SET_ITEM(%PYARG_0, 2, %CONVERTTOPYTHON[%ARG3_TYPE](%3));
- PyTuple_SET_ITEM(%PYARG_0, 3, %CONVERTTOPYTHON[%ARG4_TYPE](%4));
- </template>
-
- <template name="return_5_arguments_as_tuple">
- %PYARG_0 = PyTuple_New(5);
- PyTuple_SET_ITEM(%PYARG_0, 0, %CONVERTTOPYTHON[%ARG1_TYPE](%1));
- PyTuple_SET_ITEM(%PYARG_0, 1, %CONVERTTOPYTHON[%ARG2_TYPE](%2));
- PyTuple_SET_ITEM(%PYARG_0, 2, %CONVERTTOPYTHON[%ARG3_TYPE](%3));
- PyTuple_SET_ITEM(%PYARG_0, 3, %CONVERTTOPYTHON[%ARG4_TYPE](%4));
- PyTuple_SET_ITEM(%PYARG_0, 4, %CONVERTTOPYTHON[%ARG5_TYPE](%5));
- </template>
-
- <template name="return_none">
- %PYARG_0 = Py_None;
- Py_INCREF(Py_None);
- </template>
-
- <object-type name="Modifications">
- <enum-type name="OverloadedModFunc"/>
- <enum-type name="TestEnum"/>
-
- <modify-function signature="overloaded(int, bool, int, double)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- %RETURN_TYPE %0 = %CPPSELF.%TYPE::%FUNCTION_NAME(%1, true, %3, %4);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </modify-function>
-
- <modify-function signature="overloaded(int, bool, int, int)">
- <modify-argument index="3">
- <remove-argument/>
- <replace-default-expression with="321"/>
- </modify-argument>
- <!--
- <modify-argument index="4">
- <remove-default-expression/>
- </modify-argument>
- -->
- </modify-function>
-
- <modify-function signature="argRemoval0(int, bool, int, int)">
- <modify-argument index="3">
- <remove-argument/>
- <replace-default-expression with="321"/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="end">
- <insert-template name="return_4_arguments_as_tuple"/>
- </inject-code>
- </modify-function>
-
- <modify-function signature="argRemoval1(int, bool, Point, Point, int)">
- <modify-argument index="3">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="4">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="end">
- <insert-template name="return_5_arguments_as_tuple"/>
- </inject-code>
- </modify-function>
-
- <modify-function signature="argRemoval1(int, bool, int, bool)">
- <inject-code class="target" position="end">
- <insert-template name="return_none"/>
- </inject-code>
- </modify-function>
-
- <modify-function signature="argRemoval2(int, bool, Point, Point, int)">
- <modify-argument index="3">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="4">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="end">
- <insert-template name="return_5_arguments_as_tuple"/>
- </inject-code>
- </modify-function>
-
- <modify-function signature="argRemoval3(int, Point, bool, Point, int)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="4">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="end">
- <insert-template name="return_5_arguments_as_tuple"/>
- </inject-code>
- </modify-function>
-
- <modify-function signature="argRemoval4(int, Point, bool, Point, int)">
- <modify-argument index="2">
- <remove-argument/>
- <replace-default-expression with="Point(6, 9)"/>
- </modify-argument>
- <modify-argument index="4">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="end">
- <insert-template name="return_5_arguments_as_tuple"/>
- </inject-code>
- </modify-function>
-
- <modify-function signature="argRemoval5(int, bool, Point, Point, int)">
- <modify-argument index="1">
- <remove-argument/>
- <replace-default-expression with="100"/>
- </modify-argument>
- <modify-argument index="3">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="4">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="end">
- <insert-template name="return_5_arguments_as_tuple"/>
- </inject-code>
- </modify-function>
-
- <modify-function signature="argRemoval5(int, bool, int, bool)">
- <modify-argument index="1">
- <remove-argument/>
- <replace-default-expression with="200"/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="end">
- <insert-template name="return_4_arguments_as_tuple"/>
- </inject-code>
- </modify-function>
-
- <!--
- this alteration will trigger an interesting
- compile time error on the binding
- -->
- <!--
- <modify-function signature="overloaded(int, bool, Point, Point)">
- <modify-argument index="3">
- <remove-argument/>
- </modify-argument>
- </modify-function>
- -->
-
- <!--
- renaming this signature should remove it from the other
- overloaded methods decision tree
- -->
- <modify-function signature="overloaded(int, bool, Point, Point)" rename="over"/>
-
- <!--
- 'ok' must be removed and the return value will be changed
- to a tuple (PyObject*) containing the expected result plus
- the 'ok' value as a Python boolean
- -->
- <modify-function signature="pointToPair(Point, bool*)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- <insert-template name="boolptr_at_end_fix_beginning"/>
- </inject-code>
- <inject-code class="target" position="end">
- <insert-template name="boolptr_fix_end"/>
- </inject-code>
- </modify-function>
-
- <!-- same as 'pointToPair' except that this time 'ok' is the first argument -->
- <modify-function signature="multiplyPointCoordsPlusValue(bool*, Point, double)">
- <modify-argument index="1">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- <insert-template name="boolptr_at_start_fix_beginning"/>
- </inject-code>
- <inject-code class="target" position="end">
- <insert-template name="boolptr_fix_end"/>
- </inject-code>
- </modify-function>
-
- <!-- completely remove 'plus' from the Python side -->
- <modify-function signature="doublePlus(int, int)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- </modify-function>
-
- <!-- the default value for both arguments must be changed in Python -->
- <modify-function signature="power(int, int)">
- <modify-argument index="1">
- <replace-default-expression with="2"/>
- </modify-argument>
- <modify-argument index="2">
- <replace-default-expression with="1"/>
- </modify-argument>
- </modify-function>
-
- <!-- in Python set argument default value to 10 -->
- <modify-function signature="timesTen(int)">
- <modify-argument index="1">
- <replace-default-expression with="10"/>
- </modify-argument>
- </modify-function>
-
- <!-- in Python remove the argument default value -->
- <modify-function signature="increment(int)">
- <modify-argument index="1">
- <remove-default-expression/>
- </modify-argument>
- </modify-function>
-
- <!-- don't export this method to Python -->
- <modify-function signature="exclusiveCppStuff()" remove="all"/>
-
- <!-- change the name of this regular method -->
- <modify-function signature="cppMultiply(int, int)" rename="calculateArea"/>
-
- <!-- change the name of this virtual method -->
- <modify-function signature="className()" rename="name"/>
-
- <modify-function signature="sumPointArray(int, const Point[])">
- <modify-argument index="1">
- <remove-argument/>
- <conversion-rule class="native">
- int %out = PySequence_Size(%PYARG_1);
- </conversion-rule>
- </modify-argument>
- <modify-argument index="2">
- <replace-type modified-type="PySequence" />
- <conversion-rule class="native">
- Shiboken::AutoArrayPointer&lt;Point&gt; %out(%1);
- for (int i = 0; i &lt; %1; ++i)
- %out[i] = %CONVERTTOCPP[Point](PySequence_Fast_GET_ITEM(%PYARG_1, i));
- </conversion-rule>
- </modify-argument>
- </modify-function>
- <modify-function signature="getSize(const void*,int)">
- <modify-argument index="1">
- <replace-type modified-type="ByteArray&amp;"/>
- </modify-argument>
- <modify-argument index="2">
- <replace-default-expression with="-1"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- int size = (%2 &lt; 0) ? %1.size() : %2;
- %BEGIN_ALLOW_THREADS
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME((const void*) %1.data(), size);
- %END_ALLOW_THREADS
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </modify-function>
- <modify-function signature="sumPointCoordinates(const Point*)">
- <modify-argument index="1">
- <no-null-pointer/>
- </modify-argument>
- </modify-function>
- <template name="differenceOfPointCoordinates_arg2">
- bool _status;
- bool* %2 = &amp;_status;
- </template>
- <template name="differenceOfPointCoordinates_returnTarget">
- %PYARG_0 = PyTuple_New(2);
- PyTuple_SET_ITEM(%PYARG_0, 0, %CONVERTTOPYTHON[bool](*%2));
- PyTuple_SET_ITEM(%PYARG_0, 1, %CONVERTTOPYTHON[%RETURN_TYPE](%0));
- </template>
- <modify-function signature="differenceOfPointCoordinates(const Point*, bool*)">
- <modify-argument index="2">
- <remove-argument/>
- <conversion-rule class="native">
- <insert-template name="differenceOfPointCoordinates_arg2"/>
- </conversion-rule>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PySequence"/>
- <conversion-rule class="native">
- Shiboken::AutoDecRef _py_ok_(PySequence_GetItem(%PYARG_0, 0));
- Shiboken::AutoDecRef _py_ret_(PySequence_GetItem(%PYARG_0, 1));
- *%2 = %CONVERTTOCPP[bool](_py_ok_);
- %RETURN_TYPE %out = %CONVERTTOCPP[%RETURN_TYPE](_py_ret_);
- </conversion-rule>
- <conversion-rule class="target">
- <insert-template name="differenceOfPointCoordinates_returnTarget"/>
- </conversion-rule>
- </modify-argument>
- </modify-function>
- <modify-function signature="callDifferenceOfPointCoordinates(const Point*, bool*)">
- <modify-argument index="2">
- <remove-argument/>
- <conversion-rule class="native">
- <insert-template name="differenceOfPointCoordinates_arg2"/>
- </conversion-rule>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PySequence"/>
- <conversion-rule class="target">
- <insert-template name="differenceOfPointCoordinates_returnTarget"/>
- </conversion-rule>
- </modify-argument>
- </modify-function>
- <modify-function signature="nonConversionRuleForArgumentWithDefaultValue(ObjectType**)">
- <modify-argument index="1">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="(status, object)"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- ObjectType* tmpObject = 0;
- %BEGIN_ALLOW_THREADS
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(&amp;tmpObject);
- %END_ALLOW_THREADS
- %PYARG_0 = PyTuple_New(2);
- PyTuple_SET_ITEM(%PYARG_0, 0, %CONVERTTOPYTHON[%RETURN_TYPE](%0));
- PyTuple_SET_ITEM(%PYARG_0, 1, %CONVERTTOPYTHON[ObjectType*](tmpObject));
- </inject-code>
- </modify-function>
- <modify-function signature="passOddBool(OddBool)" rename="invertBoolean">
- <inject-code class="target" position="beginning">
- %RETURN_TYPE %0 = !%CPPSELF.%FUNCTION_NAME(%1);
- %PYARG_0 = %CONVERTTOPYTHON[OddBool](%0);
- </inject-code>
- </modify-function>
- <modify-function signature="setEnumValue(Modifications::TestEnum)">
- <modify-argument index="1">
- <replace-default-expression with="cppSelf->defaultEnumValue()"/>
- </modify-argument>
- </modify-function>
- <add-function signature="__getattro__" return-type="PyObject *">
- <inject-code class="target" position="beginning">
- cppSelf->notifyGetAttroCalled();
- </inject-code>
- </add-function>
- <add-function signature="__setattro__" return-type="int">
- <inject-code class="target" position="beginning">
- cppSelf->notifySetAttroCalled();
- </inject-code>
- </add-function>
- </object-type>
-
- <object-type name="AbstractModifications">
- <!--
- completely removing the pure virtual method from this
- class will generate an #error directive.
- -->
- <!--
- <modify-function signature="pointlessPureVirtualMethod()" remove="all"/>
- -->
- </object-type>
-
- <value-type name="Reference">
- <modify-function signature="returnMyFirstArg(Reference&amp;)">
- <modify-argument index="return">
- <replace-default-expression with="%1"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="returnMySecondArg(int, Reference&amp;)">
- <modify-argument index="return">
- <replace-default-expression with="%2"/>
- </modify-argument>
- </modify-function>
- </value-type>
- <object-type name="ObjTypeReference">
- <modify-function signature="returnMyFirstArg(ObjTypeReference&amp;)">
- <modify-argument index="return">
- <replace-default-expression with="%1"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="returnMySecondArg(int, ObjTypeReference&amp;)">
- <modify-argument index="return">
- <replace-default-expression with="%2"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="justAPureVirtualFunc(ObjTypeReference&amp;)">
- <modify-argument index="return">
- <replace-default-expression with="%1"/>
- </modify-argument>
- </modify-function>
- </object-type>
- <value-type name="ImplicitConv">
- <enum-type name="CtorEnum"/>
- <enum-type name="ICOverloadedFuncEnum"/>
- </value-type>
-
- <value-type name="VirtualMethods">
- <modify-function signature="sum0(int, int, int)" rename="sumThree"/>
- <modify-function signature="sum1(int, int, int)">
- <modify-argument index="3">
- <replace-default-expression with="1000"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="sum2(int, int, int)">
- <modify-argument index="3">
- <remove-argument/>
- <replace-default-expression with="2000"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="sum3(int, int, int)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- %RETURN_TYPE %0 = %CPPSELF.%TYPE::%FUNCTION_NAME(%1, %1+%3, %3);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </modify-function>
- <modify-function signature="sum4(int, int, int)">
- <modify-argument index="2">
- <remove-argument/>
- <replace-default-expression with="3000"/>
- </modify-argument>
- <inject-code class="native" position="beginning">
- PyObject* new_arg0 = PyInt_FromLong(PyInt_AS_LONG(%PYARG_1) - %2);
- Py_DECREF(%PYARG_1);
- %PYARG_1 = new_arg0;
- </inject-code>
- </modify-function>
- <modify-function signature="name()">
- <inject-code class="native" position="end">
- %0.prepend(Str("Pimped"));
- </inject-code>
- </modify-function>
- <modify-function signature="callMe()">
- <inject-code class="native" position="end">
- PyObject_Call(%PYTHON_METHOD_OVERRIDE, %PYTHON_ARGUMENTS, NULL);
- </inject-code>
- </modify-function>
- <modify-function signature="createStr(const char*, Str*&amp;)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PySequence"/>
- <conversion-rule class="native">
- Shiboken::AutoDecRef _py_ok_(PySequence_GetItem(%PYARG_0, 0));
- Shiboken::AutoDecRef _py_ret_(PySequence_GetItem(%PYARG_0, 1));
- %RETURN_TYPE %out = %CONVERTTOCPP[%RETURN_TYPE](_py_ok_);
- %2 = %CONVERTTOCPP[Str*](_py_ret_);
- </conversion-rule>
- </modify-argument>
- <inject-code class="target" position="beginning">
- Str* _str_arg_ = 0;
- %RETURN_TYPE %0 = %CPPSELF.%TYPE::%FUNCTION_NAME(%1, _str_arg_);
- </inject-code>
- <inject-code class="target" position="end">
- %PYARG_0 = PyTuple_New(2);
- PyObject* _item_ = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- PyTuple_SET_ITEM(%PYARG_0, 0, _item_);
- _item_ = %CONVERTTOPYTHON[Str*](_str_arg_);
- PyTuple_SET_ITEM(%PYARG_0, 1, _item_);
- </inject-code>
- </modify-function>
- <modify-function signature="callCreateStr(const char*, Str*&amp;)">
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PySequence"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- Str* _str_arg_ = 0;
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(%1, _str_arg_);
- </inject-code>
- <inject-code class="target" position="end">
- %PYARG_0 = PyTuple_New(2);
- PyObject* _item_ = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- PyTuple_SET_ITEM(%PYARG_0, 0, _item_);
- _item_ = %CONVERTTOPYTHON[Str*](_str_arg_);
- PyTuple_SET_ITEM(%PYARG_0, 1, _item_);
- </inject-code>
- </modify-function>
- <template name="fix_int*,int*,int*,int*">
- int a0, a1, a2, a3;
- %BEGIN_ALLOW_THREADS
- %CPPSELF->::%TYPE::%FUNCTION_NAME(&amp;a0, &amp;a1, &amp;a2, &amp;a3);
- %END_ALLOW_THREADS
- %PYARG_0 = PyTuple_New(4);
- PyTuple_SET_ITEM(%PYARG_0, 0, %CONVERTTOPYTHON[int](a0));
- PyTuple_SET_ITEM(%PYARG_0, 1, %CONVERTTOPYTHON[int](a1));
- PyTuple_SET_ITEM(%PYARG_0, 2, %CONVERTTOPYTHON[int](a2));
- PyTuple_SET_ITEM(%PYARG_0, 3, %CONVERTTOPYTHON[int](a3));
- </template>
- <template name="fix_native_return_int*,int*,int*,int*">
- PyObject* _obj = %PYARG_0.object();
- if (!PySequence_Check(_obj)
- || PySequence_Fast_GET_SIZE(_obj) != 4
- || !SbkNumber_Check(PySequence_Fast_GET_ITEM(_obj, 0))
- || !SbkNumber_Check(PySequence_Fast_GET_ITEM(_obj, 1))
- || !SbkNumber_Check(PySequence_Fast_GET_ITEM(_obj, 2))
- || !SbkNumber_Check(PySequence_Fast_GET_ITEM(_obj, 3))) {
- PyErr_SetString(PyExc_TypeError, "Sequence of 4 numbers expected");
- } else {
- *%1 = %CONVERTTOCPP[int](PySequence_Fast_GET_ITEM(_obj, 0));
- *%2 = %CONVERTTOCPP[int](PySequence_Fast_GET_ITEM(_obj, 1));
- *%3 = %CONVERTTOCPP[int](PySequence_Fast_GET_ITEM(_obj, 2));
- *%4 = %CONVERTTOCPP[int](PySequence_Fast_GET_ITEM(_obj, 3));
- }
- </template>
- <modify-function signature="getMargins(int*,int*,int*,int*)const">
- <modify-argument index="0">
- <replace-type modified-type="PyObject" />
- </modify-argument>
- <modify-argument index="1">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="3">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="4">
- <remove-argument/>
- <remove-default-expression/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- <insert-template name="fix_int*,int*,int*,int*"/>
- </inject-code>
- <inject-code class="native" position="end">
- <insert-template name="fix_native_return_int*,int*,int*,int*"/>
- </inject-code>
- </modify-function>
- <modify-function signature="callGetMargins(int*,int*,int*,int*)const">
- <modify-argument index="0">
- <replace-type modified-type="PyObject" />
- </modify-argument>
- <modify-argument index="1">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="2">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="3">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="4">
- <remove-argument/>
- <remove-default-expression/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- <insert-template name="fix_int*,int*,int*,int*"/>
- </inject-code>
- </modify-function>
- <modify-function signature="recursionOnModifiedVirtual(Str)const">
- <inject-code class="target" position="beginning">
- %BEGIN_ALLOW_THREADS
- // It's important for test purposes to use a constructor with parenthesis as argument.
- %RETURN_TYPE %0 = %RETURN_TYPE(%CPPSELF.%FUNCTION_NAME(Str(%1)));
- %END_ALLOW_THREADS
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </modify-function>
- </value-type>
- <value-type name="VirtualDaughter" />
- <object-type name="VirtualDaughter2" />
- <object-type name="VirtualFinalDaughter" />
-
- <value-type name="VirtualDtor">
- <modify-function signature="create()">
- <modify-argument index="return">
- <define-ownership owner="target"/>
- </modify-argument>
- </modify-function>
- </value-type>
-
- <value-type name="PointerHolder">
- <modify-function signature="PointerHolder(void*)" remove="all"/>
- <add-function signature="PointerHolder(PyObject*)">
- <inject-code class="target" position="beginning">
- %0 = new %TYPE(%PYARG_1);
- </inject-code>
- </add-function>
- <modify-function signature="pointer() const">
- <inject-code class="target" position="beginning">
- %PYARG_0 = reinterpret_cast&lt;PyObject*>(%CPPSELF.%FUNCTION_NAME());
- if (!%PYARG_0)
- %PYARG_0 = Py_None;
- Py_INCREF(%PYARG_0);
- </inject-code>
- </modify-function>
- </value-type>
-
- <function signature="applyHomogeneousTransform(Point,double,double,double,double,double,double,double,double,double,bool*)">
- <!--
- Tests handling of the '%#' substitution for # > 9.
- -->
- <modify-function signature="applyHomogeneousTransform(Point,double,double,double,double,double,double,double,double,double,bool*)">
- <modify-argument index="11">
- <remove-argument/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- bool ok_;
- %RETURN_TYPE retval_ =
- %FUNCTION_NAME(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, &amp;ok_);
- if (!ok_)
- %PYARG_0 = Py_None;
- else
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](retval_);
- </inject-code>
- </modify-function>
- </function>
-
- <!-- Tests add-function for nested template types -->
- <add-function signature="sum2d(std::list&lt;std::list&lt;int&gt; &gt;)" return-type="int">
- <inject-code class="target" position="beginning">
- typedef std::list&lt;int&gt; Inner;
- typedef std::list&lt;Inner&gt; Outer;
-
- int result = 0;
-
- Outer::const_iterator oiter, oend = %1.end();
- for (oiter = %1.begin(); oiter != oend; ++oiter) {
- const Inner&amp; inner = *oiter;
- Inner::const_iterator iiter, iend = inner.end();
- for (iiter = inner.begin(); iiter != iend; ++iiter)
- result += *iiter;
- }
-
- %PYARG_0 = %CONVERTTOPYTHON[int](result);
- </inject-code>
- </add-function>
-
- <!-- Tests add-function for nested template types -->
- <add-function signature="sumproduct(std::list&lt;std::pair&lt;int, int&gt; &gt;)" return-type="int">
- <inject-code class="target" position="beginning">
- typedef std::pair&lt;int, int&gt; Pair;
- typedef std::list&lt;Pair&gt; List;
-
- int result = 0;
-
- List::const_iterator iter, end = %1.end();
- for (iter = %1.begin(); iter != end; ++iter)
- result += iter->first * iter->second;
-
- %PYARG_0 = %CONVERTTOPYTHON[int](result);
- </inject-code>
- </add-function>
-
-
- <value-type name="InjectCode">
- <!--
- Various tests for inject codes.
- Note: Some uses of inject code here are used just for testing purposes, consider using the add-function tag.
- -->
-
- <modify-function signature="sumArrayAndLength(int *) const">
- <modify-argument index="1">
- <replace-type modified-type="PyObject"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- int* array = NULL;
- bool errorOccurred = false;
-
- if (PySequence_Check(%PYARG_1)) {
- if((array = Shiboken::sequenceToIntArray(%PYARG_1, true)) == NULL &amp;&amp; PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "Should be a sequence of ints");
- errorOccurred = true;
- }
- } else {
- PyErr_SetString(PyExc_TypeError, "Should be a sequence of ints");
- errorOccurred = true;
- }
-
- if (!errorOccurred) {
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(array);
- if (array)
- delete[] array;
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- }
- </inject-code>
- </modify-function>
-
- <modify-function signature="arrayMethod(int, int*) const">
- <modify-argument index="1">
- <remove-argument/>
- <conversion-rule class="native">
- int %out = PySequence_Size(%PYARG_1);
- </conversion-rule>
- </modify-argument>
- <modify-argument index="2">
- <replace-type modified-type="PySequence"/>
- <conversion-rule class="native">
- int numItems = PySequence_Size(%PYARG_1);
- Shiboken::AutoArrayPointer&lt;int&gt; %out(numItems);
- for (int i = 0; i &lt; numItems; ++i) {
- if (%CHECKTYPE[int](PySequence_Fast_GET_ITEM(%PYARG_1, i)))
- %out[i] = %CONVERTTOCPP[int](PySequence_Fast_GET_ITEM(%PYARG_1, i));
- else if (%ISCONVERTIBLE[int](PySequence_Fast_GET_ITEM(%PYARG_1, i)))
- %out[i] = -1;
- else
- %out[i] = -2;
- }
- </conversion-rule>
- <conversion-rule class="target">
- PyObject* %out = PyList_New(count);
- for (int i = 0; i &lt; count; ++i)
- PyList_SET_ITEM(%out, i, %CONVERTTOPYTHON[int](%in[i]));
- </conversion-rule>
- </modify-argument>
- </modify-function>
-
- <modify-function signature="callArrayMethod(int, int*) const">
- <modify-argument index="1">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="2">
- <replace-type modified-type="PySequence"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- int numItems = PySequence_Size(%PYARG_1);
- int *cppItems = new int[numItems];
- for (int i = 0; i &lt; numItems; i++)
- cppItems[i] = %CONVERTTOCPP[int](PySequence_GetItem(%PYARG_1, i));
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(numItems, cppItems);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- delete[] cppItems;
- </inject-code>
- </modify-function>
-
- <!--
- Inject the tp_str method using this alternative way
- Tested in InjectCodeTest.testTypeNativeBeginning_TypeTargetBeginning:
- -->
- <inject-code class="native" position="beginning">
- PyObject* InjectCode_tpstr(PyObject*) { return Shiboken::String::fromCString("Hi! I'm the inject code dummy class."); }
- </inject-code>
- <!--
- Register our tp_str class using another inject code
- Tested in InjectCodeTest.testTypeNativeBeginning_TypeTargetBeginning:
- -->
- <inject-code class="target" position="beginning">
- %PYTHONTYPEOBJECT.tp_str = InjectCode_tpstr;
- </inject-code>
-
- <!-- Tested in InjectCodeTest.testFunctionTargetBeginning_FunctionTargetEnd -->
- <modify-function signature="simpleMethod1(int, int)">
- <inject-code class="target" position="beginning">
- %1 += 1;
- </inject-code>
- <inject-code class="target" position="end">
- PyObject* tmp = Shiboken::String::fromCString("end");
- Shiboken::String::concat(&amp;%PYARG_0, tmp);
- Py_DECREF(tmp);
- </inject-code>
- </modify-function>
-
- <!-- Tested in InjectCodeTest.testFunctionTargetBeginning -->
- <modify-function signature="simpleMethod2()">
- <inject-code class="target" position="end">
- PyObject* tmp = Shiboken::String::fromCString("end");
- Shiboken::String::concat(&amp;%PYARG_0, tmp);
- Py_DECREF(tmp);
- </inject-code>
- </modify-function>
-
- <!-- Tested in InjectCodeTest.testArgsModification -->
- <modify-function signature="overloadedMethod(int, char**)">
- <modify-argument index="1">
- <replace-type modified-type="PySequence" />
- </modify-argument>
- <modify-argument index="2">
- <remove-argument />
- </modify-argument>
- <inject-code class="target" position="beginning">
- int argc;
- char** argv;
- if (!Shiboken::listToArgcArgv(%PYARG_1, &amp;argc, &amp;argv)) {
- PyErr_SetString(PyExc_TypeError, "error");
- return 0;
- }
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(argc, argv);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- for (int i = 0; i &lt; argc; ++i)
- free(argv[i]);
- delete[] argv;
- </inject-code>
- </modify-function>
-
- <!-- Tested in InjectCodeTest.testArgsModification2 -->
- <modify-function signature="simpleMethod3(int, char**)">
- <modify-argument index="1">
- <replace-type modified-type="PySequence" />
- </modify-argument>
- <modify-argument index="2">
- <remove-argument />
- </modify-argument>
- <inject-code class="target" position="beginning">
- int argc;
- char** argv;
- if (!Shiboken::listToArgcArgv(%PYARG_1, &amp;argc, &amp;argv)) {
- PyErr_SetString(PyExc_TypeError, "error");
- return 0;
- }
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(argc, argv);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- for (int i = 0; i &lt; argc; ++i)
- free(argv[i]);
- delete[] argv;
- </inject-code>
- </modify-function>
- </value-type>
-
- <value-type name="ImplicitBase"/>
- <value-type name="SortedOverload">
- <add-function signature="overload(PyObject *)" return-type="const char *">
- <inject-code class="target" position="beginning">
- return Shiboken::String::fromCString("PyObject");
- </inject-code>
- </add-function>
-
- <add-function signature="overloadDeep(int, PyObject *)" return-type="const char *">
- <inject-code class="target" position="beginning">
- return Shiboken::String::fromCString("PyObject");
- </inject-code>
- </add-function>
- <modify-function signature="pyObjOverload(unsigned char*, int)">
- <modify-argument index="1">
- <replace-type modified-type="PyObject" />
- <conversion-rule class="native">
- unsigned char* %out = 0;
- </conversion-rule>
- </modify-argument>
- </modify-function>
- </value-type>
- <value-type name="ImplicitTarget"/>
-
- <value-type name="Point">
- <add-function signature="__str__" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- int x1 = (int) %CPPSELF.x();
- int x2 = ((int) (%CPPSELF.x() * 100)) - (x1 * 100);
- int y1 = (int) %CPPSELF.y();
- int y2 = ((int) (%CPPSELF.y() * 100)) - (y1 * 100);
- %PYARG_0 = Shiboken::String::fromFormat("Point(%d.%d, %d.%d)", x1, x2, y1, y2);
- </inject-code>
- </add-function>
- <add-function signature="__repr__" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- int x1 = (int) %CPPSELF.x();
- int x2 = ((int) (%CPPSELF.x() * 10)) - (x1 * 10);
- int y1 = (int) %CPPSELF.y();
- int y2 = ((int) (%CPPSELF.y() * 10)) - (y1 * 10);
- %PYARG_0 = Shiboken::String::fromFormat("&lt;Point object at %p: (%d.%d, %d.%d)&gt;", %CPPSELF, x1, x2, y1, y2);
- </inject-code>
- </add-function>
-
- <add-function signature="__reduce__" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- PyObject* type = PyObject_Type(%PYSELF);
- PyObject* args = NULL;
-
- args = Py_BuildValue("(dd)", %CPPSELF.x(), %CPPSELF.y());
-
- %PYARG_0 = Py_BuildValue("(OO)", type, args);
- </inject-code>
- </add-function>
-
- <modify-function signature="midpoint(const Point&amp;, Point*)const">
- <modify-argument index="2">
- <remove-argument />
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="Point" />
- </modify-argument>
- <inject-code class="target" position="beginning">
- Point _midpoint;
- // The test consists in *NOT* using the ARGUMENT_NAMES type system variable.
- %CPPSELF.%FUNCTION_NAME(%1, &amp;_midpoint);
- %PYARG_0 = %CONVERTTOPYTHON[Point](_midpoint);
- </inject-code>
- </modify-function>
-
- <template name="return_self">
- %PYARG_0 = %PYARG_1;
- Py_INCREF(%PYARG_1);
- </template>
- <add-function signature="operator-(PyUnicode)">
- <inject-code>
- <insert-template name="return_self" />
- </inject-code>
- </add-function>
- <!-- A reverse operator -->
- <add-function signature="operator-(PyUnicode, Point)">
- <inject-code>
- <insert-template name="return_self" />
- </inject-code>
- </add-function>
- </value-type>
-
- <value-type name="PointF">
- <add-function signature="__str__" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- int x1 = (int) %CPPSELF.x();
- int x2 = ((int) (%CPPSELF.x() * 100)) - (x1 * 100);
- int y1 = (int) %CPPSELF.y();
- int y2 = ((int) (%CPPSELF.y() * 100)) - (y1 * 100);
- %PYARG_0 = Shiboken::String::fromFormat("PointF(%d.%d, %d.%d)", x1, x2, y1, y2);
- </inject-code>
- </add-function>
- <add-function signature="__repr__" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- int x1 = (int) %CPPSELF.x();
- int x2 = ((int) (%CPPSELF.x() * 10)) - (x1 * 10);
- int y1 = (int) %CPPSELF.y();
- int y2 = ((int) (%CPPSELF.y() * 10)) - (y1 * 10);
- %PYARG_0 = Shiboken::String::fromFormat("&lt;PointF object at %p: (%d.%d, %d.%d)&gt;", %CPPSELF, x1, x2, y1, y2);
- </inject-code>
- </add-function>
-
- <add-function signature="__reduce__" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- PyObject *type = PyObject_Type(%PYSELF);
- PyObject *args = NULL;
-
- args = Py_BuildValue("(dd)", %CPPSELF.x(), %CPPSELF.y());
-
- %PYARG_0 = Py_BuildValue("(OO)", type, args);
- </inject-code>
- </add-function>
-
- <modify-function signature="midpoint(const PointF&amp;, PointF*)const">
- <modify-argument index="2">
- <remove-argument />
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PointF" />
- </modify-argument>
- <inject-code class="target" position="beginning">
- PointF _midpoint;
- // The test consists in using the ARGUMENT_NAMES type system variable.
- %CPPSELF.%FUNCTION_NAME(%ARGUMENT_NAMES, &amp;_midpoint);
- %PYARG_0 = %CONVERTTOPYTHON[PointF](_midpoint);
- </inject-code>
- </modify-function>
- </value-type>
-
- <value-type name="Rect" />
- <value-type name="RectF" />
-
- <value-type name="Polygon">
- <modify-function signature="stealOwnershipFromPython(Point*)">
- <modify-argument index="1">
- <define-ownership owner="c++"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="stealOwnershipFromPython(Polygon*)">
- <modify-argument index="1">
- <define-ownership owner="c++"/>
- </modify-argument>
- </modify-function>
- </value-type>
-
- <value-type name="Time">
- <extra-includes>
- <include file-name="datetime.h" location="global"/>
- </extra-includes>
- <enum-type name="NumArgs"/>
- <add-function signature="operator!=(const PyObject*)" return-type="PyObject">
- <inject-code>
- if (!PyDateTimeAPI)
- PyDateTime_IMPORT;
- if (PyTime_Check(%1)) {
- int pyH = PyDateTime_TIME_GET_HOUR(%1);
- int pyM = PyDateTime_TIME_GET_MINUTE(%1);
- int pyS = PyDateTime_TIME_GET_SECOND(%1);
- if ((pyH == %CPPSELF.hour()) &amp;&amp;
- (pyM == %CPPSELF.minute()) &amp;&amp;
- (pyS == %CPPSELF.second()))
- %PYARG_0 = Py_False;
- else
- %PYARG_0 = Py_True;
- }
- </inject-code>
- </add-function>
- <add-function signature="operator==(const PyObject*)" return-type="PyObject">
- <inject-code>
- if (!PyDateTimeAPI)
- PyDateTime_IMPORT;
- if (PyTime_Check(%1)) {
- int pyH = PyDateTime_TIME_GET_HOUR(%1);
- int pyM = PyDateTime_TIME_GET_MINUTE(%1);
- int pyS = PyDateTime_TIME_GET_SECOND(%1);
- if ((pyH == %CPPSELF.hour()) &amp;&amp;
- (pyM == %CPPSELF.minute()) &amp;&amp;
- (pyS == %CPPSELF.second()))
- %PYARG_0 = Py_True;
- else
- %PYARG_0 = Py_False;
- }
- </inject-code>
- </add-function>
-
- </value-type>
- <value-type name="Size">
- <add-function signature="Size(const char*)">
- <inject-code class="target" position="beginning">
- %0 = new %TYPE();
- </inject-code>
- <inject-code class="target" position="end">
- Shiboken::AutoDecRef result(PyObject_CallMethod(%PYSELF, const_cast&lt;char*>("setHeight"), const_cast&lt;char*>("i"), 2));
- </inject-code>
- </add-function>
- </value-type>
- <value-type name="SizeF"/>
- <value-type name="MapUser"/>
- <value-type name="PairUser"/>
- <value-type name="ListUser">
- <enum-type name="ListOfSomething"/>
- </value-type>
- <value-type name="NoImplicitConversion" />
- <value-type name="NonDefaultCtor" />
- <value-type name="OddBoolUser" />
- <object-type name="Overload">
- <enum-type name="FunctionEnum"/>
- <enum-type name="ParamEnum"/>
- <modify-function signature="intOverloads(int, int, double)">
- <modify-argument index="2">
- <remove-argument />
- </modify-argument>
- <inject-code class="target">
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(%1, 2, %3);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </modify-function>
- <modify-function signature="singleOverload(Point*)">
- <modify-argument index="1">
- <define-ownership owner="c++"/>
- </modify-argument>
- </modify-function>
- <modify-function signature="acceptSequence(const char*const[])">
- <modify-argument index="1">
- <replace-type modified-type="PySequence" />
- <conversion-rule class="native">
- {
- Shiboken::AutoDecRef strList(PySequence_Fast(%PYARG_1, "The argument must be a sequence."));
- int lineCount = PySequence_Fast_GET_SIZE(strList.object());
- for (int line = 0; line &lt; lineCount; ++line) {
- if (!Shiboken::String::check(PySequence_Fast_GET_ITEM(strList.object(), line))) {
- PyErr_SetString(PyExc_TypeError, "The argument must be a sequence of strings.");
- break;
- }
- }
- }
- const char** %out = 0;
- </conversion-rule>
- </modify-argument>
- </modify-function>
- <modify-function signature="acceptSequence(void*)">
- <modify-argument index="1">
- <replace-type modified-type="PyObject" />
- <conversion-rule class="native">
- void* %out = 0;
- </conversion-rule>
- </modify-argument>
- </modify-function>
-
- <template name="buffer_argument">
- unsigned char* %out = (unsigned char*) Shiboken::Buffer::getPointer(%PYARG_1);
- </template>
-
- <modify-function signature="strBufferOverloads(unsigned char*,int)">
- <modify-argument index="1">
- <replace-type modified-type="PyBuffer"/>
- <conversion-rule class="native">
- <insert-template name="buffer_argument" />
- </conversion-rule>
- </modify-argument>
- </modify-function>
- <!--
- This added function simulates the solution given to PySide's QImage
- constructor problem, as seen in PySide/bbba1cc4, and described in
- bug #489 [http://bugs.pyside.org/show_bug.cgi?id=489].
- This is not the best solution, just one that works. The proper way
- to handle it would be to fix the overload decisor.
- -->
- <add-function signature="strBufferOverloads(Str&amp;,int)" return-type="Overload::FunctionEnum">
- <inject-code class="target" position="beginning">
- <insert-template name="buffer_argument">
- <replace from="%out" to="argOut" />
- </insert-template>
- %BEGIN_ALLOW_THREADS
- %RETURN_TYPE %0 = %CPPSELF.%FUNCTION_NAME(argOut, %2);
- %END_ALLOW_THREADS
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
- </object-type>
- <object-type name="Overload2" />
-
- <object-type name="Collector" stream="yes"/>
-
- <value-type name="IntWrapper" />
-
- <value-type name="Str" hash-function="strHash">
- <add-function signature="__str__" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- %PYARG_0 = Shiboken::String::fromCString(%CPPSELF.cstring());
- </inject-code>
- </add-function>
- <add-function signature="__len__" >
- <inject-code class="target" position="end">
- return %CPPSELF.size();
- </inject-code>
- </add-function>
- <add-function signature="__getitem__" >
- <inject-code class="target" position="beginning">
- if (_i &lt; 0 || _i >= %CPPSELF.size()) {
- PyErr_BadArgument();
- return 0;
- } else {
- char res[2];
- res[0] = %CPPSELF.get_char(_i);
- res[1] = 0;
- return Shiboken::String::fromCString(res);
- }
- </inject-code>
- </add-function>
- <add-function signature="__setitem__" >
- <inject-code class="target" position="beginning">
- PyObject* args = Py_BuildValue("(iO)", _i, _value);
- PyObject* result = Sbk_StrFunc_set_char(self, args);
- Py_DECREF(args);
- int ok = result == Py_True;
- if (result) {
- Py_DECREF(result);
- }
- return !ok ? -1 : 0;
- </inject-code>
- </add-function>
- <modify-function signature="toInt(bool*, int)const">
- <modify-argument index="1">
- <remove-argument/>
- </modify-argument>
- <modify-argument index="return">
- <replace-type modified-type="PyObject*"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- <insert-template name="boolptr_at_start_and_one_arg_fix_beginning"/>
- </inject-code>
- <inject-code class="target" position="end">
- <insert-template name="boolptr_fix_end"/>
- </inject-code>
- </modify-function>
- </value-type>
-
- <value-type name="ByteArray" hash-function="ByteArray::hash">
- <conversion-rule>
- <target-to-native>
- <add-conversion type="Py_None">
- %out = %OUTTYPE();
- </add-conversion>
- <add-conversion type="PyObject" check="Shiboken::String::check(%in) || PyBytes_Check(%in)">
- Py_ssize_t len;
- const char* str = Shiboken::String::toCString(%in, &amp;len);
- %out = %OUTTYPE(str, len);
- </add-conversion>
- </target-to-native>
- </conversion-rule>
-
- <modify-function signature="ByteArray(const char*,int)" remove="all" />
- <modify-function signature="ByteArray(const char*)" remove="all" >
- <!-- Keep \x00 bytes passed in Python strings. -->
- <modify-argument index="1">
- <replace-type modified-type="PyBytes"/>
- </modify-argument>
- <inject-code class="target" position="beginning">
- PyObject* data = 0;
- if (PyUnicode_CheckExact(%PYARG_1)) {
- data = PyUnicode_AsASCIIString(%PYARG_1);
- } else {
- data = %PYARG_1;
- Py_INCREF(data);
- }
-
- %0 = new %TYPE(PyBytes_AsString(data), PyBytes_GET_SIZE(data));
- Py_DECREF(data);
- </inject-code>
- </modify-function>
-
- <!-- buffer protocol -->
- <inject-code class="native" position="beginning" file="bytearray_bufferprotocol.cpp" />
- <inject-code class="target" position="end">
- #if PY_VERSION_HEX &lt; 0x03000000
- Shiboken::SbkType&lt;ByteArray&gt;()->tp_as_buffer = &amp;SbkByteArrayBufferProc;
- Shiboken::SbkType&lt;ByteArray&gt;()->tp_flags |= Py_TPFLAGS_HAVE_GETCHARBUFFER;
- #endif
- </inject-code>
-
- <modify-function signature="data() const">
- <inject-code class="target" position="beginning">
- %PYARG_0 = PyBytes_FromStringAndSize(%CPPSELF.%FUNCTION_NAME(), %CPPSELF.size());
- </inject-code>
- </modify-function>
-
- <modify-function signature="hash(const ByteArray&amp;)" remove="all" />
- <!-- Functions removed to proper deal with strings containing zeroes -->
- <modify-function signature="append(const char*)" remove="all" />
- <modify-function signature="append(const char*,int)" remove="all" />
- <modify-function signature="operator==(const char*,ByteArray)" remove="all" />
- <modify-function signature="operator==(ByteArray,const char*)" remove="all" />
- <modify-function signature="operator!=(const char*,ByteArray)" remove="all" />
- <modify-function signature="operator!=(ByteArray,const char*)" remove="all" />
- <modify-function signature="operator+(ByteArray,const char*)" remove="all" />
- <modify-function signature="operator+(const char*,ByteArray)" remove="all" />
- <modify-function signature="operator+=(const char*)" remove="all" />
- <modify-function signature="operator[](int)const" remove="all"/>
-
- <add-function signature="operator+(PyUnicode)" return-type="ByteArray">
- <inject-code>
- Shiboken::AutoDecRef data(PyUnicode_AsASCIIString(%PYARG_1));
- if (!data.isNull()) {
- ByteArray ba(*%CPPSELF);
- ba.append(PyBytes_AsString(data.object()), PyBytes_GET_SIZE(data.object()));
- %PYARG_0 = %CONVERTTOPYTHON[ByteArray](ba);
- }
- </inject-code>
- </add-function>
- <add-function signature="operator+(PyUnicode,ByteArray)" return-type="ByteArray">
- <inject-code>
- Shiboken::AutoDecRef data(PyUnicode_AsASCIIString(%PYARG_1));
- if (!data.isNull()) {
- ByteArray ba(PyBytes_AsString(data.object()), PyBytes_GET_SIZE(data.object()));
- ba.append(*%CPPSELF);
- %PYARG_0 = %CONVERTTOPYTHON[ByteArray](ba);
- }
- </inject-code>
- </add-function>
- <add-function signature="operator+(PyBytes,ByteArray)">
- <inject-code>
- ByteArray ba(PyBytes_AsString(%PYARG_1), PyBytes_GET_SIZE(%PYARG_1));
- ba = ba + *%CPPSELF;
- %PYARG_0 = %CONVERTTOPYTHON[ByteArray](ba);
- </inject-code>
- </add-function>
- <add-function signature="operator+(PyBytes)">
- <inject-code>
- ByteArray ba(PyBytes_AsString(%PYARG_1), PyBytes_GET_SIZE(%PYARG_1));
- ba.append(*%CPPSELF);
- %PYARG_0 = %CONVERTTOPYTHON[ByteArray](ba);
- </inject-code>
- </add-function>
- <add-function signature="__repr__" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- ByteArray b(Py_TYPE(%PYSELF)->tp_name);
- PyObject* aux = Shiboken::String::fromStringAndSize(%CPPSELF.data(), %CPPSELF.size());
- if (PyUnicode_CheckExact(aux)) {
- PyObject* tmp = PyUnicode_AsASCIIString(aux);
- Py_DECREF(aux);
- aux = tmp;
- }
- b += "('";
- b += ByteArray(PyBytes_AS_STRING(aux), PyBytes_GET_SIZE(aux));
- b += "')";
- %PYARG_0 = Shiboken::String::fromStringAndSize(b.data(), b.size());
- </inject-code>
- </add-function>
-
- <add-function signature="__str__" return-type="str">
- <inject-code class="target" position="beginning">
- %PYARG_0 = Shiboken::String::fromStringAndSize(%CPPSELF.data(), %CPPSELF.size());
- </inject-code>
- </add-function>
-
- <add-function signature="__len__">
- <inject-code class="target" position="beginning">
- return %CPPSELF.size();
- </inject-code>
- </add-function>
- <add-function signature="__getitem__">
- <inject-code class="target" position="beginning">
- if (_i &lt; 0 || _i >= %CPPSELF.size()) {
- PyErr_SetString(PyExc_IndexError, "index out of bounds");
- return 0;
- } else {
- char res[2];
- res[0] = %CPPSELF.at(_i);
- res[1] = 0;
- return PyBytes_FromStringAndSize(res, 1);
- }
- </inject-code>
- </add-function>
- </value-type>
-
- <value-type name="StrList">
- <enum-type name="CtorEnum"/>
- <add-function signature="__len__" >
- <inject-code class="target" position="end">
- return %CPPSELF.size();
- </inject-code>
- </add-function>
- <add-function signature="__getitem__" >
- <inject-code class="target" position="beginning">
- if (_i &lt; 0 || _i >= static_cast&lt;Py_ssize_t>(%CPPSELF.size())) {
- PyErr_BadArgument();
- return 0;
- } else {
- %TYPE::const_iterator it = %CPPSELF.begin();
- for (Py_ssize_t i = 1; i &lt;= _i; i++)
- ++it;
- return %CONVERTTOPYTHON[Str](*it);
- }
- </inject-code>
- </add-function>
- </value-type>
-
- <value-type name="SimpleFile">
- <modify-function signature="open()">
- <modify-argument index="return">
- <remove-argument/>
- </modify-argument>
- <inject-code class="target" position="end" file="simplefile_glue.cpp"/>
- </modify-function>
- </value-type>
-
- <value-type name="VoidHolder" />
-
- <object-type name="PrivateCtor" />
- <object-type name="PrivateDtor" />
-
- <object-type name="Base1"/>
- <object-type name="Base2"/>
- <object-type name="Base3"/>
- <object-type name="Base4"/>
- <object-type name="Base5"/>
- <object-type name="Base6"/>
- <object-type name="MDerived1"/>
- <object-type name="MDerived2"/>
- <object-type name="MDerived3"/>
- <object-type name="MDerived4"/>
- <object-type name="MDerived5"/>
- <object-type name="SonOfMDerived1"/>
-
- <object-type name="Bucket">
- <modify-function signature="lock()" allow-thread="yes" />
- <modify-function signature="virtualBlockerMethod()" allow-thread="yes"/>
- <modify-function signature="callVirtualBlockerMethodButYouDontKnowThis()" allow-thread="yes"/>
- </object-type>
-
- <value-type name="Echo">
- <add-function signature="echo(const char *)" return-type="PyObject*">
- <inject-code class="target" position="beginning">
- %PYARG_0 = Shiboken::String::fromCString(%1);
- </inject-code>
- </add-function>
- <add-function signature="operator>(int)">
- <inject-code>
- // This should test if code injections works inside rich comparison operators
- Py_INCREF(Py_True);
- %PYARG_0 = Py_True;
- </inject-code>
- </add-function>
- </value-type>
-
- <value-type name="Color" />
- <value-type name="Pen">
- <enum-type identified-by-value="EnumCtor"/>
- </value-type>
-
- <value-type name="CtorConvRule">
- <modify-function signature="CtorConvRule(long)">
- <modify-argument index="1">
- <!--<replace-type modified-type="long"/>-->
- <conversion-rule class="native">
- // Does nothing really, just test the code generation
- // of constructors whose arguments where
- long %out = PyInt_AS_LONG(%PYARG_1) + 1;
- </conversion-rule>
- </modify-argument>
- </modify-function>
- </value-type>
-
- <add-function signature="multiplyString(str, unsigned int)" return-type="const char*">
- <inject-code class="target" position="beginning">
- %PYARG_0 = Shiboken::String::fromCString("");
- for (unsigned int i = 0; i &lt; %2; ++i)
- Shiboken::String::concat(&amp;%PYARG_0, %PYARG_1);
- </inject-code>
- </add-function>
-
- <add-function signature="countVarargs(int, ...)" return-type="int">
- <inject-code class="target" position="beginning">
- %RETURN_TYPE %0 = PyTuple_GET_SIZE(%PYARG_2);
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
-
- <value-type name="SbkDate">
- <extra-includes>
- <include file-name="datetime.h" location="global"/>
- </extra-includes>
- <inject-code class="native" position="beginning">
- static bool PyDate_ImportAndCheck(PyObject* pyIn) {
- if (!PyDateTimeAPI)
- PyDateTime_IMPORT;
- return PyDate_Check(pyIn);
- }
- </inject-code>
- <conversion-rule>
- <target-to-native>
- <add-conversion type="PyDate" check="PyDate_ImportAndCheck(%in)">
- int day = PyDateTime_GET_DAY(%in);
- int month = PyDateTime_GET_MONTH(%in);
- int year = PyDateTime_GET_YEAR(%in);
- %out = %OUTTYPE(day, month, year);
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- <add-function signature="toPython()" return-type="PyDate">
- <inject-code class="target">
- if (!PyDateTimeAPI)
- PyDateTime_IMPORT;
- %PYARG_0 = PyDate_FromDate(%CPPSELF.day(), %CPPSELF.month(), %CPPSELF.year());
- </inject-code>
- </add-function>
- </value-type>
-
- <object-type name="HandleHolder" />
- <value-type name="PrimitiveStructPointerHolder" />
-
- <object-type name="ObjectTypeOperators">
- <add-function signature="operator!=(std::string)" return-type="bool">
- <inject-code class="target">
- %RETURN_TYPE %0 = %CPPSELF.key() != %1;
- %PYARG_0 = %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
- </object-type>
-
- <value-type name="Filter" />
- <value-type name="Data">
- <enum-type name="Field" />
- <add-function signature="operator&amp;(const Union&amp;)" return-type="Intersection">
- <inject-code class="target">
- %RETURN_TYPE %0 = *%CPPSELF &amp; %1;
- return %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
- </value-type>
- <value-type name="Union">
- <add-function signature="operator&amp;(const Data&amp;)" return-type="Intersection">
- <inject-code class="target">
- %RETURN_TYPE %0 = *%CPPSELF &amp; %1;
- return %CONVERTTOPYTHON[%RETURN_TYPE](%0);
- </inject-code>
- </add-function>
- </value-type>
- <value-type name="Intersection" />
-
- <!-- type used in abstract method -->
- <object-type name="HideType" generate="no" />
-
- <value-type name="Expression" />
-
- <object-type name="ExceptionTest" exception-handling="auto-on"/>
-
- <value-type name="ModelIndex" />
- <value-type name="ReferentModelIndex">
- <modify-function signature="operator const ModelIndex&amp;()const">
- <modify-argument index="return">
- <define-ownership owner="c++"/>
- </modify-argument>
- </modify-function>
- </value-type>
- <value-type name="PersistentModelIndex" />
-
- <!-- test rejections using full signatures; this method is a template and
- cannot be wrapped, but is otherwise recognized by shiboken and will
- result in a compile error if the rejection is not matched -->
- <rejection class="Photon::Base" function-name="isType()"/>
-
- <value-type name="ValueAndVirtual" />
-
- <object-type name="ObjectTypeByValue" />
-
- <object-type name="TemplatePtr">
- <modify-function signature="dummy(std::list&lt;std::pair&lt;BlackBox *, BlackBox *&gt; &gt; &amp;)" rename="dummy_method" />
- </object-type>
-
- <value-type name="ToBeRenamedValue" target-lang-name="RenamedValue"/>
- <value-type name="RenamedUser"/>
-
- <suppress-warning text="horribly broken type '__off64_t'" />
- <suppress-warning text="enum '__codecvt_result' does not have a type entry or is not an enum" />
- <suppress-warning text="Pure virtual method &quot;Abstract::hideFunction(HideType*)&quot; must be implement but was completely removed on typesystem." />
- <suppress-warning text="hiding of function 'takeChild' in class 'ObjectType'" />
- <suppress-warning text="Shadowing: MDerived2::castToBase3() and MDerived3::castToBase3()" />
- <suppress-warning text="hiding of function 'takeChild' in class 'Bucket'" />
- <suppress-warning text="visibility of function 'publicMethod' modified in class 'MDerived1'" />
- <suppress-warning text="hiding of function 'doNothingInPublic3' in class 'Overload2'" />
- <suppress-warning text="hiding of function 'takeChild' in class 'ObjectModel'" />
- <suppress-warning text="hiding of function 'takeChild' in class 'ObjectView'" />
- <suppress-warning text="visibility of function 'publicMethod' modified in class 'MDerived3'" />
- <suppress-warning text="skipping function 'InjectCode::toStr', unmatched parameter type 'T const&amp;'" />
-
- <!-- Do not fix this warning, the generator should be able to handle this situation for Object Types. -->
- <suppress-warning text="Argument in position 1 of added function 'SampleNamespace::passReferenceToObjectType(ObjectType * arg__1)', has a type that is not a reference, while the argument in the corresponding position in C++ function 'SampleNamespace::passReferenceToObjectType(const ObjectType &amp; obj, int multiplier)' is a reference." />
-
-</typesystem>
diff --git a/sources/shiboken2/tests/samplebinding/unsafe_parent_test.py b/sources/shiboken2/tests/samplebinding/unsafe_parent_test.py
deleted file mode 100644
index 1387e308c..000000000
--- a/sources/shiboken2/tests/samplebinding/unsafe_parent_test.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for ...'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType
-
-class DerivedObjectType(ObjectType):
- def isPython(self):
- return True
-
- def createChild(self, parent):
- return DerivedObjectType(parent)
-
-class ParentTest(unittest.TestCase):
-
- def testUunsafeParent(self):
- o = DerivedObjectType()
- o.callVirtualCreateChild()
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/useraddedctor_test.py b/sources/shiboken2/tests/samplebinding/useraddedctor_test.py
deleted file mode 100644
index f59fb3533..000000000
--- a/sources/shiboken2/tests/samplebinding/useraddedctor_test.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for user added constructors'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from sample import *
-
-class PointTest(unittest.TestCase):
- def testUsingSelfOnCtor(self):
- # This is a user added ctor and no errors should happen!
- s = Size("oi")
- self.assertEqual(s.height(), 2)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/virtualdtor_test.py b/sources/shiboken2/tests/samplebinding/virtualdtor_test.py
deleted file mode 100644
index 365d31f59..000000000
--- a/sources/shiboken2/tests/samplebinding/virtualdtor_test.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for virtual destructor.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import VirtualDtor
-
-class ExtendedVirtualDtor(VirtualDtor):
- def __init__(self):
- VirtualDtor.__init__(self)
-
-class VirtualDtorTest(unittest.TestCase):
- '''Test case for virtual destructor.'''
-
- def setUp(self):
- VirtualDtor.resetDtorCounter()
-
- def testVirtualDtor(self):
- '''Original virtual destructor is being called.'''
- dtor_called = VirtualDtor.dtorCalled()
- for i in range(1, 10):
- vd = VirtualDtor()
- del vd
- self.assertEqual(VirtualDtor.dtorCalled(), dtor_called + i)
-
- def testVirtualDtorOnCppCreatedObject(self):
- '''Original virtual destructor is being called for a C++ created object.'''
- dtor_called = VirtualDtor.dtorCalled()
- for i in range(1, 10):
- vd = VirtualDtor.create()
- del vd
- self.assertEqual(VirtualDtor.dtorCalled(), dtor_called + i)
-
- def testDtorOnDerivedClass(self):
- '''Original virtual destructor is being called for a derived class.'''
- dtor_called = ExtendedVirtualDtor.dtorCalled()
- for i in range(1, 10):
- evd = ExtendedVirtualDtor()
- del evd
- self.assertEqual(ExtendedVirtualDtor.dtorCalled(), dtor_called + i)
-
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/virtualmethods_test.py b/sources/shiboken2/tests/samplebinding/virtualmethods_test.py
deleted file mode 100644
index 2d3198071..000000000
--- a/sources/shiboken2/tests/samplebinding/virtualmethods_test.py
+++ /dev/null
@@ -1,143 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test cases for virtual methods.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-import warnings
-
-class ExtendedVirtualMethods(VirtualMethods):
- def __init__(self):
- VirtualMethods.__init__(self)
- self.virtual_method0_called = False
-
- def virtualMethod0(self, pt, val, cpx, b):
- self.virtual_method0_called = True
- return VirtualMethods.virtualMethod0(self, pt, val, cpx, b) * -1.0
-
- def strListToStdList(self, arg):
- warnings.simplefilter('error')
- # returning wrong type for test purposes.
- return True
-
- def recursionOnModifiedVirtual(self, arg):
- # check if recursion is caused by injected code that calls C++.
- return VirtualMethods.recursionOnModifiedVirtual(self, arg) + 10
-
-class ExtendedVirtualDaughter(VirtualDaughter):
- def __init__(self, name):
- VirtualDaughter.__init__(self, name)
- self.grand_daughter_name_called = False
-
- def name(self):
- self.grand_daughter_name_called = True
- return VirtualDaughter.name(self).prepend('Extended')
-
-class ExtendedExtendedVirtualDaughter(ExtendedVirtualDaughter):
- def __init__(self, name):
- ExtendedVirtualDaughter.__init__(self, name)
- self.grand_grand_daughter_name_called = False
-
- def name(self):
- self.grand_grand_daughter_name_called = True
- return ExtendedVirtualDaughter.name(self).prepend('Extended')
-
-class VirtualMethodsTest(unittest.TestCase):
- '''Test case for virtual methods'''
-
- def setUp(self):
- self.prefix_from_codeinjection = Str('Pimped')
-
- def tearDown(self):
- del self.prefix_from_codeinjection
-
- def testReimplementedVirtualMethod0(self):
- '''Test Python override of a virtual method with various different parameters is correctly called from C++.'''
- vm = VirtualMethods()
- evm = ExtendedVirtualMethods()
- pt = Point(1.1, 2.2)
- val = 4
- cpx = complex(3.3, 4.4)
- b = True
- result0 = vm.callVirtualMethod0(pt, val, cpx, b)
- result1 = evm.callVirtualMethod0(pt, val, cpx, b)
- self.assertEqual(result0 * -1.0, result1)
-
- def testRecursionOnModifiedVirtual(self):
- evm = ExtendedVirtualMethods()
- self.assertEqual(evm.recursionOnModifiedVirtual(''), 10)
- self.assertEqual(evm.callRecursionOnModifiedVirtual(''), 10)
-
- def testReimplementedVirtualMethodInheritedFromGrandParent(self):
- '''Test Python override of a virtual method inherited from a grand parent.'''
- original_name = 'Foo'
- evd = ExtendedVirtualDaughter(original_name)
-
- self.assertEqual(VirtualDaughter.name(evd), original_name)
- self.assertEqual(VirtualMethods.name(evd), original_name)
- self.assertFalse(evd.grand_daughter_name_called)
-
- name = evd.callName()
- self.assertTrue(evd.grand_daughter_name_called)
- self.assertEqual(evd.name().prepend(self.prefix_from_codeinjection), name)
-
- def testReimplementedVirtualMethodInheritedFromGrandGrandParent(self):
- '''Test Python override of a virtual method inherited from a grand grand parent.'''
- original_name = 'Foo'
- eevd = ExtendedExtendedVirtualDaughter(original_name)
-
- self.assertEqual(VirtualDaughter.name(eevd), original_name)
- self.assertEqual(VirtualMethods.name(eevd), original_name)
- self.assertFalse(eevd.grand_daughter_name_called)
- self.assertFalse(eevd.grand_grand_daughter_name_called)
-
- name = eevd.callName()
- self.assertTrue(eevd.grand_daughter_name_called)
- self.assertTrue(eevd.grand_grand_daughter_name_called)
- self.assertEqual(eevd.name().prepend(self.prefix_from_codeinjection), name)
-
-class PrettyErrorMessageTest(unittest.TestCase):
- def testIt(self):
- obj = ExtendedVirtualMethods()
- self.assertRaises(RuntimeWarning, obj.callStrListToStdList, StrList())
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/visibilitychange_test.py b/sources/shiboken2/tests/samplebinding/visibilitychange_test.py
deleted file mode 100644
index 7f723221a..000000000
--- a/sources/shiboken2/tests/samplebinding/visibilitychange_test.py
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import *
-
-class VisibilityChangeTest(unittest.TestCase):
-
- def testVisibilityChange(self):
- b1 = Base1()
- b1.publicMethod() # ok...
- d1 = MDerived1()
- self.assertRaises(TypeError, d1.publicMethod);
-
-if __name__ == '__main__':
- unittest.main()
-
-
diff --git a/sources/shiboken2/tests/samplebinding/voidholder_test.py b/sources/shiboken2/tests/samplebinding/voidholder_test.py
deleted file mode 100644
index 07b83347b..000000000
--- a/sources/shiboken2/tests/samplebinding/voidholder_test.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test case for a class that holds a void pointer.'''
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import VoidHolder, Point
-import shiboken2 as shiboken
-
-class VoidHolderTest(unittest.TestCase):
- '''Test case for void pointer manipulation.'''
-
- def testGetVoidPointerFromCppAndPutsOnVoidHolder(self):
- '''Passes a void pointer created in C++ to be kept by VoidHolder.'''
- voidptr = VoidHolder.gimmeMeSomeVoidPointer()
- voidholder = VoidHolder(voidptr)
- self.assertEqual(voidptr, voidholder.voidPointer())
-
- def testPassVoidPointerAsArgument(self):
- '''Passes a void pointer created in C++ as an argument to a function.'''
- voidptr = VoidHolder.gimmeMeSomeVoidPointer()
- voidHolder = VoidHolder()
- returnValue = voidHolder.takeVoidPointer(voidptr)
- self.assertEqual(returnValue, voidptr)
-
- def testPutRandomObjectInsideVoidHolder(self):
- '''Passes a C++ pointer for an object created in Python to be kept by VoidHolder.'''
- obj = Point(1, 2)
- voidholder = VoidHolder(obj)
- self.assertEqual(shiboken.getCppPointer(obj)[0], int(voidholder.voidPointer()))
-
- def testGetNoneObjectFromVoidHolder(self):
- '''A VoidHolder created without parameters returns a NULL pointer
- that should be converted to a Python None.'''
- voidholder = VoidHolder()
- self.assertEqual(voidholder.voidPointer(), None)
-
-if __name__ == '__main__':
- unittest.main()
-
diff --git a/sources/shiboken2/tests/samplebinding/weakref_test.py b/sources/shiboken2/tests/samplebinding/weakref_test.py
deleted file mode 100644
index a4a2dc461..000000000
--- a/sources/shiboken2/tests/samplebinding/weakref_test.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-'''Test weakref support'''
-
-import os
-import sys
-import unittest
-import weakref
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import ObjectType, PrivateDtor
-
-
-class WeakrefBasicTest(unittest.TestCase):
- '''Simple test case of using a weakref'''
-
- def setUp(self):
- self.called = False
-
- def cb(self, *args):
- self.called = True
-
- def testBasic(self):
- '''ObjectType weakref'''
- obj = ObjectType()
- ref = weakref.ref(obj, self.cb)
- del obj
- self.assertTrue(self.called)
-
- def testPrivateDtor(self):
- '''PrivateDtor weakref'''
- obj = PrivateDtor.instance()
- ref = weakref.ref(obj, self.cb)
- del obj
- self.assertTrue(self.called)
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/samplebinding/writableclassdict_test.py b/sources/shiboken2/tests/samplebinding/writableclassdict_test.py
deleted file mode 100644
index 58083b5d4..000000000
--- a/sources/shiboken2/tests/samplebinding/writableclassdict_test.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-from sample import Point
-
-class ExtPoint(Point): pass
-
-class TestWritableClassDict(unittest.TestCase):
- def testSetattrOnClass(self):
- setattr(Point, 'foo', 123)
- self.assertEqual(Point.foo, 123)
- pt = Point()
- self.assertEqual(pt.foo, 123)
-
- def testSetattrOnInheritingClass(self):
- setattr(Point, 'bar', 321)
- self.assertEqual(Point.bar, 321)
- self.assertEqual(ExtPoint.bar, 321)
- pt = ExtPoint()
- self.assertEqual(pt.bar, 321)
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/shiboken_paths.py b/sources/shiboken2/tests/shiboken_paths.py
deleted file mode 100644
index e5a8f2926..000000000
--- a/sources/shiboken2/tests/shiboken_paths.py
+++ /dev/null
@@ -1,106 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2020 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-
-import os
-import sys
-
-
-def get_dir_env_var(var_name):
- """Return a directory set by an environment variable"""
- result = os.environ.get(var_name)
- if not result:
- raise ValueError('{} is not set!'.format(var_name))
- if not os.path.isdir(result):
- raise ValueError('{} is not a directory!'.format(result))
- return result
-
-
-def get_build_dir():
- return get_dir_env_var('BUILD_DIR')
-
-
-def _prepend_path_var(var_name, paths):
- """Prepend additional paths to a path environment variable
- like PATH, LD_LIBRARY_PATH"""
- old_paths = os.environ.get(var_name)
- new_paths = os.pathsep.join(paths)
- if old_paths:
- new_paths += '{}{}'.format(os.pathsep, old_paths)
- os.environ[var_name] = new_paths
-
-
-def add_python_dirs(python_dirs):
- """Add directories to the Python path unless present."""
- for python_dir in python_dirs:
- if python_dir not in sys.path:
- sys.path.append(python_dir)
-
-
-def add_lib_dirs(lib_dirs):
- """Add directories to the platform's library path."""
- if sys.platform == 'win32':
- if sys.version_info >= (3, 8, 0):
- for lib_dir in lib_dirs:
- os.add_dll_directory(lib_dir)
- else:
- _prepend_path_var('PATH', lib_dirs)
- else:
- _prepend_path_var('LD_LIBRARY_PATH', lib_dirs)
-
-
-def shiboken_paths(include_shiboken_tests=False):
- """Return a tuple of python directories/lib directories to be set for
- using the shiboken2 module from the build directory or running the
- shiboken tests depending on a single environment variable BUILD_DIR
- pointing to the build directory."""
- src_dir = os.path.dirname(os.path.abspath(__file__))
- python_dirs = []
- if include_shiboken_tests:
- python_dirs.append(src_dir) # For py3kcompat
- shiboken_dir = os.path.join(get_build_dir(), 'shiboken2')
- python_dirs.append(os.path.join(shiboken_dir, 'shibokenmodule'))
- lib_dirs = [os.path.join(shiboken_dir, 'libshiboken')]
- if include_shiboken_tests:
- shiboken_test_dir = os.path.join(shiboken_dir, 'tests')
- for module in ['minimal', 'sample', 'smart', 'other']:
- module_dir = os.path.join(shiboken_test_dir, module + 'binding')
- python_dirs.append(module_dir)
- lib_dir = os.path.join(shiboken_test_dir, 'lib' + module)
- lib_dirs.append(lib_dir)
- return (python_dirs, lib_dirs)
-
-
-def init_paths():
- """Sets the correct import paths (Python modules and C++ library
- paths) for testing shiboken depending on a single
- environment variable BUILD_DIR pointing to the build
- directory."""
- paths = shiboken_paths(True)
- add_python_dirs(paths[0])
- add_lib_dirs(paths[1])
diff --git a/sources/shiboken2/tests/shiboken_test_helper.py b/sources/shiboken2/tests/shiboken_test_helper.py
deleted file mode 100644
index 793baf4ad..000000000
--- a/sources/shiboken2/tests/shiboken_test_helper.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2019 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-
-def objectFullname(t):
- # '__qualname__' for Python 2 does exist for PySide types, only.
- name = getattr(t, "__qualname__", t.__name__)
- module = t.__module__
- if module is None or module == str.__class__.__module__:
- return name
- else:
- return module + '.' + name
diff --git a/sources/shiboken2/tests/shibokenmodule/module_test.py b/sources/shiboken2/tests/shibokenmodule/module_test.py
deleted file mode 100644
index d0a8e6bf5..000000000
--- a/sources/shiboken2/tests/shibokenmodule/module_test.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-
-import shiboken2 as shiboken
-from sample import *
-
-class MultipleInherited (ObjectType, Point):
- def __init__(self):
- ObjectType.__init__(self)
- Point.__init__(self)
-
-class TestShiboken(unittest.TestCase):
- def testIsValid(self):
- self.assertTrue(shiboken.isValid(object()))
- self.assertTrue(shiboken.isValid(None))
-
- bb = BlackBox()
- item = ObjectType()
- ticket = bb.keepObjectType(item)
- bb.disposeObjectType(ticket)
- self.assertFalse(shiboken.isValid(item))
-
- def testWrapInstance(self):
- addr = ObjectType.createObjectType()
- obj = shiboken.wrapInstance(addr, ObjectType)
- self.assertFalse(shiboken.createdByPython(obj))
- obj.setObjectName("obj")
- self.assertEqual(obj.objectName(), "obj")
- self.assertEqual(addr, obj.identifier())
- self.assertFalse(shiboken.createdByPython(obj))
-
- # avoid mem leak =]
- bb = BlackBox()
- self.assertTrue(shiboken.createdByPython(bb))
- bb.disposeObjectType(bb.keepObjectType(obj))
-
- def testIsOwnedByPython(self):
- obj = ObjectType()
- self.assertTrue(shiboken.ownedByPython(obj))
- p = ObjectType()
- obj.setParent(p)
- self.assertFalse(shiboken.ownedByPython(obj))
-
- def testDump(self):
- """Just check if dump doesn't crash on certain use cases"""
- p = ObjectType()
- obj = ObjectType(p)
- obj2 = ObjectType(obj)
- obj3 = ObjectType(obj)
- self.assertEqual(shiboken.dump(None), "Ordinary Python type.")
- shiboken.dump(obj)
-
- model = ObjectModel(p)
- v = ObjectView(model, p)
- shiboken.dump(v)
-
- m = MultipleInherited()
- shiboken.dump(m)
- self.assertEqual(len(shiboken.getCppPointer(m)), 2)
-
- # Don't crash even after deleting an object
- shiboken.invalidate(obj)
- shiboken.dump(obj) # deleted
- shiboken.dump(p) # child deleted
- shiboken.dump(obj2) # parent deleted
-
- def testDelete(self):
- obj = ObjectType()
- child = ObjectType(obj)
- self.assertTrue(shiboken.isValid(obj))
- self.assertTrue(shiboken.isValid(child))
- # Note: this test doesn't assure that the object dtor was really called
- shiboken.delete(obj)
- self.assertFalse(shiboken.isValid(obj))
- self.assertFalse(shiboken.isValid(child))
-
- def testVersionAttr(self):
- self.assertEqual(type(shiboken.__version__), str)
- self.assertTrue(len(shiboken.__version__) >= 5)
- self.assertEqual(type(shiboken.__version_info__), tuple)
- self.assertEqual(len(shiboken.__version_info__), 5)
-
- def testAllWrappers(self):
- obj = ObjectType()
- self.assertTrue(obj in shiboken.getAllValidWrappers())
- shiboken.delete(obj)
- self.assertFalse(obj in shiboken.getAllValidWrappers())
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/smartbinding/CMakeLists.txt b/sources/shiboken2/tests/smartbinding/CMakeLists.txt
deleted file mode 100644
index 88a7bc059..000000000
--- a/sources/shiboken2/tests/smartbinding/CMakeLists.txt
+++ /dev/null
@@ -1,40 +0,0 @@
-project(smart)
-
-set(smart_TYPESYSTEM
-${CMAKE_CURRENT_SOURCE_DIR}/typesystem_smart.xml
-)
-
-set(smart_SRC
-${CMAKE_CURRENT_BINARY_DIR}/smart/smart_module_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/smart/obj_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/smart/integer_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/smart/sharedptr_obj_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/smart/sharedptr_integer_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/smart/registry_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/smart/smart_integer2_wrapper.cpp
-${CMAKE_CURRENT_BINARY_DIR}/smart/sharedptr_integer2_wrapper.cpp
-)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/smart-binding.txt.in"
- "${CMAKE_CURRENT_BINARY_DIR}/smart-binding.txt" @ONLY)
-
-add_custom_command(
-OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/mjb_rejected_classes.log"
-BYPRODUCTS ${smart_SRC}
-COMMAND shiboken2 --project-file=${CMAKE_CURRENT_BINARY_DIR}/smart-binding.txt ${GENERATOR_EXTRA_FLAGS}
-DEPENDS ${smart_TYPESYSTEM} ${CMAKE_CURRENT_SOURCE_DIR}/global.h shiboken2
-WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
-COMMENT "Running generator for 'smart' test binding..."
-)
-
-add_library(smart MODULE ${smart_SRC})
-target_include_directories(smart PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
-target_link_libraries(smart PUBLIC libsmart libshiboken)
-set_property(TARGET smart PROPERTY PREFIX "")
-set_property(TARGET smart PROPERTY OUTPUT_NAME "smart${PYTHON_EXTENSION_SUFFIX}")
-
-if(WIN32)
- set_property(TARGET smart PROPERTY SUFFIX ".pyd")
-endif()
-
-create_generator_target(smart)
diff --git a/sources/shiboken2/tests/smartbinding/global.h b/sources/shiboken2/tests/smartbinding/global.h
deleted file mode 100644
index 959859b40..000000000
--- a/sources/shiboken2/tests/smartbinding/global.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2017 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "smart.h"
diff --git a/sources/shiboken2/tests/smartbinding/smart-binding.txt.in b/sources/shiboken2/tests/smartbinding/smart-binding.txt.in
deleted file mode 100644
index 699f0bfe6..000000000
--- a/sources/shiboken2/tests/smartbinding/smart-binding.txt.in
+++ /dev/null
@@ -1,15 +0,0 @@
-[generator-project]
-
-generator-set = shiboken
-
-header-file = @CMAKE_CURRENT_SOURCE_DIR@/global.h
-typesystem-file = @smart_TYPESYSTEM@
-
-output-directory = @CMAKE_CURRENT_BINARY_DIR@
-
-include-path = @libsmart_SOURCE_DIR@
-
-typesystem-path = @CMAKE_CURRENT_SOURCE_DIR@
-
-enable-parent-ctor-heuristic
-use-isnull-as-nb_nonzero
diff --git a/sources/shiboken2/tests/smartbinding/smart_pointer_test.py b/sources/shiboken2/tests/smartbinding/smart_pointer_test.py
deleted file mode 100644
index 50b2120a2..000000000
--- a/sources/shiboken2/tests/smartbinding/smart_pointer_test.py
+++ /dev/null
@@ -1,219 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-#############################################################################
-##
-## Copyright (C) 2017 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is part of the test suite of Qt for Python.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
-
-from __future__ import print_function
-
-import gc
-import os
-import sys
-import unittest
-
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-from shiboken_paths import init_paths
-init_paths()
-from copy import copy
-from smart import Obj, Registry, Integer
-
-def objCount():
- return Registry.getInstance().countObjects()
-
-def integerCount():
- return Registry.getInstance().countIntegers()
-
-class SmartPointerTests(unittest.TestCase):
- def testObjSmartPointer(self):
- # Uncomment to see more debug info about creation of objects and ref counts.
- # Registry.getInstance().setShouldPrint(True)
-
- # Create Obj.
- o = Obj()
- self.assertEqual(objCount(), 1)
-
- # Create a shared pointer to an Obj together with an Obj.
- ptrToObj = o.giveSharedPtrToObj()
- self.assertEqual(objCount(), 2)
-
- # Delete the old Obj.
- o = None
- self.assertEqual(objCount(), 1)
-
- # Get a wrapper to the Obj inside of the shared pointer, object count should not change.
- obj = ptrToObj.data()
- self.assertEqual(objCount(), 1)
- obj.m_integer = 50
- self.assertEqual(obj.m_integer, 50)
-
- # Set and get a member value via shared pointer (like operator->).
- ptrToObj.m_integer = 100
- self.assertEqual(ptrToObj.m_integer, 100)
-
- # Get inner PyObject via shared pointer (like operator->) and set value in it.
- ptrToObj.m_internalInteger.m_int = 200
- self.assertEqual(ptrToObj.m_internalInteger.m_int, 200)
-
- # Pass smart pointer as argument to a method, return value is the value of m_integer of
- # passed Obj inside the smart pointer.
- result = ptrToObj.takeSharedPtrToObj(ptrToObj)
- self.assertEqual(result, 100)
-
- # Pass an Integer as an argument that returns itself.
- result = ptrToObj.takeInteger(ptrToObj.m_internalInteger)
- self.assertEqual(integerCount(), 2)
- result = None
- if integerCount() > 1:
- gc.collect()
- print('Running garbage collector for reference test', file=sys.stderr)
- self.assertEqual(integerCount(), 1)
-
- # Make a copy of the shared pointer, object count should not change.
- ptrToObj2 = copy(ptrToObj)
- self.assertEqual(objCount(), 1)
-
- # Delete the first shared pointer, object count should not change because the second
- # one still has a reference.
- del ptrToObj
- self.assertEqual(objCount(), 1)
-
- # Delete the second smart pointer, object should be deleted.
- del ptrToObj2
- self.assertEqual(objCount(), 0)
- self.assertEqual(integerCount(), 0)
-
- def testIntegerSmartPointer(self):
- # Uncomment to see more debug info about creation of objects and ref counts.
- # Registry.getInstance().setShouldPrint(True)
-
- # Create Obj.
- o = Obj()
- self.assertEqual(objCount(), 1)
-
- # Create a shared pointer to an Integer together with an Integer.
- ptrToInteger = o.giveSharedPtrToInteger()
- self.assertEqual(objCount(), 1)
- self.assertEqual(integerCount(), 2)
-
- # Get a wrapper to the Integer inside of the shared pointer, integer count should not
- # change.
- integer = ptrToInteger.data()
- self.assertEqual(integerCount(), 2)
- integer.m_int = 50
- self.assertEqual(integer.m_int, 50)
-
- # Set and get a member value via shared pointer (like operator->).
- ptrToInteger.setValue(150)
- self.assertEqual(ptrToInteger.value(), 150)
-
- # Set and get a member field via shared pointer (like operator->).
- ptrToInteger.m_int = 100
- self.assertEqual(ptrToInteger.m_int, 100)
-
- # Pass smart pointer as argument to a method, return value is the value of m_int of
- # passed Integer inside the smart pointer.
- result = o.takeSharedPtrToInteger(ptrToInteger)
- self.assertEqual(result, 100)
-
- # Make a copy of the shared pointer, integer count should not change.
- ptrToInteger2 = copy(ptrToInteger)
- self.assertEqual(integerCount(), 2)
-
- # Delete the first shared pointer, integer count should not change because the second
- # one still has a reference.
- del ptrToInteger
- self.assertEqual(integerCount(), 2)
-
- # Delete the second smart pointer, integer should be deleted.
- del ptrToInteger2
- self.assertEqual(objCount(), 1)
- self.assertEqual(integerCount(), 1)
-
- # Delete the original object which was used to create the integer.
- del o
- self.assertEqual(objCount(), 0)
- self.assertEqual(integerCount(), 0)
-
- def testConstIntegerSmartPointer(self):
- # Uncomment to see more debug info about creation of objects and ref counts.
- # Registry.getInstance().setShouldPrint(True)
-
- # Create Obj.
- o = Obj()
- ptrToConstInteger = o.giveSharedPtrToConstInteger()
- self.assertEqual(ptrToConstInteger.m_int, 456)
- result = o.takeSharedPtrToConstInteger(ptrToConstInteger)
- self.assertEqual(result, 456)
- self.assertEqual(ptrToConstInteger.value(), 456)
-
- def testSmartPointersWithNamespace(self):
- # Create the main object
- o = Obj()
- self.assertEqual(objCount(), 1)
-
- # Create a shared pointer to an Integer together with an Integer.
- ptrToInteger = o.giveSharedPtrToInteger2()
- self.assertEqual(objCount(), 1)
- self.assertEqual(integerCount(), 2)
-
- integer = ptrToInteger.data()
- self.assertTrue(integer)
-
- def testListOfSmartPointers(self):
- # Create the main object
- o = Obj()
-
- # Create a list of shared objects
- ptrToObjList = o.giveSharedPtrToObjList(10)
- self.assertEqual(len(ptrToObjList), 10)
- self.assertEqual(objCount(), 11)
-
- # Remove one from the list
- ptrToObjList.pop()
- self.assertEqual(len(ptrToObjList), 9)
- self.assertEqual(objCount(), 10)
-
- # clear and delete all objects in the list
- del ptrToObjList[:] # Python 2.7 lists have no clear method
- self.assertEqual(len(ptrToObjList), 0)
- self.assertEqual(objCount(), 1)
-
- def testInvalidParameter(self):
- # Create Obj.
- o = Obj()
- # Create a shared pointer to an Obj together with an Obj.
- ptrToObj = o.giveSharedPtrToObj()
- try:
- ptrToObj.typo
- self.assertFail()
- except AttributeError as error:
- self.assertEqual(error.args[0], "'smart.SharedPtr_Obj' object has no attribute 'typo'")
-
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/sources/shiboken2/tests/smartbinding/typesystem_smart.xml b/sources/shiboken2/tests/smartbinding/typesystem_smart.xml
deleted file mode 100644
index 8fb3082a0..000000000
--- a/sources/shiboken2/tests/smartbinding/typesystem_smart.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<typesystem package="smart">
- <primitive-type name="int" />
- <primitive-type name="char" />
- <primitive-type name="float" />
- <primitive-type name="bool" />
-
- <template name="cpplist_to_pylist_convertion">
- PyObject *%out = PyList_New(int(%in.size()));
- int idx = 0;
- for (const auto &amp;cppItem : %in)
- PyList_SET_ITEM(%out, idx++, %CONVERTTOPYTHON[%INTYPE_0](cppItem));
- return %out;
- </template>
- <template name="pyseq_to_cpplist_convertion">
- Shiboken::AutoDecRef seq(PySequence_Fast(%in, 0));
- for (int i = 0, size = PySequence_Fast_GET_SIZE(seq.object()); i &lt; size; ++i) {
- PyObject* pyItem = PySequence_Fast_GET_ITEM(seq.object(), i);
- %OUTTYPE_0 cppItem = %CONVERTTOCPP[%OUTTYPE_0](pyItem);
- %out.push_back(cppItem);
- }
- </template>
- <container-type name="std::vector" type="list">
- <include file-name="list" location="global"/>
- <conversion-rule>
- <native-to-target>
- <insert-template name="cpplist_to_pylist_convertion"/>
- </native-to-target>
- <target-to-native>
- <add-conversion type="PySequence">
- <insert-template name="pyseq_to_cpplist_convertion"/>
- </add-conversion>
- </target-to-native>
- </conversion-rule>
- </container-type>
-
-
- <!-- Used in tests to check what C++ objects are allocated. -->
- <object-type name="Registry" />
-
- <!-- Current limitation: shared pointer python objects can only be instantiated from API usage,
- like when they are returned as a result of a method, or passed as arguments. It is not
- possible to explicitly instantiate a new shared pointer in python e.g. o = SharedPtr_Foo()
- won't work.
- -->
- <smart-pointer-type name="SharedPtr" type="shared" getter="data" ref-count-method="useCount"
- instantiations="Integer,Smart::Integer2,Obj"/>
-
- <object-type name="Obj" />
- <value-type name="Integer" />
- <namespace-type name="Smart" generate="no">
- <value-type name="Integer2" />
- </namespace-type>
- <!-- Just used to silence the warnings that shiboken doens't know what to do with this type -->
- <custom-type name="RefData" />
-</typesystem>
diff --git a/sources/shiboken2/tests/sphinxtabletest.cpp b/sources/shiboken2/tests/sphinxtabletest.cpp
deleted file mode 100644
index 5ad56fb69..000000000
--- a/sources/shiboken2/tests/sphinxtabletest.cpp
+++ /dev/null
@@ -1,332 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "sphinxtabletest.h"
-#include "qtdocgenerator.h"
-#include <QtTest/QTest>
-#include <QDebug>
-
-QString SphinxTableTest::transformXml(const char* xml)
-{
- return QtXmlToSphinx(m_generator, xml).result();
-}
-
-void SphinxTableTest::setUp()
-{
- m_generator = new QtDocGenerator;
-}
-
-void SphinxTableTest::tearDown()
-{
- delete m_generator;
-}
-
-void SphinxTableTest::testEmptyString()
-{
- const char* xml = "";
- QCOMPARE(transformXml(xml), QString());
-}
-
-void SphinxTableTest::testSimpleTable()
-{
- const char* xml = "\
-<table>\
- <header>\
- <item>\
- <para>Header 1</para>\
- </item>\
- <item>\
- <para>Header 2</para>\
- </item>\
- </header>\
- <row>\
- <item>\
- <para>1 1</para>\
- </item>\
- <item>\
- <para>1 2</para>\
- </item>\
- </row>\
- <row>\
- <item>\
- <para>2 1</para>\
- </item>\
- <item>\
- <para>2 2</para>\
- </item>\
- </row>\
-</table>";
- QCOMPARE(transformXml(xml), QString("\
- +--------+--------+\n\
- |Header 1|Header 2|\n\
- +--------+--------+\n\
- |1 1 |1 2 |\n\
- +--------+--------+\n\
- |2 1 |2 2 |\n\
- +--------+--------+\n\
-\n"));
-}
-
-void SphinxTableTest::testColSpan()
-{
- const char* xml = "\
-<table>\
- <header>\
- <item>\
- <para>Header 1</para>\
- </item>\
- <item>\
- <para>Header 2</para>\
- </item>\
- </header>\
- <row>\
- <item colspan=\"2\">\
- <para>I'm a big text!</para>\
- </item>\
- </row>\
- <row>\
- <item>\
- <para>2 1</para>\
- </item>\
- <item>\
- <para>2 2</para>\
- </item>\
- </row>\
-</table>";
- QCOMPARE(transformXml(xml), QString("\
- +---------------+--------+\n\
- |Header 1 |Header 2|\n\
- +---------------+--------+\n\
- |I'm a big text! |\n\
- +---------------+--------+\n\
- |2 1 |2 2 |\n\
- +---------------+--------+\n\
-\n"));
-}
-
-
-void SphinxTableTest::testRowSpan()
-{
- const char* xml = "\
-<table>\
- <header>\
- <item>\
- <para>Header 1</para>\
- </item>\
- <item>\
- <para>Header 2</para>\
- </item>\
- </header>\
- <row>\
- <item rowspan=\"2\">\
- <para>1.1</para>\
- </item>\
- <item>\
- <para>1.2</para>\
- </item>\
- </row>\
- <row>\
- <item>\
- <para>2 2</para>\
- </item>\
- </row>\
-</table>";
- QCOMPARE(transformXml(xml), QString("\
- +--------+--------+\n\
- |Header 1|Header 2|\n\
- +--------+--------+\n\
- |1.1 |1.2 |\n\
- + +--------+\n\
- | |2 2 |\n\
- +--------+--------+\n\
-\n"));
-}
-
-
-void SphinxTableTest::testComplexTable()
-{
- const char* xml = "\
-<table>\
- <header>\
- <item>\
- <para>Header 1</para>\
- </item>\
- <item>\
- <para>Header 2</para>\
- </item>\
- <item>\
- <para>Header 3</para>\
- </item>\
- </header>\
- <row>\
- <item rowspan=\"2\">\
- <para>1.1</para>\
- </item>\
- <item colspan=\"2\">\
- <para>1.2</para>\
- </item>\
- </row>\
- <row>\
- <item>\
- <para>2 2</para>\
- </item>\
- <item>\
- <para>2 3</para>\
- </item>\
- </row>\
-</table>";
- QCOMPARE(transformXml(xml), QString("\
- +--------+--------+--------+\n\
- |Header 1|Header 2|Header 3|\n\
- +--------+--------+--------+\n\
- |1.1 |1.2 |\n\
- + +--------+--------+\n\
- | |2 2 |2 3 |\n\
- +--------+--------+--------+\n\
-\n"));
-}
-
-void SphinxTableTest::testRowSpan2()
-{
- const char* xml = "\
-<table>\
- <header>\
- <item><para>h1</para></item>\
- <item><para>h2</para></item>\
- <item><para>h3</para></item>\
- <item><para>h4</para></item>\
- </header>\
- <row>\
- <item rowspan=\"6\"><para>A</para></item>\
- <item rowspan=\"6\"><para>B</para></item>\
- <item><para>C</para></item>\
- <item><para>D</para></item>\
- </row>\
- <row>\
- <item><para>E</para></item>\
- <item><para>F</para></item>\
- </row>\
- <row>\
- <item><para>E</para></item>\
- <item><para>F</para></item>\
- </row>\
- <row>\
- <item><para>E</para></item>\
- <item><para>F</para></item>\
- </row>\
- <row>\
- <item><para>E</para></item>\
- <item><para>F</para></item>\
- </row>\
- <row>\
- <item><para>E</para></item>\
- <item><para>F</para></item>\
- </row>\
-</table>";
- QCOMPARE(transformXml(xml), QString("\
- +--+--+--+--+\n\
- |h1|h2|h3|h4|\n\
- +--+--+--+--+\n\
- |A |B |C |D |\n\
- + + +--+--+\n\
- | | |E |F |\n\
- + + +--+--+\n\
- | | |E |F |\n\
- + + +--+--+\n\
- | | |E |F |\n\
- + + +--+--+\n\
- | | |E |F |\n\
- + + +--+--+\n\
- | | |E |F |\n\
- +--+--+--+--+\n\
-\n"));
-}
-
-void SphinxTableTest::testBrokenTable()
-{
- const char* xml = "\
-<table>\
- <header>\
- <item>\
- <para>Header 1</para>\
- </item>\
- <item>\
- <para>Header 2</para>\
- </item>\
- </header>\
- <row>\
- <item>\
- <para>1.1</para>\
- </item>\
- <item>\
- <para>1.2</para>\
- </item>\
- </row>\
- <row>\
- <item colspan=\"2\">\
- <para>2 2</para>\
- </item>\
- <item>\
- <para>2 3</para>\
- </item>\
- <item>\
- <para>2 4</para>\
- </item>\
- <item>\
- <para>2 5</para>\
- </item>\
- </row>\
- <row>\
- <item>\
- <para>3 1</para>\
- </item>\
- <item>\
- <para>3 2</para>\
- </item>\
- <item>\
- <para>3 3</para>\
- </item>\
- </row>\
-</table>";
- QCOMPARE(transformXml(xml), QString("\
- +--------+------------+\n\
- |Header 1|Header 2 |\n\
- +--------+------------+\n\
- |1.1 |1.2 |\n\
- +--------+------------+\n\
- |2 2 2 3 2 4 2 5|\n\
- +--------+------------+\n\
- |3 1 |3 2 3 3 |\n\
- +--------+------------+\n\
-\n"));
-}
-
-
-QTEST_APPLESS_MAIN( SphinxTableTest )
-
-#include "sphinxtabletest.moc"
diff --git a/sources/shiboken2/tests/sphinxtabletest.h b/sources/shiboken2/tests/sphinxtabletest.h
deleted file mode 100644
index bba020207..000000000
--- a/sources/shiboken2/tests/sphinxtabletest.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef SPHINXTABLETEST_H
-#define SPHINXTABLETEST_H
-
-#include <QObject>
-
-class QtDocGenerator;
-class SphinxTableTest : public QObject {
- Q_OBJECT
-
-private slots:
- void setUp();
- void tearDown();
- void testEmptyString();
- void testSimpleTable();
- void testRowSpan();
- void testColSpan();
- void testComplexTable();
- void testRowSpan2();
- void testBrokenTable();
-private:
- QtDocGenerator* m_generator;
-
- QString transformXml(const char* xml);
-};
-
-#endif
diff --git a/sources/shiboken2/tests/test_generator/CMakeLists.txt b/sources/shiboken2/tests/test_generator/CMakeLists.txt
deleted file mode 100644
index da8cde6f8..000000000
--- a/sources/shiboken2/tests/test_generator/CMakeLists.txt
+++ /dev/null
@@ -1,68 +0,0 @@
-project(test_generator)
-
-set(dummy_generator_SRC dummygenerator.cpp)
-add_library(dummy_generator SHARED ${dummy_generator_SRC})
-target_link_libraries(dummy_generator ${APIEXTRACTOR_LIBRARY} ${QT_QTCORE_LIBRARY} genrunner)
-set_property(TARGET dummy_generator PROPERTY PREFIX "")
-
-add_executable(dummygenerator main.cpp)
-set(DUMMYGENERATOR_EXECUTABLE dummygenerator${generator_SUFFIX})
-set_target_properties(dummygenerator PROPERTIES OUTPUT_NAME ${DUMMYGENERATOR_EXECUTABLE})
-target_link_libraries(dummygenerator ${Qt${QT_MAJOR_VERSION}Core_LIBRARIES})
-
-configure_file(dummygentestconfig.h.in "${CMAKE_CURRENT_BINARY_DIR}/dummygentestconfig.h" @ONLY)
-
-get_filename_component(APIEXTRACTOR_LIBRARY_DIRS ${APIEXTRACTOR_LIBRARY} PATH)
-if(WIN32)
- set(PATH_SEP ";")
- find_program(APIEXTRACTOR_BINARY apiextractor.dll HINTS ${APIEXTRACTOR_LIBRARY_DIRS})
- get_filename_component(APIEXTRACTOR_BINARY_DIR ${APIEXTRACTOR_BINARY} PATH)
- set(APIEXTRACTOR_LIBRARY_DIRS "${APIEXTRACTOR_LIBRARY_DIRS}${PATH_SEP}${APIEXTRACTOR_BINARY_DIR}")
-else()
- set(PATH_SEP ":")
-endif()
-
-set(ENV_PATH "${generatorrunner_BINARY_DIR}${PATH_SEP}${CMAKE_CURRENT_BINARY_DIR}${PATH_SEP}$ENV{PATH}${PATH_SEP}${APIEXTRACTOR_LIBRARY_DIRS}")
-set(ENV_QT_PLUGIN_PATH "${CMAKE_CURRENT_BINARY_DIR}${PATH_SEP}$ENV{QT_PLUGIN_PATH}")
-if(WIN32)
- string(REPLACE "\\;" ";" ENV_PATH "${ENV_PATH}")
- string(REPLACE ";" "\\;" ENV_PATH "${ENV_PATH}")
- string(REPLACE "\\;" ";" ENV_QT_PLUGIN_PATH "${ENV_QT_PLUGIN_PATH}")
- string(REPLACE ";" "\\;" ENV_QT_PLUGIN_PATH "${ENV_QT_PLUGIN_PATH}")
-endif()
-
-macro(m_add_test testname)
- if(CMAKE_VERSION VERSION_LESS 2.8)
- add_test(${testname} ${CMAKE_COMMAND} -DTEST=${testname}
- -DWORKDIR=${CMAKE_CURRENT_BINARY_DIR}
- -DENV_PATH=${ENV_PATH} -DENV_QT_PLUGIN_PATH=${ENV_QT_PLUGIN_PATH}
- -P ${CMAKE_CURRENT_SOURCE_DIR}/run_test.cmake)
- else()
- add_test(${testname} ${testname})
- set_property(TEST ${testname} PROPERTY ENVIRONMENT "PATH=${ENV_PATH}" "QT_PLUGIN_PATH=${ENV_QT_PLUGIN_PATH}")
- endif()
-endmacro()
-
-macro(declare_test testname)
- qt4_automoc("${testname}.cpp")
- add_executable(${testname} "${testname}.cpp")
- include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR})
- target_link_libraries(${testname}
- ${QT_QTTEST_LIBRARY}
- ${QT_QTCORE_LIBRARY}
- ${Qt${QT_MAJOR_VERSION}Test_LIBRARIES}
- ${Qt${QT_MAJOR_VERSION}Core_LIBRARIES}
- )
- m_add_test(${testname})
-endmacro(declare_test testname)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/test_global.h"
- "${CMAKE_CURRENT_BINARY_DIR}/test_global.h" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/test_typesystem.xml"
- "${CMAKE_CURRENT_BINARY_DIR}/test_typesystem.xml" COPYONLY)
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/dummygentest-project.txt.in"
- "${CMAKE_CURRENT_BINARY_DIR}/dummygentest-project.txt" @ONLY)
-declare_test(dummygentest)
-
-add_dependencies(dummygenerator generatorrunner)
-
diff --git a/sources/shiboken2/tests/test_generator/dummygenerator.cpp b/sources/shiboken2/tests/test_generator/dummygenerator.cpp
deleted file mode 100644
index ef82c11c9..000000000
--- a/sources/shiboken2/tests/test_generator/dummygenerator.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <iostream>
-#include "dummygenerator.h"
-
-EXPORT_GENERATOR_PLUGIN(new DummyGenerator)
-
-using namespace std;
-
-QString
-DummyGenerator::fileNameForClass(const AbstractMetaClass* metaClass) const
-{
- return QString("%1_generated.txt").arg(metaClass->name().toLower());
-}
-
-void
-DummyGenerator::generateClass(QTextStream& s, const AbstractMetaClass* metaClass)
-{
- s << "// Generated code for class: " << qPrintable(metaClass->name()) << endl;
-}
-
-bool
-DummyGenerator::doSetup(const QMap<QString, QString>& args)
-{
- if (args.contains("dump-arguments") && !args["dump-arguments"].isEmpty()) {
- QFile logFile(args["dump-arguments"]);
- logFile.open(QIODevice::WriteOnly | QIODevice::Text);
- QTextStream out(&logFile);
- for (QMap<QString, QString>::const_iterator it = args.cbegin(), end = args.cend(); it != end; ++it) {
- const QString& key = it.key();
- if (key == "arg-1")
- out << "header-file";
- else if (key == "arg-2")
- out << "typesystem-file";
- else
- out << key;
- if (!args[key].isEmpty())
- out << " = " << args[key];
- out << endl;
- }
- }
- return true;
-}
-
diff --git a/sources/shiboken2/tests/test_generator/dummygenerator.h b/sources/shiboken2/tests/test_generator/dummygenerator.h
deleted file mode 100644
index e768e7643..000000000
--- a/sources/shiboken2/tests/test_generator/dummygenerator.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef DUMMYGENERATOR_H
-#define DUMMYGENERATOR_H
-
-#include "generator.h"
-
-class GENRUNNER_API DummyGenerator : public Generator
-{
-public:
- DummyGenerator() {}
- ~DummyGenerator() {}
- bool doSetup(const QMap<QString, QString>& args);
- const char* name() const { return "DummyGenerator"; }
-
-protected:
- void writeFunctionArguments(QTextStream&, const AbstractMetaFunction*, Options) const {}
- void writeArgumentNames(QTextStream&, const AbstractMetaFunction*, Options) const {}
- QString fileNameForClass(const AbstractMetaClass* metaClass) const;
- void generateClass(QTextStream& s, const AbstractMetaClass* metaClass);
- void finishGeneration() {}
-};
-
-#endif // DUMMYGENERATOR_H
diff --git a/sources/shiboken2/tests/test_generator/dummygentest-project.txt.in b/sources/shiboken2/tests/test_generator/dummygentest-project.txt.in
deleted file mode 100644
index 0a076d8bd..000000000
--- a/sources/shiboken2/tests/test_generator/dummygentest-project.txt.in
+++ /dev/null
@@ -1,20 +0,0 @@
-[generator-project]
-
-generator-set = dummy
-header-file = @CMAKE_CURRENT_BINARY_DIR@/test_global.h
-typesystem-file = @CMAKE_CURRENT_BINARY_DIR@/test_typesystem.xml
-output-directory = /tmp/output
-
-dump-arguments = @CMAKE_CURRENT_BINARY_DIR@/dummygen-args.log
-
-include-path = /include/path/location1
-include-path = /include/path/location2
-
-typesystem-path = /typesystem/path/location1
-typesystem-path = /typesystem/path/location2
-
-api-version = 1.2.3
-debug = sparse
-
-no-suppress-warnings
-
diff --git a/sources/shiboken2/tests/test_generator/dummygentest.cpp b/sources/shiboken2/tests/test_generator/dummygentest.cpp
deleted file mode 100644
index c09cdfb82..000000000
--- a/sources/shiboken2/tests/test_generator/dummygentest.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "dummygentest.h"
-#include "dummygenerator.h"
-#include "dummygentestconfig.h"
-#include <QTemporaryFile>
-#include <QtTest/QTest>
-#include <QProcess>
-
-#define GENERATED_CONTENTS "// Generated code for class: Dummy"
-
-void DummyGenTest::initTestCase()
-{
- int argc = 0;
- char* argv[] = {NULL};
- QCoreApplication app(argc, argv);
- workDir = QDir::currentPath();
-
- headerFilePath = workDir + "/test_global.h";
- typesystemFilePath = workDir + "/test_typesystem.xml";
- projectFilePath = workDir + "/dummygentest-project.txt";
- generatedFilePath = QString("%1/dummy/dummy_generated.txt").arg(QDir::tempPath());
-}
-
-void DummyGenTest::testCallGenRunnerWithFullPathToDummyGenModule()
-{
- QStringList args;
- args.append("--generator-set=" DUMMYGENERATOR_BINARY_DIR "/dummy_generator" MODULE_EXTENSION);
- args.append(QString("--output-directory=%1").arg(QDir::tempPath()));
- args.append(headerFilePath);
- args.append(typesystemFilePath);
- int result = QProcess::execute("generatorrunner", args);
- QCOMPARE(result, 0);
-
- QFile generatedFile(generatedFilePath);
- generatedFile.open(QIODevice::ReadOnly);
- QCOMPARE(generatedFile.readAll().trimmed(), QByteArray(GENERATED_CONTENTS).trimmed());
- generatedFile.close();
-
- QVERIFY(generatedFile.remove());
-}
-
-void DummyGenTest::testCallGenRunnerWithNameOfDummyGenModule()
-{
- QStringList args;
- args.append("--generator-set=dummy");
- args.append(QString("--output-directory=%1").arg(QDir::tempPath()));
- args.append(headerFilePath);
- args.append(typesystemFilePath);
- int result = QProcess::execute("generatorrunner", args);
- QCOMPARE(result, 0);
-
- QFile generatedFile(generatedFilePath);
- generatedFile.open(QIODevice::ReadOnly);
- QCOMPARE(generatedFile.readAll().trimmed(), QByteArray(GENERATED_CONTENTS).trimmed());
- generatedFile.close();
-
- QVERIFY(generatedFile.remove());
-}
-
-void DummyGenTest::testCallDummyGeneratorExecutable()
-{
- QStringList args;
- args.append(QString("--output-directory=%1").arg(QDir::tempPath()));
- args.append(headerFilePath);
- args.append(typesystemFilePath);
- int result = QProcess::execute(DUMMYGENERATOR_BINARY, args);
- QCOMPARE(result, 0);
-
- QFile generatedFile(generatedFilePath);
- generatedFile.open(QIODevice::ReadOnly);
- QCOMPARE(generatedFile.readAll().trimmed(), QByteArray(GENERATED_CONTENTS).trimmed());
- generatedFile.close();
-
- QVERIFY(generatedFile.remove());
-}
-
-void DummyGenTest::testProjectFileArgumentsReading()
-{
- QStringList args(QString("--project-file=%1/dummygentest-project.txt").arg(workDir));
- int result = QProcess::execute("generatorrunner", args);
- QCOMPARE(result, 0);
-
- QFile logFile(workDir + "/dummygen-args.log");
- logFile.open(QIODevice::ReadOnly);
- QStringList logContents;
- while (!logFile.atEnd())
- logContents << logFile.readLine().trimmed();
- logContents.sort();
- QCOMPARE(logContents[0], QString("api-version = 1.2.3"));
- QCOMPARE(logContents[1], QString("debug = sparse"));
- QVERIFY(logContents[2].startsWith("dump-arguments = "));
- QVERIFY(logContents[2].endsWith("dummygen-args.log"));
- QCOMPARE(logContents[3], QString("generator-set = dummy"));
- QVERIFY(logContents[4].startsWith("header-file = "));
- QVERIFY(logContents[4].endsWith("test_global.h"));
- QCOMPARE(logContents[5],
- QDir::toNativeSeparators(QString("include-paths = /include/path/location1%1/include/path/location2").arg(PATH_SPLITTER)));
- QCOMPARE(logContents[6], QString("no-suppress-warnings"));
- QCOMPARE(logContents[7], QString("output-directory = /tmp/output"));
- QVERIFY(logContents[8].startsWith("project-file = "));
- QVERIFY(logContents[8].endsWith("dummygentest-project.txt"));
- QVERIFY(logContents[9].startsWith("typesystem-file = "));
- QVERIFY(logContents[9].endsWith("test_typesystem.xml"));
- QCOMPARE(logContents[10],
- QDir::toNativeSeparators(QString("typesystem-paths = /typesystem/path/location1%1/typesystem/path/location2").arg(PATH_SPLITTER)));
-}
-
-QTEST_APPLESS_MAIN(DummyGenTest)
-
-#include "dummygentest.moc"
-
diff --git a/sources/shiboken2/tests/test_generator/dummygentest.h b/sources/shiboken2/tests/test_generator/dummygentest.h
deleted file mode 100644
index 78bae1d52..000000000
--- a/sources/shiboken2/tests/test_generator/dummygentest.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef DUMMYGENTABLETEST_H
-#define DUMMYGENTABLETEST_H
-
-#include <QObject>
-
-class DummyGenerator;
-
-class DummyGenTest : public QObject
-{
- Q_OBJECT
-
-private:
- QString workDir;
- QString headerFilePath;
- QString typesystemFilePath;
- QString generatedFilePath;
- QString projectFilePath;
-
-private slots:
- void initTestCase();
- void testCallGenRunnerWithFullPathToDummyGenModule();
- void testCallGenRunnerWithNameOfDummyGenModule();
- void testCallDummyGeneratorExecutable();
- void testProjectFileArgumentsReading();
-};
-
-#endif
-
diff --git a/sources/shiboken2/tests/test_generator/dummygentestconfig.h.in b/sources/shiboken2/tests/test_generator/dummygentestconfig.h.in
deleted file mode 100644
index 9da17dcd3..000000000
--- a/sources/shiboken2/tests/test_generator/dummygentestconfig.h.in
+++ /dev/null
@@ -1,15 +0,0 @@
-#ifndef DUMMYGENTESTCONFIG_H
-#define DUMMYGENTESTCONFIG_H
-
-#define MODULE_EXTENSION "@CMAKE_SHARED_LIBRARY_SUFFIX@"
-#define DUMMYGENERATOR_BINARY "@DUMMYGENERATOR_EXECUTABLE@"
-#define DUMMYGENERATOR_BINARY_DIR "@CMAKE_CURRENT_BINARY_DIR@"
-
-#ifdef _WINDOWS
- #define PATH_SPLITTER ";"
-#else
- #define PATH_SPLITTER ":"
-#endif
-
-#endif // DUMMYGENTESTCONFIG_H
-
diff --git a/sources/shiboken2/tests/test_generator/main.cpp b/sources/shiboken2/tests/test_generator/main.cpp
deleted file mode 100644
index f928b4d2c..000000000
--- a/sources/shiboken2/tests/test_generator/main.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of Qt for Python.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtCore>
-
-int main(int argc, char *argv[])
-{
- QStringList args;
- args.append("--generator-set=dummy");
- for (int i = 1; i < argc; i++)
- args.append(argv[i]);
- return QProcess::execute("generatorrunner", args);
-}
-
diff --git a/sources/shiboken2/tests/test_generator/run_test.cmake b/sources/shiboken2/tests/test_generator/run_test.cmake
deleted file mode 100644
index 34a821d80..000000000
--- a/sources/shiboken2/tests/test_generator/run_test.cmake
+++ /dev/null
@@ -1,11 +0,0 @@
-# The tests are run through this script due to a limitation
-# on versions of CMake lesser than 2.8, that prevent setting
-# environment variables for tests from working.
-
-set(ENV{PATH} "${ENV_PATH}")
-set(ENV{QT_PLUGIN_PATH} "${ENV_QT_PLUGIN_PATH}")
-execute_process(COMMAND ${TEST} WORKING_DIRECTORY "${WORKDIR}" RESULT_VARIABLE OK)
-
-if(NOT OK EQUAL 0)
- message(SEND_ERROR "${TEST} failed!")
-endif()
diff --git a/sources/shiboken2/tests/test_generator/test_global.h b/sources/shiboken2/tests/test_generator/test_global.h
deleted file mode 100644
index 6a95200cf..000000000
--- a/sources/shiboken2/tests/test_generator/test_global.h
+++ /dev/null
@@ -1 +0,0 @@
-struct Dummy {};
diff --git a/sources/shiboken2/tests/test_generator/test_typesystem.xml b/sources/shiboken2/tests/test_generator/test_typesystem.xml
deleted file mode 100644
index c19a4e95e..000000000
--- a/sources/shiboken2/tests/test_generator/test_typesystem.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-<typesystem package='dummy'>
- <value-type name='Dummy'/>
-</typesystem>